1
0

test.cc 700 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966
  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. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  398. // were received, into one list. Headers preserves that order, so the answer
  399. // is decided by the last coding of the last line and the order the lines
  400. // arrived in is significant.
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  403. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  404. // The split can fall anywhere in the list.
  405. EXPECT_TRUE(
  406. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  407. EXPECT_FALSE(
  408. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  409. // A trailing line naming no coding leaves the list ending in nothing, so it
  410. // must not inherit the chunked from the line before it.
  411. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  412. }
  413. // Forward declaration: in split builds split.py strips `inline` and moves the
  414. // definition into httplib.cc, so detail::base64_encode is not visible from the
  415. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  416. // in both header-only and split builds.
  417. namespace httplib {
  418. namespace detail {
  419. std::string base64_encode(const std::string &in);
  420. } // namespace detail
  421. } // namespace httplib
  422. TEST(Base64EncodeTest, KnownAnswers) {
  423. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  424. // where the accumulator's top bit is already set before the next shift.
  425. EXPECT_EQ("", detail::base64_encode(""));
  426. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  427. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  428. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  429. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  430. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  431. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  432. // High bytes keep the top bit set across several rounds.
  433. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  434. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  435. }
  436. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  441. string reservedCharacters = ";,/?:@&=+$";
  442. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  443. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  444. }
  445. TEST(ClientQueryOrder, PreserveOrder) {
  446. // This test reproduces Issue #2259: client may reorder query parameters
  447. // when sending a GET request. The expected behavior is that the client
  448. // preserves the original query string order when the caller supplied it
  449. // as part of the path.
  450. Server svr;
  451. svr.Get("/", [&](const Request &req, Response &res) {
  452. // Echo back the raw target so the test can assert ordering
  453. res.set_content(req.target, "text/plain");
  454. });
  455. std::thread t{[&] { svr.listen(HOST, PORT); }};
  456. auto se = detail::scope_exit([&] {
  457. svr.stop();
  458. t.join();
  459. ASSERT_FALSE(svr.is_running());
  460. });
  461. svr.wait_until_ready();
  462. Client cli(HOST, PORT);
  463. ASSERT_TRUE(cli.is_valid());
  464. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  465. auto res = cli.Get(original);
  466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  467. // Expect the echoed target to exactly match the original path (order
  468. // preserved)
  469. EXPECT_EQ(res->body, original);
  470. }
  471. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  472. string chineseCharacters = U8("中国語");
  473. string russianCharacters = U8("дом");
  474. string brazilianCharacters = U8("óculos");
  475. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  476. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  477. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  478. "%D0%B4%D0%BE%D0%BC");
  479. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  480. }
  481. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  482. string unescapedCharacters = "-_.!~*'()";
  483. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  484. }
  485. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  486. string reservedCharacters = ";,/?:@&=+$";
  487. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  488. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  489. }
  490. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  491. string chineseCharacters = U8("中国語");
  492. string russianCharacters = U8("дом");
  493. string brazilianCharacters = U8("óculos");
  494. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  495. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  496. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  497. "%D0%B4%D0%BE%D0%BC");
  498. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  499. }
  500. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  501. // Issue #2082 use case: encoding path component with ampersand
  502. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  503. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  504. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  505. }
  506. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  507. string unescapedCharacters = "-_.!~*'()";
  508. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  509. }
  510. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  511. string reservedCharacters = ";,/?:@&=+$#";
  512. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  513. }
  514. TEST(EncodeUriTest, TestUTF8Characters) {
  515. string chineseCharacters = U8("中国語");
  516. string russianCharacters = U8("дом");
  517. string brazilianCharacters = U8("óculos");
  518. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  519. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  520. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  521. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  522. }
  523. TEST(EncodeUriTest, TestCompleteUri) {
  524. string uri =
  525. "https://example.com/path/to/resource?query=value&param=test#fragment";
  526. EXPECT_EQ(
  527. httplib::encode_uri(uri),
  528. "https://example.com/path/to/resource?query=value&param=test#fragment");
  529. }
  530. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  531. string uri =
  532. "https://example.com/path with spaces/file name.html?q=hello world";
  533. EXPECT_EQ(httplib::encode_uri(uri),
  534. "https://example.com/path%20with%20spaces/"
  535. "file%20name.html?q=hello%20world");
  536. }
  537. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  538. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  539. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  540. }
  541. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  546. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  547. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  548. string encodedBrazilian = "%C3%B3culos";
  549. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  550. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  551. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  552. }
  553. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  554. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  556. "Piri Tommy Villiers - on & on");
  557. }
  558. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  559. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  560. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  561. }
  562. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  563. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  564. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  565. }
  566. TEST(DecodeUriTest, TestUTF8Characters) {
  567. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  568. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  569. string encodedBrazilian = "%C3%B3culos";
  570. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  571. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  572. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  573. }
  574. TEST(DecodeUriTest, TestCompleteUri) {
  575. string encodedUri = "https://example.com/path%20with%20spaces/"
  576. "file%20name.html?q=hello%20world";
  577. EXPECT_EQ(
  578. httplib::decode_uri(encodedUri),
  579. "https://example.com/path with spaces/file name.html?q=hello world");
  580. }
  581. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  582. string original =
  583. "https://example.com/path with spaces/file name.html?q=hello world";
  584. string encoded = httplib::encode_uri(original);
  585. string decoded = httplib::decode_uri(encoded);
  586. EXPECT_EQ(decoded, original);
  587. }
  588. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  589. string original = "Piri Tommy Villiers - on & on";
  590. string encoded = httplib::encode_uri_component(original);
  591. string decoded = httplib::decode_uri_component(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(TrimTests, TrimStringTests) {
  595. EXPECT_EQ("abc", detail::trim_copy("abc"));
  596. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  597. EXPECT_TRUE(detail::trim_copy("").empty());
  598. }
  599. TEST(AsciiTest, LocaleIndependentClassification) {
  600. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  601. // which consult the global C locale: std::isalnum(0xC5) can return true
  602. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  603. // helpers must classify every byte by the ASCII grammar alone.
  604. for (int i = 0; i < 256; i++) {
  605. auto c = static_cast<char>(i);
  606. auto is_digit = i >= '0' && i <= '9';
  607. auto is_upper = i >= 'A' && i <= 'Z';
  608. auto is_lower = i >= 'a' && i <= 'z';
  609. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  610. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  611. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  612. << "byte " << i;
  613. }
  614. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  615. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  616. // Non-ASCII bytes must be percent-encoded, never passed through as
  617. // alphanumeric.
  618. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  619. }
  620. TEST(FromCharsTest, Double) {
  621. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  622. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  623. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  624. auto parse = [](const std::string &s, double &v) {
  625. return detail::from_chars(s.data(), s.data() + s.size(), v);
  626. };
  627. double v = -1.0;
  628. // Representative quality values.
  629. EXPECT_EQ(parse("0", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.0);
  631. EXPECT_EQ(parse("1", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 1.0);
  633. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.8);
  635. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.001);
  637. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. // A missing integer or fractional part is tolerated.
  640. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  641. EXPECT_DOUBLE_EQ(v, 0.5);
  642. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 5.0);
  644. // Values outside [0, 1] still parse; the caller range-checks them.
  645. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  646. EXPECT_DOUBLE_EQ(v, 123.456);
  647. // Stops at the first byte that is not part of the number and reports where.
  648. std::string trailing = "0.9, text/html";
  649. auto r = parse(trailing, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 0.9);
  652. EXPECT_EQ(*r.ptr, ',');
  653. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  654. // outright, and an 'e'/'E' simply ends the number.
  655. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  657. std::string exp_input = "1.5e3";
  658. r = parse(exp_input, v);
  659. EXPECT_EQ(r.ec, std::errc{});
  660. EXPECT_DOUBLE_EQ(v, 1.5);
  661. EXPECT_EQ(*r.ptr, 'e');
  662. // Invalid inputs.
  663. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  664. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  665. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  666. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  667. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  668. // Pathological but well-formed inputs must stay bounded (no overflow, no
  669. // out-of-bounds table access) and stay within [0, 1] for the caller.
  670. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  671. std::errc{});
  672. EXPECT_DOUBLE_EQ(v, 0.0);
  673. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  674. std::errc{});
  675. EXPECT_GE(v, 0.0);
  676. EXPECT_LE(v, 1.0);
  677. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  678. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  679. }
  680. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  681. // Simple case without quality values
  682. std::vector<std::string> result1;
  683. EXPECT_TRUE(detail::parse_accept_header(
  684. "text/html,application/json,text/plain", result1));
  685. EXPECT_EQ(result1.size(), 3U);
  686. EXPECT_EQ(result1[0], "text/html");
  687. EXPECT_EQ(result1[1], "application/json");
  688. EXPECT_EQ(result1[2], "text/plain");
  689. // With quality values
  690. std::vector<std::string> result2;
  691. EXPECT_TRUE(detail::parse_accept_header(
  692. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  693. EXPECT_EQ(result2.size(), 3U);
  694. EXPECT_EQ(result2[0], "application/json"); // highest q value
  695. EXPECT_EQ(result2[1], "text/html");
  696. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  697. }
  698. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  699. // Mixed with and without quality values
  700. std::vector<std::string> result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  703. EXPECT_EQ(result.size(), 3U);
  704. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  705. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  706. EXPECT_EQ(result[2], "application/json"); // q=0.5
  707. }
  708. TEST(ParseAcceptHeaderTest, EdgeCases) {
  709. // Empty header
  710. std::vector<std::string> empty_result;
  711. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  712. EXPECT_TRUE(empty_result.empty());
  713. // Single type
  714. std::vector<std::string> single_result;
  715. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  716. EXPECT_EQ(single_result.size(), 1U);
  717. EXPECT_EQ(single_result[0], "application/json");
  718. // Wildcard types
  719. std::vector<std::string> wildcard_result;
  720. EXPECT_TRUE(detail::parse_accept_header(
  721. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  722. EXPECT_EQ(wildcard_result.size(), 3U);
  723. EXPECT_EQ(wildcard_result[0], "application/json");
  724. EXPECT_EQ(wildcard_result[1], "text/*");
  725. EXPECT_EQ(wildcard_result[2], "*/*");
  726. }
  727. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  728. // Common browser Accept header
  729. std::vector<std::string> browser_result;
  730. EXPECT_TRUE(
  731. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  732. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  733. browser_result));
  734. EXPECT_EQ(browser_result.size(), 6U);
  735. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  736. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  737. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  738. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  739. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  740. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  741. // API client header
  742. std::vector<std::string> api_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  745. api_result));
  746. EXPECT_EQ(api_result.size(), 3U);
  747. EXPECT_EQ(api_result[0], "application/json");
  748. EXPECT_EQ(api_result[1], "application/xml");
  749. EXPECT_EQ(api_result[2], "text/plain");
  750. }
  751. TEST(ParseAcceptHeaderTest, SpecialCases) {
  752. // Quality value with 3 decimal places
  753. std::vector<std::string> decimal_result;
  754. EXPECT_TRUE(detail::parse_accept_header(
  755. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  756. EXPECT_EQ(decimal_result.size(), 2U);
  757. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  758. EXPECT_EQ(decimal_result[1], "text/html");
  759. // Zero quality (should still be included but with lowest priority)
  760. std::vector<std::string> zero_q_result;
  761. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  762. zero_q_result));
  763. EXPECT_EQ(zero_q_result.size(), 2U);
  764. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  765. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  766. // No spaces around commas
  767. std::vector<std::string> no_space_result;
  768. EXPECT_TRUE(detail::parse_accept_header(
  769. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  770. no_space_result));
  771. EXPECT_EQ(no_space_result.size(), 3U);
  772. EXPECT_EQ(no_space_result[0], "text/html");
  773. EXPECT_EQ(no_space_result[1], "application/json");
  774. EXPECT_EQ(no_space_result[2], "text/plain");
  775. }
  776. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  777. // Quality values always use '.' as the decimal separator, so parsing must
  778. // not depend on the process locale. An embedding application may have
  779. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  780. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  781. std::string saved = cur ? cur : "C";
  782. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  783. "fr_FR.UTF-8"};
  784. bool switched = false;
  785. for (const auto loc : comma_locales) {
  786. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  787. std::localeconv()->decimal_point[0] == ',') {
  788. switched = true;
  789. break;
  790. }
  791. }
  792. if (!switched) {
  793. std::setlocale(LC_NUMERIC, saved.c_str());
  794. GTEST_SKIP() << "no comma-decimal locale available on this host";
  795. }
  796. // The higher-weighted type appears later in the list, so a correct parse
  797. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  798. // sensitive parse reads both weights as 0 and leaves the original order.
  799. std::vector<std::string> result;
  800. EXPECT_TRUE(detail::parse_accept_header(
  801. "application/json;q=0.1,text/html;q=0.9", result));
  802. ASSERT_EQ(result.size(), 2U);
  803. EXPECT_EQ(result[0], "text/html");
  804. EXPECT_EQ(result[1], "application/json");
  805. std::setlocale(LC_NUMERIC, saved.c_str());
  806. }
  807. TEST(ParseAcceptHeaderTest, InvalidCases) {
  808. std::vector<std::string> result;
  809. // Invalid quality value (> 1.0)
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  812. // Invalid quality value (< 0.0)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  815. // Invalid quality value (not a number)
  816. EXPECT_FALSE(detail::parse_accept_header(
  817. "text/html;q=invalid,application/json", result));
  818. // Empty quality value
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=,application/json", result));
  821. // Invalid media type format (no slash and not wildcard)
  822. EXPECT_FALSE(
  823. detail::parse_accept_header("invalidtype,application/json", result));
  824. // Empty media type
  825. result.clear();
  826. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  827. // Only commas
  828. result.clear();
  829. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  830. // Valid cases should still work
  831. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  832. EXPECT_EQ(result.size(), 1U);
  833. EXPECT_EQ(result[0], "*/*");
  834. EXPECT_TRUE(detail::parse_accept_header("*", result));
  835. EXPECT_EQ(result.size(), 1U);
  836. EXPECT_EQ(result[0], "*");
  837. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "text/*");
  840. }
  841. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  842. Server svr;
  843. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  844. EXPECT_EQ(req.accept_content_types.size(), 3U);
  845. EXPECT_EQ(req.accept_content_types[0], "application/json");
  846. EXPECT_EQ(req.accept_content_types[1], "text/html");
  847. EXPECT_EQ(req.accept_content_types[2], "*/*");
  848. res.set_content("ok", "text/plain");
  849. });
  850. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  851. EXPECT_TRUE(false);
  852. res.set_content("bad request", "text/plain");
  853. });
  854. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  855. auto se = detail::scope_exit([&] {
  856. svr.stop();
  857. listen_thread.join();
  858. ASSERT_FALSE(svr.is_running());
  859. });
  860. svr.wait_until_ready();
  861. Client cli("localhost", PORT);
  862. {
  863. auto res = cli.Get(
  864. "/accept_ok",
  865. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  867. EXPECT_EQ(StatusCode::OK_200, res->status);
  868. }
  869. {
  870. auto res = cli.Get("/accept_bad_request",
  871. Headers{{"Accept", "text/html;q=abc,application/json"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  874. }
  875. }
  876. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  877. Server svr;
  878. svr.Get("/", [](const Request & /*req*/, Response &res) {
  879. res.set_content("ok", "text/plain");
  880. });
  881. std::atomic<int> start_count{0};
  882. std::atomic<bool> running_when_called{false};
  883. svr.set_start_handler([&]() {
  884. running_when_called = svr.is_running();
  885. start_count++;
  886. });
  887. auto port = svr.bind_to_any_port(HOST);
  888. std::thread t([&]() { svr.listen_after_bind(); });
  889. auto se = detail::scope_exit([&] {
  890. svr.stop();
  891. t.join();
  892. ASSERT_FALSE(svr.is_running());
  893. });
  894. svr.wait_until_ready();
  895. // A successful request proves the accept loop is running, which the start
  896. // handler precedes; so by now the handler must have run exactly once.
  897. Client cli(HOST, port);
  898. cli.set_connection_timeout(std::chrono::seconds(5));
  899. auto res = cli.Get("/");
  900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. EXPECT_EQ(1, start_count.load());
  903. EXPECT_TRUE(running_when_called.load());
  904. }
  905. TEST(DivideTest, DivideStringTests) {
  906. auto divide = [](const std::string &str, char d) {
  907. std::string lhs;
  908. std::string rhs;
  909. detail::divide(str, d,
  910. [&](const char *lhs_data, std::size_t lhs_size,
  911. const char *rhs_data, std::size_t rhs_size) {
  912. lhs.assign(lhs_data, lhs_size);
  913. rhs.assign(rhs_data, rhs_size);
  914. });
  915. return std::make_pair(std::move(lhs), std::move(rhs));
  916. };
  917. {
  918. const auto res = divide("", '=');
  919. EXPECT_EQ(res.first, "");
  920. EXPECT_EQ(res.second, "");
  921. }
  922. {
  923. const auto res = divide("=", '=');
  924. EXPECT_EQ(res.first, "");
  925. EXPECT_EQ(res.second, "");
  926. }
  927. {
  928. const auto res = divide(" ", '=');
  929. EXPECT_EQ(res.first, " ");
  930. EXPECT_EQ(res.second, "");
  931. }
  932. {
  933. const auto res = divide("a", '=');
  934. EXPECT_EQ(res.first, "a");
  935. EXPECT_EQ(res.second, "");
  936. }
  937. {
  938. const auto res = divide("a=", '=');
  939. EXPECT_EQ(res.first, "a");
  940. EXPECT_EQ(res.second, "");
  941. }
  942. {
  943. const auto res = divide("=b", '=');
  944. EXPECT_EQ(res.first, "");
  945. EXPECT_EQ(res.second, "b");
  946. }
  947. {
  948. const auto res = divide("a=b", '=');
  949. EXPECT_EQ(res.first, "a");
  950. EXPECT_EQ(res.second, "b");
  951. }
  952. {
  953. const auto res = divide("a=b=", '=');
  954. EXPECT_EQ(res.first, "a");
  955. EXPECT_EQ(res.second, "b=");
  956. }
  957. {
  958. const auto res = divide("a=b=c", '=');
  959. EXPECT_EQ(res.first, "a");
  960. EXPECT_EQ(res.second, "b=c");
  961. }
  962. }
  963. TEST(SplitTest, ParseQueryString) {
  964. string s = "key1=val1&key2=val2&key3=val3";
  965. Params dic;
  966. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  967. [&](const char *b, const char *e) {
  968. string key, val;
  969. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  970. if (key.empty()) {
  971. key.assign(b2, e2);
  972. } else {
  973. val.assign(b2, e2);
  974. }
  975. });
  976. dic.emplace(key, val);
  977. });
  978. EXPECT_EQ("val1", dic.find("key1")->second);
  979. EXPECT_EQ("val2", dic.find("key2")->second);
  980. EXPECT_EQ("val3", dic.find("key3")->second);
  981. }
  982. TEST(SplitTest, ParseInvalidQueryTests) {
  983. {
  984. string s = " ";
  985. Params dict;
  986. detail::parse_query_text(s, dict);
  987. EXPECT_TRUE(dict.empty());
  988. }
  989. {
  990. string s = " = =";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. }
  996. TEST(ParseQueryTest, ParseQueryString) {
  997. {
  998. std::string s = "key1=val1&key2=val2&key3=val3";
  999. Params dic;
  1000. detail::parse_query_text(s, dic);
  1001. EXPECT_EQ("val1", dic.find("key1")->second);
  1002. EXPECT_EQ("val2", dic.find("key2")->second);
  1003. EXPECT_EQ("val3", dic.find("key3")->second);
  1004. }
  1005. {
  1006. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1007. Params dic;
  1008. detail::parse_query_text(s, dic);
  1009. EXPECT_EQ("", dic.find("key1")->second);
  1010. EXPECT_EQ("val1", dic.find("key2")->second);
  1011. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1012. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1013. }
  1014. }
  1015. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1016. Params dic;
  1017. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1018. dic.emplace("key1", "val1");
  1019. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1020. dic.emplace("key2", "val2");
  1021. dic.emplace("key3", "val3");
  1022. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1023. }
  1024. // Joins every entry of a Headers or Params into "key=value " so a whole
  1025. // traversal can be compared in one assertion. Both are instantiations of the
  1026. // same insertion-ordered container, so one helper serves both.
  1027. template <typename Map> static std::string entries_to_string(const Map &m) {
  1028. std::string s;
  1029. for (const auto &entry : m) {
  1030. s += entry.first + "=" + entry.second + " ";
  1031. }
  1032. return s;
  1033. }
  1034. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1035. // Params used to be a std::multimap, which sorted by name and handed the
  1036. // caller's query back alphabetised. A client signing its query string could
  1037. // not reproduce the order it asked for.
  1038. Params dic;
  1039. dic.emplace("zulu", "1");
  1040. dic.emplace("alpha", "2");
  1041. dic.emplace("mike", "3");
  1042. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1043. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1044. }
  1045. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1046. Params dic;
  1047. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1048. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1049. }
  1050. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1051. Request req;
  1052. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1053. req.params);
  1054. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1055. EXPECT_EQ("first", req.get_param_value("tag"));
  1056. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1057. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1058. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1059. EXPECT_EQ("", req.get_param_value("tag", 3));
  1060. }
  1061. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1062. // Params shares its container with Headers, which matches field names
  1063. // case-insensitively. Parameter names must not pick that up.
  1064. Params dic;
  1065. dic.emplace("Key", "upper");
  1066. dic.emplace("key", "lower");
  1067. EXPECT_EQ(2U, dic.size());
  1068. EXPECT_EQ(1U, dic.count("Key"));
  1069. EXPECT_EQ(1U, dic.count("key"));
  1070. EXPECT_EQ("upper", dic.find("Key")->second);
  1071. EXPECT_EQ("lower", dic.find("key")->second);
  1072. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1073. }
  1074. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1075. Server svr;
  1076. std::string order;
  1077. svr.Get("/order", [&](const Request &req, Response &res) {
  1078. order = entries_to_string(req.params);
  1079. res.set_content("ok", "text/plain");
  1080. });
  1081. thread t = thread([&] { svr.listen(HOST, PORT); });
  1082. auto se = detail::scope_exit([&] {
  1083. svr.stop();
  1084. t.join();
  1085. ASSERT_FALSE(svr.is_running());
  1086. });
  1087. svr.wait_until_ready();
  1088. Client cli(HOST, PORT);
  1089. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1090. ASSERT_TRUE(res);
  1091. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1092. }
  1093. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1094. string content_type = "multipart/form-data; boundary=something";
  1095. string boundary;
  1096. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1097. EXPECT_TRUE(ret);
  1098. EXPECT_EQ(boundary, "something");
  1099. }
  1100. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1101. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1102. string boundary;
  1103. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1104. EXPECT_TRUE(ret);
  1105. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1106. }
  1107. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1108. string content_type =
  1109. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1110. string boundary;
  1111. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1112. EXPECT_TRUE(ret);
  1113. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1114. }
  1115. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1116. string content_type =
  1117. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1118. string boundary;
  1119. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1120. EXPECT_TRUE(ret);
  1121. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1122. }
  1123. TEST(GetHeaderValueTest, DefaultValue) {
  1124. Headers headers = {{"Dummy", "Dummy"}};
  1125. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1126. EXPECT_STREQ("text/plain", val);
  1127. }
  1128. TEST(GetHeaderValueTest, DefaultValueInt) {
  1129. Headers headers = {{"Dummy", "Dummy"}};
  1130. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1131. EXPECT_EQ(100ull, val);
  1132. }
  1133. TEST(GetHeaderValueTest, RegularValue) {
  1134. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1135. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1136. EXPECT_STREQ("text/html", val);
  1137. }
  1138. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1139. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1140. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1141. EXPECT_STREQ("text/html", val);
  1142. }
  1143. TEST(GetHeaderValueTest, SetContent) {
  1144. Response res;
  1145. res.set_content("html", "text/html");
  1146. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1147. res.set_content("text", "text/plain");
  1148. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1149. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1150. }
  1151. TEST(GetHeaderValueTest, RegularValueInt) {
  1152. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1153. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1154. EXPECT_EQ(100ull, val);
  1155. }
  1156. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1157. Headers headers = {{"Content-Length", "x"}};
  1158. auto is_invalid_value = false;
  1159. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1160. is_invalid_value);
  1161. EXPECT_EQ(0ull, val);
  1162. EXPECT_TRUE(is_invalid_value);
  1163. }
  1164. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1165. // An all-digit value that overflows size_t must be reported as invalid, not
  1166. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1167. // a large length to a small one on 32-bit builds, leaving the framing length
  1168. // wrong while is_invalid_value stayed false.
  1169. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1170. auto is_invalid_value = false;
  1171. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1172. is_invalid_value);
  1173. EXPECT_TRUE(is_invalid_value);
  1174. // A well-formed length is unaffected.
  1175. Headers ok = {{"Content-Length", "1234"}};
  1176. is_invalid_value = false;
  1177. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1178. is_invalid_value);
  1179. EXPECT_EQ(1234ull, val);
  1180. EXPECT_FALSE(is_invalid_value);
  1181. }
  1182. TEST(GetHeaderValueTest, Range) {
  1183. {
  1184. Headers headers = {make_range_header({{1, -1}})};
  1185. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1186. EXPECT_STREQ("bytes=1-", val);
  1187. }
  1188. {
  1189. Headers headers = {make_range_header({{-1, 1}})};
  1190. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1191. EXPECT_STREQ("bytes=-1", val);
  1192. }
  1193. {
  1194. Headers headers = {make_range_header({{1, 10}})};
  1195. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1196. EXPECT_STREQ("bytes=1-10", val);
  1197. }
  1198. {
  1199. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1200. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1201. EXPECT_STREQ("bytes=1-10, 100-", val);
  1202. }
  1203. {
  1204. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1205. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1206. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1207. }
  1208. {
  1209. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1210. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1211. EXPECT_STREQ("bytes=0-0, -1", val);
  1212. }
  1213. }
  1214. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1215. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1216. // to depend on the standard library (libstdc++ handed back duplicates in
  1217. // reverse insertion order, libc++ in insertion order).
  1218. Request req;
  1219. req.set_header("Accept-Encoding", "gzip");
  1220. req.set_header("Accept-Encoding", "deflate");
  1221. req.set_header("Accept-Encoding", "br");
  1222. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1223. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1224. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1225. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1226. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1227. }
  1228. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1229. Request req;
  1230. req.set_header("X-Test", "only");
  1231. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1232. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1233. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1234. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1235. }
  1236. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1237. Headers headers;
  1238. headers.emplace("Host", "example.com");
  1239. headers.emplace("Accept-Encoding", "gzip");
  1240. headers.emplace("User-Agent", "test");
  1241. headers.emplace("Accept-Encoding", "deflate");
  1242. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1243. "Accept-Encoding=deflate ",
  1244. entries_to_string(headers));
  1245. }
  1246. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1247. Headers headers = {{"Content-Type", "text/html"},
  1248. {"CONTENT-TYPE", "text/xml"}};
  1249. EXPECT_EQ(2U, headers.count("content-type"));
  1250. auto it = headers.find("content-type");
  1251. ASSERT_TRUE(it != headers.end());
  1252. EXPECT_EQ("text/html", it->second);
  1253. }
  1254. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1255. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1256. // drop only those fields and leave everything positioned between them.
  1257. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1258. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1259. auto rng = headers.equal_range("a");
  1260. headers.erase(rng.first, rng.second);
  1261. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1262. }
  1263. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1264. Headers headers = {
  1265. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1266. EXPECT_EQ(3U, headers.erase("A"));
  1267. EXPECT_EQ(0U, headers.count("A"));
  1268. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1269. }
  1270. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1271. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1272. headers.emplace_front("Host", "example.com");
  1273. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1274. entries_to_string(headers));
  1275. }
  1276. TEST(ParseHeaderValueTest, Range) {
  1277. {
  1278. Ranges ranges;
  1279. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1280. EXPECT_TRUE(ret);
  1281. EXPECT_EQ(1u, ranges.size());
  1282. EXPECT_EQ(1u, ranges[0].first);
  1283. EXPECT_EQ(-1, ranges[0].second);
  1284. }
  1285. {
  1286. Ranges ranges;
  1287. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1288. EXPECT_TRUE(ret);
  1289. EXPECT_EQ(1u, ranges.size());
  1290. EXPECT_EQ(-1, ranges[0].first);
  1291. EXPECT_EQ(1u, ranges[0].second);
  1292. }
  1293. {
  1294. Ranges ranges;
  1295. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1296. EXPECT_TRUE(ret);
  1297. EXPECT_EQ(1u, ranges.size());
  1298. EXPECT_EQ(1u, ranges[0].first);
  1299. EXPECT_EQ(10u, ranges[0].second);
  1300. }
  1301. {
  1302. Ranges ranges;
  1303. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1304. EXPECT_FALSE(ret);
  1305. }
  1306. {
  1307. Ranges ranges;
  1308. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1309. EXPECT_TRUE(ret);
  1310. EXPECT_EQ(2u, ranges.size());
  1311. EXPECT_EQ(1u, ranges[0].first);
  1312. EXPECT_EQ(10u, ranges[0].second);
  1313. EXPECT_EQ(100u, ranges[1].first);
  1314. EXPECT_EQ(-1, ranges[1].second);
  1315. }
  1316. {
  1317. Ranges ranges;
  1318. auto ret =
  1319. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1320. EXPECT_TRUE(ret);
  1321. EXPECT_EQ(3u, ranges.size());
  1322. EXPECT_EQ(1u, ranges[0].first);
  1323. EXPECT_EQ(10u, ranges[0].second);
  1324. EXPECT_EQ(100u, ranges[1].first);
  1325. EXPECT_EQ(200u, ranges[1].second);
  1326. EXPECT_EQ(300u, ranges[2].first);
  1327. EXPECT_EQ(400u, ranges[2].second);
  1328. }
  1329. {
  1330. Ranges ranges;
  1331. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1332. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1333. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1334. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1335. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1336. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1337. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1338. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1339. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1340. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1341. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1342. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1343. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1344. EXPECT_TRUE(ranges.empty());
  1345. }
  1346. }
  1347. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1348. Request req;
  1349. req.set_header("Accept-Encoding", "gzip");
  1350. Response res;
  1351. res.set_header("Content-Type", "text/plain");
  1352. auto ret = detail::encoding_type(req, res);
  1353. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1354. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1355. #else
  1356. EXPECT_TRUE(ret == detail::EncodingType::None);
  1357. #endif
  1358. }
  1359. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1360. Request req;
  1361. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1362. Response res;
  1363. res.set_header("Content-Type", "text/plain");
  1364. auto ret = detail::encoding_type(req, res);
  1365. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1366. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1367. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1368. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1369. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1370. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1371. #else
  1372. EXPECT_TRUE(ret == detail::EncodingType::None);
  1373. #endif
  1374. }
  1375. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1376. Request req;
  1377. req.set_header("Accept-Encoding",
  1378. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1379. Response res;
  1380. res.set_header("Content-Type", "text/plain");
  1381. auto ret = detail::encoding_type(req, res);
  1382. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1383. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1384. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1385. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1386. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1387. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1388. #else
  1389. EXPECT_TRUE(ret == detail::EncodingType::None);
  1390. #endif
  1391. }
  1392. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1393. // All supported encodings rejected with q=0 should return None
  1394. Request req;
  1395. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1396. Response res;
  1397. res.set_header("Content-Type", "text/plain");
  1398. auto ret = detail::encoding_type(req, res);
  1399. EXPECT_TRUE(ret == detail::EncodingType::None);
  1400. }
  1401. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1402. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1403. Request req;
  1404. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1405. Response res;
  1406. res.set_header("Content-Type", "text/plain");
  1407. auto ret = detail::encoding_type(req, res);
  1408. EXPECT_TRUE(ret == detail::EncodingType::None);
  1409. }
  1410. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1411. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1412. Request req;
  1413. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1414. Response res;
  1415. res.set_header("Content-Type", "text/plain");
  1416. auto ret = detail::encoding_type(req, res);
  1417. EXPECT_TRUE(ret == detail::EncodingType::None);
  1418. }
  1419. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1420. // RFC 7231: Accept-Encoding values are case-insensitive
  1421. Request req;
  1422. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1423. Response res;
  1424. res.set_header("Content-Type", "text/plain");
  1425. auto ret = detail::encoding_type(req, res);
  1426. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1427. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1428. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1429. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1430. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1431. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1432. #else
  1433. EXPECT_TRUE(ret == detail::EncodingType::None);
  1434. #endif
  1435. }
  1436. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1437. // q value should determine priority, not hardcoded order
  1438. Request req;
  1439. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1440. Response res;
  1441. res.set_header("Content-Type", "text/plain");
  1442. auto ret = detail::encoding_type(req, res);
  1443. // gzip has highest q=1.0, so it should be selected even though
  1444. // br and zstd are also supported
  1445. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1446. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1447. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1448. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1449. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1450. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1451. #else
  1452. EXPECT_TRUE(ret == detail::EncodingType::None);
  1453. #endif
  1454. }
  1455. TEST(BufferStreamTest, read) {
  1456. detail::BufferStream strm1;
  1457. Stream &strm = strm1;
  1458. EXPECT_EQ(5, strm.write("hello"));
  1459. char buf[512];
  1460. EXPECT_EQ(2, strm.read(buf, 2));
  1461. EXPECT_EQ('h', buf[0]);
  1462. EXPECT_EQ('e', buf[1]);
  1463. EXPECT_EQ(2, strm.read(buf, 2));
  1464. EXPECT_EQ('l', buf[0]);
  1465. EXPECT_EQ('l', buf[1]);
  1466. EXPECT_EQ(1, strm.read(buf, 1));
  1467. EXPECT_EQ('o', buf[0]);
  1468. EXPECT_EQ(0, strm.read(buf, 1));
  1469. }
  1470. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1471. auto host = "www.httpwatch.com";
  1472. auto ip = hosted_at(host);
  1473. EXPECT_EQ("23.96.13.243", ip);
  1474. std::vector<std::string> addrs;
  1475. hosted_at(host, addrs);
  1476. EXPECT_EQ(1u, addrs.size());
  1477. }
  1478. #if 0 // It depends on each test environment...
  1479. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1480. auto host = "www.youtube.com";
  1481. std::vector<std::string> addrs;
  1482. hosted_at(host, addrs);
  1483. EXPECT_EQ(20u, addrs.size());
  1484. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1485. EXPECT_TRUE(it != addrs.end());
  1486. }
  1487. #endif
  1488. class ChunkedEncodingTest : public ::testing::Test {
  1489. protected:
  1490. ChunkedEncodingTest()
  1491. : cli_(HOST, PORT)
  1492. #ifdef CPPHTTPLIB_SSL_ENABLED
  1493. ,
  1494. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1495. #endif
  1496. {
  1497. cli_.set_connection_timeout(2);
  1498. #ifdef CPPHTTPLIB_SSL_ENABLED
  1499. cli_.enable_server_certificate_verification(false);
  1500. #endif
  1501. }
  1502. virtual void SetUp() {
  1503. read_file("./image.jpg", image_data_);
  1504. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1505. res.set_content("Hello World!", "text/plain");
  1506. });
  1507. svr_.Get(
  1508. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1509. res.set_chunked_content_provider(
  1510. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1511. size_t remaining = image_data_.size() - offset;
  1512. if (remaining == 0) {
  1513. sink.done();
  1514. } else {
  1515. constexpr size_t CHUNK_SIZE = 1024;
  1516. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1517. sink.write(&image_data_[offset], send_size);
  1518. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1519. }
  1520. return true;
  1521. });
  1522. });
  1523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1524. svr_.wait_until_ready();
  1525. }
  1526. virtual void TearDown() {
  1527. svr_.stop();
  1528. if (!request_threads_.empty()) {
  1529. std::this_thread::sleep_for(std::chrono::seconds(1));
  1530. for (auto &t : request_threads_) {
  1531. t.join();
  1532. }
  1533. }
  1534. t_.join();
  1535. }
  1536. #ifdef CPPHTTPLIB_SSL_ENABLED
  1537. SSLClient cli_;
  1538. SSLServer svr_;
  1539. #else
  1540. Client cli_;
  1541. Server svr_;
  1542. #endif
  1543. thread t_;
  1544. std::vector<thread> request_threads_;
  1545. std::string image_data_;
  1546. };
  1547. TEST_F(ChunkedEncodingTest, NormalGet) {
  1548. auto res = cli_.Get("/chunked");
  1549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1550. std::string out;
  1551. read_file("./image.jpg", out);
  1552. EXPECT_EQ(StatusCode::OK_200, res->status);
  1553. EXPECT_EQ(out, res->body);
  1554. }
  1555. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1556. std::string body;
  1557. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1558. body.append(data, data_length);
  1559. return true;
  1560. });
  1561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1562. std::string out;
  1563. read_file("./image.jpg", out);
  1564. EXPECT_EQ(StatusCode::OK_200, res->status);
  1565. EXPECT_EQ(out, body);
  1566. }
  1567. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1568. std::string body;
  1569. auto res = cli_.Get(
  1570. "/chunked",
  1571. [&](const Response &response) {
  1572. EXPECT_EQ(StatusCode::OK_200, response.status);
  1573. return true;
  1574. },
  1575. [&](const char *data, size_t data_length) {
  1576. body.append(data, data_length);
  1577. return true;
  1578. });
  1579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1580. std::string out;
  1581. read_file("./image.jpg", out);
  1582. EXPECT_EQ(StatusCode::OK_200, res->status);
  1583. EXPECT_EQ(out, body);
  1584. }
  1585. TEST(RangeTest, FromHTTPBin_Online) {
  1586. auto host = "httpbingo.org";
  1587. auto path = std::string{"/range/32"};
  1588. #ifdef CPPHTTPLIB_SSL_ENABLED
  1589. auto port = 443;
  1590. SSLClient cli(host, port);
  1591. #else
  1592. auto port = 80;
  1593. Client cli(host, port);
  1594. #endif
  1595. cli.set_connection_timeout(5);
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1599. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1600. EXPECT_EQ(StatusCode::OK_200, res->status);
  1601. }
  1602. {
  1603. Headers headers = {make_range_header({{1, -1}})};
  1604. auto res = cli.Get(path, headers);
  1605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1606. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1608. }
  1609. {
  1610. Headers headers = {make_range_header({{1, 10}})};
  1611. auto res = cli.Get(path, headers);
  1612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1613. EXPECT_EQ("bcdefghijk", res->body);
  1614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1615. }
  1616. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1617. // entire resource, while the original httpbin returned 200. Both are
  1618. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1619. {
  1620. Headers headers = {make_range_header({{0, 31}})};
  1621. auto res = cli.Get(path, headers);
  1622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1623. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1624. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1625. res->status == StatusCode::PartialContent_206);
  1626. }
  1627. {
  1628. Headers headers = {make_range_header({{0, -1}})};
  1629. auto res = cli.Get(path, headers);
  1630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1631. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1632. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1633. res->status == StatusCode::PartialContent_206);
  1634. }
  1635. // go-httpbin returns 206 with clamped range for over-range requests,
  1636. // while the original httpbin returned 416. Both behaviors are observed
  1637. // in real servers, so we only verify the request succeeds.
  1638. {
  1639. Headers headers = {make_range_header({{0, 32}})};
  1640. auto res = cli.Get(path, headers);
  1641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1642. }
  1643. }
  1644. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1645. auto host = "unresolvableaddress.local";
  1646. auto path = std::string{"/"};
  1647. #ifdef CPPHTTPLIB_SSL_ENABLED
  1648. auto port = 443;
  1649. SSLClient cli(host, port);
  1650. #else
  1651. auto port = 80;
  1652. Client cli(host, port);
  1653. #endif
  1654. cli.set_connection_timeout(1);
  1655. {
  1656. auto res = cli.Get(path);
  1657. ASSERT_FALSE(res);
  1658. }
  1659. std::this_thread::sleep_for(std::chrono::seconds(8));
  1660. }
  1661. #if defined(__linux__) && defined(__GLIBC__) && \
  1662. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1663. // Forward declaration: in split builds split.py strips `inline` and moves the
  1664. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1665. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1666. // against the symbol in both header-only and split builds.
  1667. namespace httplib {
  1668. namespace detail {
  1669. int getaddrinfo_with_timeout(const char *node, const char *service,
  1670. const struct addrinfo *hints,
  1671. struct addrinfo **res, time_t timeout_sec);
  1672. } // namespace detail
  1673. } // namespace httplib
  1674. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1675. //
  1676. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1677. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1678. // gai_suspend() call hits the connection timeout the function calls
  1679. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1680. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1681. // still alive and still references the now-destroyed stack frame.
  1682. //
  1683. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1684. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1685. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1686. // and runs them in a container.
  1687. namespace {
  1688. bool should_run_issue_2431_tests() {
  1689. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1690. return v && *v && std::string(v) != "0";
  1691. }
  1692. std::string unique_unresolvable_host(int n) {
  1693. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1694. // glibc still asks the configured nameserver — which is exactly the path
  1695. // we want to exercise. A unique label per call avoids the resolver cache.
  1696. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1697. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1698. std::to_string(n) + ".invalid";
  1699. }
  1700. } // namespace
  1701. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1702. if (!should_run_issue_2431_tests()) {
  1703. GTEST_SKIP()
  1704. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1705. }
  1706. for (int i = 0; i < 8; ++i) {
  1707. struct addrinfo hints;
  1708. memset(&hints, 0, sizeof(hints));
  1709. hints.ai_family = AF_UNSPEC;
  1710. hints.ai_socktype = SOCK_STREAM;
  1711. auto host = unique_unresolvable_host(i);
  1712. struct addrinfo *result = nullptr;
  1713. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1714. &result, /*timeout_sec=*/1);
  1715. if (rc == 0 && result) { freeaddrinfo(result); }
  1716. }
  1717. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1718. // stack region they still believe holds their gaicb.
  1719. std::this_thread::sleep_for(std::chrono::seconds(3));
  1720. }
  1721. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1722. if (!should_run_issue_2431_tests()) {
  1723. GTEST_SKIP()
  1724. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1725. }
  1726. std::atomic<bool> stop{false};
  1727. std::vector<std::thread> threads;
  1728. for (int t = 0; t < 8; ++t) {
  1729. threads.emplace_back([t, &stop] {
  1730. int i = 0;
  1731. while (!stop.load(std::memory_order_relaxed)) {
  1732. struct addrinfo hints;
  1733. memset(&hints, 0, sizeof(hints));
  1734. hints.ai_family = AF_UNSPEC;
  1735. hints.ai_socktype = SOCK_STREAM;
  1736. auto host = unique_unresolvable_host(t * 100000 + i++);
  1737. struct addrinfo *result = nullptr;
  1738. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1739. &result, /*timeout_sec=*/1);
  1740. if (rc == 0 && result) { freeaddrinfo(result); }
  1741. }
  1742. });
  1743. }
  1744. std::this_thread::sleep_for(std::chrono::seconds(8));
  1745. stop.store(true, std::memory_order_relaxed);
  1746. for (auto &th : threads) {
  1747. th.join();
  1748. }
  1749. std::this_thread::sleep_for(std::chrono::seconds(3));
  1750. }
  1751. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1752. if (!should_run_issue_2431_tests()) {
  1753. GTEST_SKIP()
  1754. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1755. }
  1756. std::atomic<bool> stop{false};
  1757. std::vector<std::thread> threads;
  1758. for (int t = 0; t < 8; ++t) {
  1759. threads.emplace_back([t, &stop] {
  1760. int i = 0;
  1761. while (!stop.load(std::memory_order_relaxed)) {
  1762. auto host = unique_unresolvable_host(t * 100000 + i++);
  1763. Client cli(host, 80);
  1764. cli.set_connection_timeout(1, 0);
  1765. cli.set_read_timeout(1, 0);
  1766. cli.set_write_timeout(1, 0);
  1767. (void)cli.Get("/");
  1768. }
  1769. });
  1770. }
  1771. std::this_thread::sleep_for(std::chrono::seconds(8));
  1772. stop.store(true, std::memory_order_relaxed);
  1773. for (auto &th : threads) {
  1774. th.join();
  1775. }
  1776. std::this_thread::sleep_for(std::chrono::seconds(3));
  1777. }
  1778. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1779. TEST(ConnectionErrorTest, InvalidHost) {
  1780. auto host = "-abcde.com";
  1781. #ifdef CPPHTTPLIB_SSL_ENABLED
  1782. auto port = 443;
  1783. SSLClient cli(host, port);
  1784. #else
  1785. auto port = 80;
  1786. Client cli(host, port);
  1787. #endif
  1788. cli.set_connection_timeout(std::chrono::seconds(2));
  1789. auto res = cli.Get("/");
  1790. ASSERT_TRUE(!res);
  1791. EXPECT_EQ(Error::Connection, res.error());
  1792. }
  1793. TEST(ConnectionErrorTest, InvalidHost2) {
  1794. auto host = "httpcan.org/";
  1795. #ifdef CPPHTTPLIB_SSL_ENABLED
  1796. SSLClient cli(host);
  1797. #else
  1798. Client cli(host);
  1799. #endif
  1800. cli.set_connection_timeout(std::chrono::seconds(2));
  1801. auto res = cli.Get("/");
  1802. ASSERT_TRUE(!res);
  1803. EXPECT_EQ(Error::Connection, res.error());
  1804. }
  1805. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1806. auto host = "httpcan.org/";
  1807. #ifdef CPPHTTPLIB_SSL_ENABLED
  1808. SSLClient cli(host);
  1809. #else
  1810. Client cli(host);
  1811. #endif
  1812. cli.set_connection_timeout(std::chrono::seconds(2));
  1813. auto res = cli.Get("/");
  1814. ASSERT_TRUE(!res);
  1815. stringstream s;
  1816. s << "error code: " << res.error();
  1817. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1818. }
  1819. TEST(ConnectionErrorTest, InvalidPort) {
  1820. auto host = "localhost";
  1821. auto port = 44380;
  1822. #ifdef CPPHTTPLIB_SSL_ENABLED
  1823. SSLClient cli(host, port);
  1824. #else
  1825. Client cli(host, port);
  1826. #endif
  1827. cli.set_connection_timeout(std::chrono::seconds(2));
  1828. auto res = cli.Get("/");
  1829. ASSERT_TRUE(!res);
  1830. EXPECT_TRUE(Error::Connection == res.error() ||
  1831. Error::ConnectionTimeout == res.error());
  1832. }
  1833. TEST(ConnectionErrorTest, Timeout_Online) {
  1834. auto host = "google.com";
  1835. #ifdef CPPHTTPLIB_SSL_ENABLED
  1836. auto port = 44380;
  1837. SSLClient cli(host, port);
  1838. #else
  1839. auto port = 8080;
  1840. Client cli(host, port);
  1841. #endif
  1842. cli.set_connection_timeout(std::chrono::seconds(2));
  1843. // only probe one address type so that the error reason
  1844. // correlates to the timed-out IPv4, not the unsupported
  1845. // IPv6 connection attempt
  1846. cli.set_address_family(AF_INET);
  1847. auto res = cli.Get("/");
  1848. ASSERT_TRUE(!res);
  1849. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1850. }
  1851. TEST(CancelTest, NoCancel_Online) {
  1852. auto host = "httpbingo.org";
  1853. auto path = std::string{"/range/32"};
  1854. #ifdef CPPHTTPLIB_SSL_ENABLED
  1855. auto port = 443;
  1856. SSLClient cli(host, port);
  1857. #else
  1858. auto port = 80;
  1859. Client cli(host, port);
  1860. #endif
  1861. cli.set_connection_timeout(std::chrono::seconds(5));
  1862. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1864. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1865. EXPECT_EQ(StatusCode::OK_200, res->status);
  1866. }
  1867. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1868. // Use /bytes with a large payload so that the DownloadProgress callback
  1869. // (which only fires for Content-Length responses) is invoked before the
  1870. // entire body is received, giving cancellation a chance to fire.
  1871. auto host = "httpbingo.org";
  1872. auto path = std::string{"/bytes/524288"};
  1873. #ifdef CPPHTTPLIB_SSL_ENABLED
  1874. auto port = 443;
  1875. SSLClient cli(host, port);
  1876. #else
  1877. auto port = 80;
  1878. Client cli(host, port);
  1879. #endif
  1880. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1881. cli.set_connection_timeout(std::chrono::seconds(5));
  1882. ASSERT_TRUE(!res);
  1883. EXPECT_EQ(Error::Canceled, res.error());
  1884. }
  1885. TEST(CancelTest, WithCancelLargePayload_Online) {
  1886. auto host = "httpbingo.org";
  1887. auto path = std::string{"/bytes/524288"};
  1888. #ifdef CPPHTTPLIB_SSL_ENABLED
  1889. auto port = 443;
  1890. SSLClient cli(host, port);
  1891. #else
  1892. auto port = 80;
  1893. Client cli(host, port);
  1894. #endif
  1895. cli.set_connection_timeout(std::chrono::seconds(5));
  1896. uint32_t count = 0;
  1897. auto res =
  1898. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1899. ASSERT_TRUE(!res);
  1900. EXPECT_EQ(Error::Canceled, res.error());
  1901. }
  1902. TEST(CancelTest, NoCancelPost) {
  1903. Server svr;
  1904. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1905. res.set_content("Hello World!", "text/plain");
  1906. });
  1907. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1908. auto se = detail::scope_exit([&] {
  1909. svr.stop();
  1910. thread.join();
  1911. ASSERT_FALSE(svr.is_running());
  1912. });
  1913. svr.wait_until_ready();
  1914. Client cli(HOST, PORT);
  1915. cli.set_connection_timeout(std::chrono::seconds(5));
  1916. auto res =
  1917. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1918. "application/json", [](uint64_t, uint64_t) { return true; });
  1919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1920. EXPECT_EQ("Hello World!", res->body);
  1921. EXPECT_EQ(StatusCode::OK_200, res->status);
  1922. }
  1923. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1924. Server svr;
  1925. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1926. res.set_content("Hello World!", "text/plain");
  1927. });
  1928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1929. auto se = detail::scope_exit([&] {
  1930. svr.stop();
  1931. thread.join();
  1932. ASSERT_FALSE(svr.is_running());
  1933. });
  1934. svr.wait_until_ready();
  1935. Client cli(HOST, PORT);
  1936. cli.set_connection_timeout(std::chrono::seconds(5));
  1937. auto res =
  1938. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1939. "application/json", [](uint64_t, uint64_t) { return false; });
  1940. ASSERT_TRUE(!res);
  1941. EXPECT_EQ(Error::Canceled, res.error());
  1942. }
  1943. TEST(CancelTest, WithCancelLargePayloadPost) {
  1944. Server svr;
  1945. svr.set_payload_max_length(200 * 1024 * 1024);
  1946. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1947. res.set_content(LARGE_DATA, "text/plain");
  1948. });
  1949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1950. auto se = detail::scope_exit([&] {
  1951. svr.stop();
  1952. thread.join();
  1953. ASSERT_FALSE(svr.is_running());
  1954. });
  1955. svr.wait_until_ready();
  1956. Client cli(HOST, PORT);
  1957. cli.set_payload_max_length(200 * 1024 * 1024);
  1958. cli.set_connection_timeout(std::chrono::seconds(5));
  1959. auto res =
  1960. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1961. "application/json", [](uint64_t, uint64_t) { return false; });
  1962. ASSERT_TRUE(!res);
  1963. EXPECT_EQ(Error::Canceled, res.error());
  1964. }
  1965. TEST(CancelTest, NoCancelPut) {
  1966. Server svr;
  1967. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1968. res.set_content("Hello World!", "text/plain");
  1969. });
  1970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1971. auto se = detail::scope_exit([&] {
  1972. svr.stop();
  1973. thread.join();
  1974. ASSERT_FALSE(svr.is_running());
  1975. });
  1976. svr.wait_until_ready();
  1977. Client cli(HOST, PORT);
  1978. cli.set_connection_timeout(std::chrono::seconds(5));
  1979. auto res =
  1980. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1981. "application/json", [](uint64_t, uint64_t) { return true; });
  1982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1983. EXPECT_EQ("Hello World!", res->body);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1987. Server svr;
  1988. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1989. res.set_content("Hello World!", "text/plain");
  1990. });
  1991. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1992. auto se = detail::scope_exit([&] {
  1993. svr.stop();
  1994. thread.join();
  1995. ASSERT_FALSE(svr.is_running());
  1996. });
  1997. svr.wait_until_ready();
  1998. Client cli(HOST, PORT);
  1999. cli.set_connection_timeout(std::chrono::seconds(5));
  2000. auto res =
  2001. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2002. "application/json", [](uint64_t, uint64_t) { return false; });
  2003. ASSERT_TRUE(!res);
  2004. EXPECT_EQ(Error::Canceled, res.error());
  2005. }
  2006. TEST(CancelTest, WithCancelLargePayloadPut) {
  2007. Server svr;
  2008. svr.set_payload_max_length(200 * 1024 * 1024);
  2009. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2010. res.set_content(LARGE_DATA, "text/plain");
  2011. });
  2012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. thread.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. Client cli(HOST, PORT);
  2020. cli.set_payload_max_length(200 * 1024 * 1024);
  2021. cli.set_connection_timeout(std::chrono::seconds(5));
  2022. auto res =
  2023. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2024. "application/json", [](uint64_t, uint64_t) { return false; });
  2025. ASSERT_TRUE(!res);
  2026. EXPECT_EQ(Error::Canceled, res.error());
  2027. }
  2028. TEST(CancelTest, NoCancelPatch) {
  2029. Server svr;
  2030. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2031. res.set_content("Hello World!", "text/plain");
  2032. });
  2033. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2034. auto se = detail::scope_exit([&] {
  2035. svr.stop();
  2036. thread.join();
  2037. ASSERT_FALSE(svr.is_running());
  2038. });
  2039. svr.wait_until_ready();
  2040. Client cli(HOST, PORT);
  2041. cli.set_connection_timeout(std::chrono::seconds(5));
  2042. auto res =
  2043. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2044. "application/json", [](uint64_t, uint64_t) { return true; });
  2045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2046. EXPECT_EQ("Hello World!", res->body);
  2047. EXPECT_EQ(StatusCode::OK_200, res->status);
  2048. }
  2049. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2050. Server svr;
  2051. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2052. res.set_content("Hello World!", "text/plain");
  2053. });
  2054. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. Client cli(HOST, PORT);
  2062. cli.set_connection_timeout(std::chrono::seconds(5));
  2063. auto res =
  2064. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2065. "application/json", [](uint64_t, uint64_t) { return false; });
  2066. ASSERT_TRUE(!res);
  2067. EXPECT_EQ(Error::Canceled, res.error());
  2068. }
  2069. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2070. Server svr;
  2071. svr.set_payload_max_length(200 * 1024 * 1024);
  2072. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2073. res.set_content(LARGE_DATA, "text/plain");
  2074. });
  2075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2076. auto se = detail::scope_exit([&] {
  2077. svr.stop();
  2078. thread.join();
  2079. ASSERT_FALSE(svr.is_running());
  2080. });
  2081. svr.wait_until_ready();
  2082. Client cli(HOST, PORT);
  2083. cli.set_payload_max_length(200 * 1024 * 1024);
  2084. cli.set_connection_timeout(std::chrono::seconds(5));
  2085. auto res =
  2086. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2087. "application/json", [](uint64_t, uint64_t) { return false; });
  2088. ASSERT_TRUE(!res);
  2089. EXPECT_EQ(Error::Canceled, res.error());
  2090. }
  2091. TEST(CancelTest, NoCancelDelete) {
  2092. Server svr;
  2093. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2094. res.set_content("Hello World!", "text/plain");
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. Client cli(HOST, PORT);
  2104. cli.set_connection_timeout(std::chrono::seconds(5));
  2105. auto res =
  2106. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2107. "application/json", [](uint64_t, uint64_t) { return true; });
  2108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2109. EXPECT_EQ("Hello World!", res->body);
  2110. EXPECT_EQ(StatusCode::OK_200, res->status);
  2111. }
  2112. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2113. Server svr;
  2114. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2115. res.set_content("Hello World!", "text/plain");
  2116. });
  2117. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2118. auto se = detail::scope_exit([&] {
  2119. svr.stop();
  2120. thread.join();
  2121. ASSERT_FALSE(svr.is_running());
  2122. });
  2123. svr.wait_until_ready();
  2124. Client cli(HOST, PORT);
  2125. cli.set_connection_timeout(std::chrono::seconds(5));
  2126. auto res =
  2127. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2128. "application/json", [](uint64_t, uint64_t) { return false; });
  2129. ASSERT_TRUE(!res);
  2130. EXPECT_EQ(Error::Canceled, res.error());
  2131. }
  2132. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2133. Server svr;
  2134. svr.set_payload_max_length(200 * 1024 * 1024);
  2135. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2136. res.set_content(LARGE_DATA, "text/plain");
  2137. });
  2138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2139. auto se = detail::scope_exit([&] {
  2140. svr.stop();
  2141. thread.join();
  2142. ASSERT_FALSE(svr.is_running());
  2143. });
  2144. svr.wait_until_ready();
  2145. Client cli(HOST, PORT);
  2146. cli.set_payload_max_length(200 * 1024 * 1024);
  2147. cli.set_connection_timeout(std::chrono::seconds(5));
  2148. auto res =
  2149. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2150. "application/json", [](uint64_t, uint64_t) { return false; });
  2151. ASSERT_TRUE(!res);
  2152. EXPECT_EQ(Error::Canceled, res.error());
  2153. }
  2154. static std::string remove_whitespace(const std::string &input) {
  2155. std::string output;
  2156. output.reserve(input.size());
  2157. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2158. [](unsigned char c) { return !std::isspace(c); });
  2159. return output;
  2160. }
  2161. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2162. auto host = "httpbingo.org";
  2163. auto path = std::string{"/basic-auth/hello/world"};
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. auto port = 443;
  2166. SSLClient cli(host, port);
  2167. #else
  2168. auto port = 80;
  2169. Client cli(host, port);
  2170. #endif
  2171. {
  2172. auto res = cli.Get(path);
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2175. }
  2176. {
  2177. auto res = cli.Get(
  2178. path, Headers{make_basic_authentication_header("hello", "world")});
  2179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2180. auto body = remove_whitespace(res->body);
  2181. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2182. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2183. EXPECT_EQ(StatusCode::OK_200, res->status);
  2184. }
  2185. {
  2186. cli.set_basic_auth("hello", "world");
  2187. auto res = cli.Get(path);
  2188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2189. auto body = remove_whitespace(res->body);
  2190. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2191. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2192. EXPECT_EQ(StatusCode::OK_200, res->status);
  2193. }
  2194. {
  2195. cli.set_basic_auth("hello", "bad");
  2196. auto res = cli.Get(path);
  2197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2198. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2199. }
  2200. {
  2201. cli.set_basic_auth("bad", "world");
  2202. auto res = cli.Get(path);
  2203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2204. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2205. }
  2206. }
  2207. #ifdef CPPHTTPLIB_SSL_ENABLED
  2208. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2209. auto host = "httpbingo.org";
  2210. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2211. auto paths = std::vector<std::string>{
  2212. "/digest-auth/auth/hello/world/MD5",
  2213. "/digest-auth/auth/hello/world/SHA-256",
  2214. };
  2215. auto port = 443;
  2216. SSLClient cli(host, port);
  2217. {
  2218. auto res = cli.Get(unauth_path);
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2221. }
  2222. {
  2223. cli.set_digest_auth("hello", "world");
  2224. for (const auto &path : paths) {
  2225. auto res = cli.Get(path.c_str());
  2226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2227. auto body = remove_whitespace(res->body);
  2228. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2229. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2230. EXPECT_EQ(StatusCode::OK_200, res->status);
  2231. }
  2232. cli.set_digest_auth("hello", "bad");
  2233. for (const auto &path : paths) {
  2234. auto res = cli.Get(path.c_str());
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2237. }
  2238. }
  2239. }
  2240. #endif
  2241. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2242. auto host = "google.com";
  2243. auto another_host = "example.com";
  2244. auto wrong_ip = "0.0.0.0";
  2245. #ifdef CPPHTTPLIB_SSL_ENABLED
  2246. SSLClient cli(host);
  2247. #else
  2248. Client cli(host);
  2249. #endif
  2250. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2251. auto res = cli.Get("/");
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2254. }
  2255. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2256. auto host = "google.com";
  2257. auto wrong_ip = "0.0.0.0";
  2258. #ifdef CPPHTTPLIB_SSL_ENABLED
  2259. SSLClient cli(host);
  2260. #else
  2261. Client cli(host);
  2262. #endif
  2263. cli.set_hostname_addr_map({{host, wrong_ip}});
  2264. auto res = cli.Get("/");
  2265. ASSERT_TRUE(!res);
  2266. EXPECT_EQ(Error::Connection, res.error());
  2267. }
  2268. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2269. // A mapped value that is not an IP literal must be resolved. "localhost"
  2270. // resolves from the hosts file, so this test needs no external DNS.
  2271. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2272. auto host = "target.invalid";
  2273. Server svr;
  2274. std::string received_host;
  2275. svr.Get("/hi", [&](const Request &req, Response &res) {
  2276. received_host = req.get_header_value("Host");
  2277. res.set_content("Hello World!", "text/plain");
  2278. });
  2279. auto port = svr.bind_to_any_port(HOST);
  2280. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2281. auto se = detail::scope_exit([&] {
  2282. svr.stop();
  2283. thread.join();
  2284. ASSERT_FALSE(svr.is_running());
  2285. });
  2286. svr.wait_until_ready();
  2287. Client cli(host, port);
  2288. cli.set_hostname_addr_map({{host, HOST}});
  2289. auto res = cli.Get("/hi");
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ(StatusCode::OK_200, res->status);
  2292. // The mapping only redirects the connection; the identity stays host_.
  2293. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2294. }
  2295. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2296. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2297. auto host = "target.invalid";
  2298. Server svr;
  2299. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2300. res.set_content("Hello World!", "text/plain");
  2301. });
  2302. auto port = svr.bind_to_any_port("127.0.0.1");
  2303. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2304. auto se = detail::scope_exit([&] {
  2305. svr.stop();
  2306. thread.join();
  2307. ASSERT_FALSE(svr.is_running());
  2308. });
  2309. svr.wait_until_ready();
  2310. Client cli(host, port);
  2311. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2312. auto res = cli.Get("/hi");
  2313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2314. EXPECT_EQ(StatusCode::OK_200, res->status);
  2315. }
  2316. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2317. // An empty mapped value must leave host_ as the connection target. Without
  2318. // that guard the empty value would become the host argument, getaddrinfo
  2319. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2320. // loopback - silently connecting somewhere the caller never asked for.
  2321. // The server listens on loopback, so such a fallback would succeed and is
  2322. // therefore observable as a failure of this test.
  2323. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2324. Server svr;
  2325. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2326. res.set_content("Hello World!", "text/plain");
  2327. });
  2328. auto port = svr.bind_to_any_port(HOST);
  2329. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(blackhole, port);
  2337. cli.set_hostname_addr_map({{blackhole, ""}});
  2338. cli.set_connection_timeout(1);
  2339. auto res = cli.Get("/hi");
  2340. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2341. }
  2342. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2343. auto host = "httpbingo.org";
  2344. auto path = std::string{"/absolute-redirect/3"};
  2345. #ifdef CPPHTTPLIB_SSL_ENABLED
  2346. SSLClient cli(host);
  2347. #else
  2348. Client cli(host);
  2349. #endif
  2350. cli.set_follow_location(true);
  2351. auto res = cli.Get(path);
  2352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2353. EXPECT_EQ(StatusCode::OK_200, res->status);
  2354. }
  2355. TEST(RedirectTest, Redirect_Online) {
  2356. auto host = "httpbingo.org";
  2357. auto path = std::string{"/redirect/3"};
  2358. #ifdef CPPHTTPLIB_SSL_ENABLED
  2359. SSLClient cli(host);
  2360. #else
  2361. Client cli(host);
  2362. #endif
  2363. cli.set_follow_location(true);
  2364. auto res = cli.Get(path);
  2365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2366. EXPECT_EQ(StatusCode::OK_200, res->status);
  2367. }
  2368. TEST(RelativeRedirectTest, Redirect_Online) {
  2369. auto host = "httpbingo.org";
  2370. auto path = std::string{"/relative-redirect/3"};
  2371. #ifdef CPPHTTPLIB_SSL_ENABLED
  2372. SSLClient cli(host);
  2373. #else
  2374. Client cli(host);
  2375. #endif
  2376. cli.set_follow_location(true);
  2377. auto res = cli.Get(path);
  2378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2379. EXPECT_EQ(StatusCode::OK_200, res->status);
  2380. }
  2381. TEST(TooManyRedirectTest, Redirect_Online) {
  2382. auto host = "httpbingo.org";
  2383. auto path = std::string{"/redirect/21"};
  2384. #ifdef CPPHTTPLIB_SSL_ENABLED
  2385. SSLClient cli(host);
  2386. #else
  2387. Client cli(host);
  2388. #endif
  2389. cli.set_follow_location(true);
  2390. auto res = cli.Get(path);
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2393. }
  2394. #ifdef CPPHTTPLIB_SSL_ENABLED
  2395. TEST(YahooRedirectTest, Redirect_Online) {
  2396. Client cli("yahoo.com");
  2397. auto res = cli.Get("/");
  2398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2399. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2400. cli.set_follow_location(true);
  2401. res = cli.Get("/");
  2402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2405. }
  2406. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2407. #define REDIR_HOST "httpbingo.org"
  2408. #define REDIR_PATH "/redirect-to"
  2409. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2410. SSLClient cli(REDIR_HOST);
  2411. cli.set_follow_location(true);
  2412. auto res =
  2413. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2415. EXPECT_EQ(StatusCode::OK_200, res->status);
  2416. }
  2417. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2418. SSLClient cli(REDIR_HOST);
  2419. cli.set_follow_location(true);
  2420. Params params;
  2421. params.emplace("url", "http://example.com");
  2422. params.emplace("status_code", "302");
  2423. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2425. EXPECT_EQ(StatusCode::OK_200, res->status);
  2426. }
  2427. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2428. SSLClient cli(REDIR_HOST);
  2429. cli.set_follow_location(true);
  2430. Params params;
  2431. params.emplace("url", "http://example.com");
  2432. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. }
  2436. TEST(UrlWithSpace, Redirect_Online) {
  2437. SSLClient cli("edge.forgecdn.net");
  2438. cli.set_follow_location(true);
  2439. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2441. EXPECT_EQ(StatusCode::OK_200, res->status);
  2442. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2443. }
  2444. #endif
  2445. #if !defined(_WIN32) && !defined(_WIN64)
  2446. TEST(ReceiveSignals, Signal) {
  2447. auto setupSignalHandlers = []() {
  2448. struct sigaction act;
  2449. sigemptyset(&act.sa_mask);
  2450. act.sa_flags = SA_SIGINFO;
  2451. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2452. switch (sig) {
  2453. case SIGINT:
  2454. default: break;
  2455. }
  2456. };
  2457. ::sigaction(SIGINT, &act, nullptr);
  2458. };
  2459. Server svr;
  2460. int port = 0;
  2461. auto thread = std::thread([&]() {
  2462. setupSignalHandlers();
  2463. port = svr.bind_to_any_port(HOST);
  2464. svr.listen_after_bind();
  2465. });
  2466. auto se = detail::scope_exit([&] {
  2467. svr.stop();
  2468. thread.join();
  2469. ASSERT_FALSE(svr.is_running());
  2470. });
  2471. svr.wait_until_ready();
  2472. ASSERT_TRUE(svr.is_running());
  2473. pthread_kill(thread.native_handle(), SIGINT);
  2474. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2475. ASSERT_TRUE(svr.is_running());
  2476. }
  2477. #endif
  2478. TEST(RedirectToDifferentPort, Redirect) {
  2479. Server svr1;
  2480. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2481. res.set_content("Hello World!", "text/plain");
  2482. });
  2483. int svr1_port = 0;
  2484. auto thread1 = std::thread([&]() {
  2485. svr1_port = svr1.bind_to_any_port(HOST);
  2486. svr1.listen_after_bind();
  2487. });
  2488. Server svr2;
  2489. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2490. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2491. });
  2492. int svr2_port = 0;
  2493. auto thread2 = std::thread([&]() {
  2494. svr2_port = svr2.bind_to_any_port(HOST);
  2495. svr2.listen_after_bind();
  2496. });
  2497. auto se = detail::scope_exit([&] {
  2498. svr2.stop();
  2499. thread2.join();
  2500. svr1.stop();
  2501. thread1.join();
  2502. ASSERT_FALSE(svr2.is_running());
  2503. ASSERT_FALSE(svr1.is_running());
  2504. });
  2505. svr1.wait_until_ready();
  2506. svr2.wait_until_ready();
  2507. Client cli("localhost", svr2_port);
  2508. cli.set_follow_location(true);
  2509. auto res = cli.Get("/2");
  2510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2511. EXPECT_EQ(StatusCode::OK_200, res->status);
  2512. EXPECT_EQ("Hello World!", res->body);
  2513. }
  2514. static void
  2515. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2516. Server svr1;
  2517. std::string captured_authorization;
  2518. svr1.Get("/target", [&](const Request &req, Response &res) {
  2519. captured_authorization = req.get_header_value("Authorization");
  2520. res.set_content("OK", "text/plain");
  2521. });
  2522. int svr1_port = 0;
  2523. auto thread1 = std::thread([&]() {
  2524. svr1_port = svr1.bind_to_any_port(HOST);
  2525. svr1.listen_after_bind();
  2526. });
  2527. Server svr2;
  2528. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2529. res.set_redirect(
  2530. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2531. });
  2532. int svr2_port = 0;
  2533. auto thread2 = std::thread([&]() {
  2534. svr2_port = svr2.bind_to_any_port(HOST);
  2535. svr2.listen_after_bind();
  2536. });
  2537. auto se = detail::scope_exit([&] {
  2538. svr2.stop();
  2539. thread2.join();
  2540. svr1.stop();
  2541. thread1.join();
  2542. ASSERT_FALSE(svr2.is_running());
  2543. ASSERT_FALSE(svr1.is_running());
  2544. });
  2545. svr1.wait_until_ready();
  2546. svr2.wait_until_ready();
  2547. Client cli("localhost", svr2_port);
  2548. cli.set_follow_location(true);
  2549. set_auth(cli);
  2550. auto res = cli.Get("/redir");
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ(StatusCode::OK_200, res->status);
  2553. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2554. EXPECT_TRUE(captured_authorization.empty());
  2555. }
  2556. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2557. TestDoNotForwardCredentialsOnRedirect(
  2558. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2559. }
  2560. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2561. TestDoNotForwardCredentialsOnRedirect(
  2562. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2563. }
  2564. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2565. Server svr1;
  2566. std::string captured_cookie;
  2567. bool target_hit = false;
  2568. svr1.Get("/target", [&](const Request &req, Response &res) {
  2569. captured_cookie = req.get_header_value("Cookie");
  2570. target_hit = true;
  2571. res.set_content("OK", "text/plain");
  2572. });
  2573. int svr1_port = 0;
  2574. auto thread1 = std::thread([&]() {
  2575. svr1_port = svr1.bind_to_any_port(HOST);
  2576. svr1.listen_after_bind();
  2577. });
  2578. Server svr2;
  2579. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2580. res.set_redirect(
  2581. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2582. });
  2583. int svr2_port = 0;
  2584. auto thread2 = std::thread([&]() {
  2585. svr2_port = svr2.bind_to_any_port(HOST);
  2586. svr2.listen_after_bind();
  2587. });
  2588. auto se = detail::scope_exit([&] {
  2589. svr2.stop();
  2590. thread2.join();
  2591. svr1.stop();
  2592. thread1.join();
  2593. ASSERT_FALSE(svr2.is_running());
  2594. ASSERT_FALSE(svr1.is_running());
  2595. });
  2596. svr1.wait_until_ready();
  2597. svr2.wait_until_ready();
  2598. Client cli("localhost", svr2_port);
  2599. cli.set_follow_location(true);
  2600. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2601. auto res = cli.Get("/redir", headers);
  2602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2603. EXPECT_EQ(StatusCode::OK_200, res->status);
  2604. EXPECT_TRUE(target_hit);
  2605. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2606. EXPECT_TRUE(captured_cookie.empty());
  2607. }
  2608. TEST(RedirectToSamePort, ForwardCookie) {
  2609. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2610. // header so that ordinary session flows keep working.
  2611. Server svr;
  2612. std::string captured_cookie;
  2613. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2614. res.set_redirect("/target", 302);
  2615. });
  2616. svr.Get("/target", [&](const Request &req, Response &res) {
  2617. captured_cookie = req.get_header_value("Cookie");
  2618. res.set_content("OK", "text/plain");
  2619. });
  2620. auto port = svr.bind_to_any_port(HOST);
  2621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2622. auto se = detail::scope_exit([&] {
  2623. svr.stop();
  2624. thread.join();
  2625. ASSERT_FALSE(svr.is_running());
  2626. });
  2627. svr.wait_until_ready();
  2628. Client cli(HOST, port);
  2629. cli.set_follow_location(true);
  2630. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2631. auto res = cli.Get("/redir", headers);
  2632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2635. }
  2636. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2637. Server svr;
  2638. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2639. // Port number that overflows int — should not crash
  2640. res.set_redirect("http://localhost:99999999999999999999/target");
  2641. });
  2642. auto port = svr.bind_to_any_port(HOST);
  2643. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, port);
  2651. cli.set_follow_location(true);
  2652. auto res = cli.Get("/redir");
  2653. // Should fail gracefully, not crash (no valid response due to bad port)
  2654. EXPECT_FALSE(res);
  2655. }
  2656. TEST(RedirectFromPageWithContent, Redirect) {
  2657. Server svr;
  2658. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content("___", "text/plain");
  2660. res.set_redirect("/2");
  2661. });
  2662. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2663. res.set_content("Hello World!", "text/plain");
  2664. });
  2665. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2666. auto se = detail::scope_exit([&] {
  2667. svr.stop();
  2668. th.join();
  2669. ASSERT_FALSE(svr.is_running());
  2670. });
  2671. svr.wait_until_ready();
  2672. {
  2673. Client cli("localhost", PORT);
  2674. cli.set_follow_location(true);
  2675. std::string body;
  2676. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2677. body.append(data, data_length);
  2678. return true;
  2679. });
  2680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2681. EXPECT_EQ(StatusCode::OK_200, res->status);
  2682. EXPECT_EQ("Hello World!", body);
  2683. }
  2684. {
  2685. Client cli("localhost", PORT);
  2686. std::string body;
  2687. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2688. body.append(data, data_length);
  2689. return true;
  2690. });
  2691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2692. EXPECT_EQ(StatusCode::Found_302, res->status);
  2693. EXPECT_EQ("___", body);
  2694. }
  2695. }
  2696. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2697. Server svr;
  2698. auto port_str = std::to_string(PORT);
  2699. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2700. auto expected_host = "[::1]:" + port_str;
  2701. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2702. res.set_content("___", "text/plain");
  2703. // res.set_redirect("/2");
  2704. res.set_redirect(redirect_url);
  2705. });
  2706. svr.Get("/2", [&](const Request &req, Response &res) {
  2707. auto host_header = req.headers.find("Host");
  2708. ASSERT_TRUE(host_header != req.headers.end());
  2709. EXPECT_EQ(expected_host, host_header->second);
  2710. res.set_content("Hello World!", "text/plain");
  2711. });
  2712. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. th.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2719. // actually starts anything, so the condition !svr.is_running() will
  2720. // always remain true, and the loop never stops.
  2721. // This basically counts how many milliseconds have passed since the
  2722. // call to svr.listen(), and if after 5 seconds nothing started yet
  2723. // aborts the test.
  2724. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2725. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2726. ASSERT_LT(milliseconds, 5000U);
  2727. }
  2728. {
  2729. Client cli("::1", PORT);
  2730. cli.set_follow_location(true);
  2731. std::string body;
  2732. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2733. body.append(data, data_length);
  2734. return true;
  2735. });
  2736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2737. EXPECT_EQ(StatusCode::OK_200, res->status);
  2738. EXPECT_EQ("Hello World!", body);
  2739. }
  2740. {
  2741. Client cli("::1", PORT);
  2742. std::string body;
  2743. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2744. body.append(data, data_length);
  2745. return true;
  2746. });
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. EXPECT_EQ(StatusCode::Found_302, res->status);
  2749. EXPECT_EQ("___", body);
  2750. }
  2751. }
  2752. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2753. Server svr;
  2754. svr.Get("/foo", [](const Request &req, Response &res) {
  2755. auto a = req.params.find("a");
  2756. if (a != req.params.end()) {
  2757. res.set_content((*a).second, "text/plain");
  2758. res.status = StatusCode::OK_200;
  2759. } else {
  2760. res.status = StatusCode::BadRequest_400;
  2761. }
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. {
  2771. Client cli(HOST, PORT);
  2772. cli.set_path_encode(false);
  2773. auto res = cli.Get("/foo?a=explicitly+encoded");
  2774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2775. EXPECT_EQ(StatusCode::OK_200, res->status);
  2776. // This expects it back with a space, as the `+` won't have been
  2777. // url-encoded, and server-side the params get decoded turning `+`
  2778. // into spaces.
  2779. EXPECT_EQ("explicitly encoded", res->body);
  2780. }
  2781. }
  2782. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2783. // When path encoding is disabled the client must transmit the supplied
  2784. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2785. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2786. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2787. // than a space (0x20). Assert on the raw wire target to catch this.
  2788. Server svr;
  2789. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2790. svr.Get("/foo", [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(expected_target, req.target);
  2792. res.status = StatusCode::OK_200;
  2793. });
  2794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2795. auto se = detail::scope_exit([&] {
  2796. svr.stop();
  2797. thread.join();
  2798. ASSERT_FALSE(svr.is_running());
  2799. });
  2800. svr.wait_until_ready();
  2801. {
  2802. Client cli(HOST, PORT);
  2803. cli.set_path_encode(false);
  2804. auto res = cli.Get(expected_target.c_str());
  2805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2806. EXPECT_EQ(StatusCode::OK_200, res->status);
  2807. }
  2808. }
  2809. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2810. // `open_stream()` used to skip the path encoding that the buffered send
  2811. // path applies, so the same `path` produced different bytes in the request
  2812. // line depending on which API was used. Assert the two agree.
  2813. Server svr;
  2814. std::string target;
  2815. svr.Get(".*", [&](const Request &req, Response &res) {
  2816. target = req.target;
  2817. res.status = StatusCode::OK_200;
  2818. });
  2819. auto port = svr.bind_to_any_port(HOST);
  2820. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2821. auto se = detail::scope_exit([&] {
  2822. svr.stop();
  2823. thread.join();
  2824. ASSERT_FALSE(svr.is_running());
  2825. });
  2826. svr.wait_until_ready();
  2827. struct {
  2828. const char *path;
  2829. const char *expected;
  2830. } cases[] = {
  2831. {"/a b?x=1", "/a%20b?x=1"},
  2832. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2833. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2834. };
  2835. for (const auto &c : cases) {
  2836. Client cli(HOST, port);
  2837. target.clear();
  2838. auto res = cli.Get(c.path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2841. auto buffered_target = target;
  2842. target.clear();
  2843. auto handle = cli.open_stream("GET", c.path);
  2844. EXPECT_TRUE(handle.is_valid())
  2845. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2846. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2847. }
  2848. }
  2849. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2850. // The `set_path_encode(false)` contract — transmit the supplied target
  2851. // verbatim — must hold for the streaming API too.
  2852. Server svr;
  2853. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2854. std::string target;
  2855. svr.Get("/foo", [&](const Request &req, Response &res) {
  2856. target = req.target;
  2857. res.status = StatusCode::OK_200;
  2858. });
  2859. auto port = svr.bind_to_any_port(HOST);
  2860. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. {
  2868. Client cli(HOST, port);
  2869. cli.set_path_encode(false);
  2870. auto handle = cli.open_stream("GET", expected_target);
  2871. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2872. EXPECT_EQ(expected_target, target);
  2873. }
  2874. }
  2875. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2876. // With path encoding enabled a CR/LF in the target is percent-encoded
  2877. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2878. // write_request_line still backstops `set_path_encode(false)`, which is
  2879. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2880. Server svr;
  2881. // Captured before routing: the decoded path contains a newline, which a
  2882. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2883. std::string target;
  2884. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2885. target = req.target;
  2886. res.status = StatusCode::OK_200;
  2887. return Server::HandlerResponse::Handled;
  2888. });
  2889. auto port = svr.bind_to_any_port(HOST);
  2890. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2891. auto se = detail::scope_exit([&] {
  2892. svr.stop();
  2893. thread.join();
  2894. ASSERT_FALSE(svr.is_running());
  2895. });
  2896. svr.wait_until_ready();
  2897. {
  2898. Client cli(HOST, port);
  2899. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2900. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2901. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2902. }
  2903. }
  2904. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2905. // Nothing may reach the wire: a raw CR/LF target would split the request
  2906. // line and inject headers.
  2907. Server svr;
  2908. // Pre-routing so that "not called" means nothing reached the server at all,
  2909. // rather than merely failing to match a handler pattern.
  2910. auto handler_called = false;
  2911. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2912. handler_called = true;
  2913. res.status = StatusCode::OK_200;
  2914. return Server::HandlerResponse::Handled;
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. thread.join();
  2921. ASSERT_FALSE(svr.is_running());
  2922. });
  2923. svr.wait_until_ready();
  2924. {
  2925. Client cli(HOST, port);
  2926. cli.set_path_encode(false);
  2927. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2928. EXPECT_FALSE(handle.is_valid());
  2929. EXPECT_EQ(Error::Write, handle.error);
  2930. EXPECT_FALSE(handler_called);
  2931. }
  2932. }
  2933. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2934. // Which of the two branches runs is decided by whether the query component
  2935. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2936. // an empty query and must still fall back to building one from
  2937. // `req.params`, while a non-empty query must win over `req.params`.
  2938. Server svr;
  2939. std::string target;
  2940. svr.Get("/foo", [&](const Request &req, Response &res) {
  2941. target = req.target;
  2942. res.status = StatusCode::OK_200;
  2943. });
  2944. auto port = svr.bind_to_any_port(HOST);
  2945. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2946. auto se = detail::scope_exit([&] {
  2947. svr.stop();
  2948. thread.join();
  2949. ASSERT_FALSE(svr.is_running());
  2950. });
  2951. svr.wait_until_ready();
  2952. {
  2953. // Trailing `?` -> empty query component -> `req.params` is used.
  2954. Client cli(HOST, port);
  2955. Request req;
  2956. req.method = "GET";
  2957. req.path = "/foo?";
  2958. req.params.emplace("a", "1");
  2959. target.clear();
  2960. auto res = cli.send(req);
  2961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2962. EXPECT_EQ("/foo?a=1", target);
  2963. }
  2964. {
  2965. // Non-empty query in `req.path` -> `req.params` is not appended.
  2966. Client cli(HOST, port);
  2967. Request req;
  2968. req.method = "GET";
  2969. req.path = "/foo?b=2";
  2970. req.params.emplace("a", "1");
  2971. target.clear();
  2972. auto res = cli.send(req);
  2973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2974. EXPECT_EQ("/foo?b=2", target);
  2975. }
  2976. }
  2977. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2978. Server svr;
  2979. svr.Get("/", [](const Request &req, Response &) {
  2980. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2981. });
  2982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2983. auto se = detail::scope_exit([&] {
  2984. svr.stop();
  2985. thread.join();
  2986. ASSERT_FALSE(svr.is_running());
  2987. });
  2988. svr.wait_until_ready();
  2989. {
  2990. Client cli(HOST, PORT);
  2991. cli.set_path_encode(false);
  2992. auto res = cli.Get("/?something=%0A");
  2993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2994. EXPECT_EQ(StatusCode::OK_200, res->status);
  2995. }
  2996. }
  2997. TEST(BindServerTest, BindDualStack) {
  2998. Server svr;
  2999. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3000. res.set_content("Hello World!", "text/plain");
  3001. });
  3002. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3003. auto se = detail::scope_exit([&] {
  3004. svr.stop();
  3005. thread.join();
  3006. ASSERT_FALSE(svr.is_running());
  3007. });
  3008. svr.wait_until_ready();
  3009. {
  3010. Client cli("127.0.0.1", PORT);
  3011. auto res = cli.Get("/1");
  3012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. EXPECT_EQ("Hello World!", res->body);
  3015. }
  3016. {
  3017. Client cli("::1", PORT);
  3018. auto res = cli.Get("/1");
  3019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. EXPECT_EQ("Hello World!", res->body);
  3022. }
  3023. }
  3024. TEST(BindServerTest, BindAndListenSeparately) {
  3025. Server svr;
  3026. int port = svr.bind_to_any_port("0.0.0.0");
  3027. ASSERT_TRUE(svr.is_valid());
  3028. ASSERT_TRUE(port > 0);
  3029. svr.stop();
  3030. }
  3031. // Reports whether anything is still listening on a loopback port. A plain
  3032. // connect() is used instead of a Client request because a socket left bound by
  3033. // mistake accepts the connection into its backlog and never answers, which
  3034. // would hang the test instead of failing it.
  3035. static bool is_loopback_port_accepting(int port) {
  3036. sockaddr_in addr{};
  3037. addr.sin_family = AF_INET;
  3038. addr.sin_port = htons(static_cast<uint16_t>(port));
  3039. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3040. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3041. EXPECT_NE(sock, INVALID_SOCKET);
  3042. if (sock == INVALID_SOCKET) { return false; }
  3043. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3044. static_cast<socklen_t>(sizeof(addr)));
  3045. detail::close_socket(sock);
  3046. return ret == 0;
  3047. }
  3048. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3049. Server svr;
  3050. auto port = svr.bind_to_any_port("127.0.0.1");
  3051. ASSERT_TRUE(port > 0);
  3052. svr.stop();
  3053. // bind_to_any_port() already called listen(2), so until stop() closed the
  3054. // descriptor the port kept accepting connections into the backlog. ASSERT
  3055. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3056. // below blocks forever in the accept loop.
  3057. ASSERT_FALSE(is_loopback_port_accepting(port));
  3058. // Nothing is left to accept on, so listen_after_bind() must report failure
  3059. // instead of returning success without ever serving.
  3060. EXPECT_FALSE(svr.listen_after_bind());
  3061. // The failed listen marks the server decommissioned, so a waiter returns
  3062. // instead of spinning forever.
  3063. svr.wait_until_ready();
  3064. }
  3065. #ifdef CPPHTTPLIB_SSL_ENABLED
  3066. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3068. CLIENT_CA_CERT_DIR);
  3069. int port = svr.bind_to_any_port("0.0.0.0");
  3070. ASSERT_TRUE(svr.is_valid());
  3071. ASSERT_TRUE(port > 0);
  3072. svr.stop();
  3073. }
  3074. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3075. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3076. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3077. int port = svr.bind_to_any_port("0.0.0.0");
  3078. ASSERT_TRUE(svr.is_valid());
  3079. ASSERT_TRUE(port > 0);
  3080. svr.stop();
  3081. }
  3082. TEST(BindServerTest, UpdateCertsPem) {
  3083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3084. int port = svr.bind_to_any_port("0.0.0.0");
  3085. ASSERT_TRUE(svr.is_valid());
  3086. ASSERT_TRUE(port > 0);
  3087. // Read PEM files
  3088. std::string cert_pem, key_pem, ca_pem;
  3089. read_file(SERVER_CERT_FILE, cert_pem);
  3090. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3091. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3092. // Update server certificates using PEM API
  3093. ASSERT_TRUE(
  3094. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3095. ASSERT_TRUE(svr.is_valid());
  3096. svr.stop();
  3097. }
  3098. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3099. // Start server with client CA (enables client auth)
  3100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3101. ASSERT_TRUE(svr.is_valid());
  3102. bool handler_called = false;
  3103. svr.Get("/test", [&](const Request &req, Response &res) {
  3104. handler_called = true;
  3105. // Verify client certificate is present
  3106. auto cert = req.peer_cert();
  3107. EXPECT_TRUE(static_cast<bool>(cert));
  3108. res.set_content("ok", "text/plain");
  3109. });
  3110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. t.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. // Read PEM files
  3118. std::string cert_pem, key_pem, ca_pem;
  3119. read_file(SERVER_CERT_FILE, cert_pem);
  3120. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3121. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3122. // Update server certificates and client CA using PEM API while server running
  3123. ASSERT_TRUE(
  3124. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3125. // Connect with client certificate
  3126. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3127. cli.enable_server_certificate_verification(false);
  3128. cli.set_connection_timeout(30);
  3129. auto res = cli.Get("/test");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. ASSERT_EQ(StatusCode::OK_200, res->status);
  3132. ASSERT_TRUE(handler_called);
  3133. EXPECT_EQ("ok", res->body);
  3134. }
  3135. #endif
  3136. TEST(ErrorHandlerTest, ContentLength) {
  3137. Server svr;
  3138. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3139. res.status = StatusCode::OK_200;
  3140. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3141. "text/html"); // <= Content-Length still 13
  3142. });
  3143. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3144. res.set_content("Hello World!\n", "text/plain");
  3145. res.status = 524;
  3146. });
  3147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3148. auto se = detail::scope_exit([&] {
  3149. svr.stop();
  3150. thread.join();
  3151. ASSERT_FALSE(svr.is_running());
  3152. });
  3153. svr.wait_until_ready();
  3154. {
  3155. Client cli(HOST, PORT);
  3156. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3158. EXPECT_EQ(StatusCode::OK_200, res->status);
  3159. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3160. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3162. }
  3163. }
  3164. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3165. TEST(ExceptionTest, WithoutExceptionHandler) {
  3166. Server svr;
  3167. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3168. throw std::runtime_error("exception...");
  3169. });
  3170. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3171. throw std::runtime_error("exception\r\n...");
  3172. });
  3173. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3174. auto se = detail::scope_exit([&] {
  3175. svr.stop();
  3176. listen_thread.join();
  3177. ASSERT_FALSE(svr.is_running());
  3178. });
  3179. svr.wait_until_ready();
  3180. Client cli("localhost", PORT);
  3181. {
  3182. auto res = cli.Get("/exception");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3185. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3186. }
  3187. {
  3188. auto res = cli.Get("/unknown");
  3189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3190. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3191. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3192. }
  3193. }
  3194. TEST(ExceptionTest, WithExceptionHandler) {
  3195. Server svr;
  3196. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3197. std::exception_ptr ep) {
  3198. EXPECT_FALSE(ep == nullptr);
  3199. try {
  3200. std::rethrow_exception(ep);
  3201. } catch (std::exception &e) {
  3202. EXPECT_EQ("abc", std::string(e.what()));
  3203. } catch (...) {}
  3204. res.status = StatusCode::InternalServerError_500;
  3205. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3206. "text/html"); // <= Content-Length still 13 at this point
  3207. });
  3208. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3209. res.set_content("Hello World!\n", "text/plain");
  3210. throw std::runtime_error("abc");
  3211. });
  3212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3213. auto se = detail::scope_exit([&] {
  3214. svr.stop();
  3215. thread.join();
  3216. ASSERT_FALSE(svr.is_running());
  3217. });
  3218. svr.wait_until_ready();
  3219. for (size_t i = 0; i < 10; i++) {
  3220. Client cli(HOST, PORT);
  3221. for (size_t j = 0; j < 100; j++) {
  3222. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3225. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3226. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3227. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3228. }
  3229. cli.set_keep_alive(true);
  3230. for (size_t j = 0; j < 100; j++) {
  3231. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3233. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3234. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3236. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3237. }
  3238. }
  3239. }
  3240. TEST(ExceptionTest, AndErrorHandler) {
  3241. Server svr;
  3242. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3243. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3244. });
  3245. svr.set_exception_handler(
  3246. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3247. EXPECT_FALSE(ep == nullptr);
  3248. try {
  3249. std::rethrow_exception(ep);
  3250. } catch (std::exception &e) {
  3251. res.set_content(e.what(), "text/html");
  3252. } catch (...) {}
  3253. res.status = StatusCode::InternalServerError_500;
  3254. });
  3255. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3256. throw std::runtime_error("EXCEPTION");
  3257. });
  3258. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3259. res.set_content("ERROR", "text/html");
  3260. res.status = StatusCode::InternalServerError_500;
  3261. });
  3262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3263. auto se = detail::scope_exit([&] {
  3264. svr.stop();
  3265. thread.join();
  3266. ASSERT_FALSE(svr.is_running());
  3267. });
  3268. svr.wait_until_ready();
  3269. Client cli(HOST, PORT);
  3270. {
  3271. auto res = cli.Get("/exception");
  3272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3273. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3274. EXPECT_EQ("EXCEPTION", res->body);
  3275. }
  3276. {
  3277. auto res = cli.Get("/error");
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3280. EXPECT_EQ("ERROR", res->body);
  3281. }
  3282. {
  3283. auto res = cli.Get("/invalid");
  3284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3286. EXPECT_EQ("NOT_FOUND", res->body);
  3287. }
  3288. }
  3289. #endif
  3290. TEST(NoContentTest, ContentLength) {
  3291. Server svr;
  3292. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3293. res.status = StatusCode::NoContent_204;
  3294. });
  3295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3296. auto se = detail::scope_exit([&] {
  3297. svr.stop();
  3298. thread.join();
  3299. ASSERT_FALSE(svr.is_running());
  3300. });
  3301. svr.wait_until_ready();
  3302. {
  3303. Client cli(HOST, PORT);
  3304. auto res = cli.Get("/hi");
  3305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3306. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3307. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3308. }
  3309. }
  3310. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3311. #ifdef CPPHTTPLIB_SSL_ENABLED
  3312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3313. ASSERT_TRUE(svr.is_valid());
  3314. #else
  3315. Server svr;
  3316. #endif
  3317. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3318. if (req.path == "/routing_handler") {
  3319. res.set_header("PRE_ROUTING", "on");
  3320. res.set_content("Routing Handler", "text/plain");
  3321. return httplib::Server::HandlerResponse::Handled;
  3322. }
  3323. return httplib::Server::HandlerResponse::Unhandled;
  3324. });
  3325. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3326. res.set_content("Error", "text/html");
  3327. });
  3328. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3329. if (req.path == "/routing_handler") {
  3330. res.set_header("POST_ROUTING", "on");
  3331. }
  3332. });
  3333. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3334. res.set_content("Hello World!\n", "text/plain");
  3335. });
  3336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3337. auto se = detail::scope_exit([&] {
  3338. svr.stop();
  3339. thread.join();
  3340. ASSERT_FALSE(svr.is_running());
  3341. });
  3342. svr.wait_until_ready();
  3343. {
  3344. #ifdef CPPHTTPLIB_SSL_ENABLED
  3345. SSLClient cli(HOST, PORT);
  3346. cli.enable_server_certificate_verification(false);
  3347. #else
  3348. Client cli(HOST, PORT);
  3349. #endif
  3350. auto res = cli.Get("/routing_handler");
  3351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3352. EXPECT_EQ(StatusCode::OK_200, res->status);
  3353. EXPECT_EQ("Routing Handler", res->body);
  3354. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3355. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3356. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3357. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3358. }
  3359. {
  3360. #ifdef CPPHTTPLIB_SSL_ENABLED
  3361. SSLClient cli(HOST, PORT);
  3362. cli.enable_server_certificate_verification(false);
  3363. #else
  3364. Client cli(HOST, PORT);
  3365. #endif
  3366. auto res = cli.Get("/hi");
  3367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3368. EXPECT_EQ(StatusCode::OK_200, res->status);
  3369. EXPECT_EQ("Hello World!\n", res->body);
  3370. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3371. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3372. }
  3373. {
  3374. #ifdef CPPHTTPLIB_SSL_ENABLED
  3375. SSLClient cli(HOST, PORT);
  3376. cli.enable_server_certificate_verification(false);
  3377. #else
  3378. Client cli(HOST, PORT);
  3379. #endif
  3380. auto res = cli.Get("/aaa");
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3383. EXPECT_EQ("Error", res->body);
  3384. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3385. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3386. }
  3387. }
  3388. TEST(RequestHandlerTest, PreRequestHandler) {
  3389. auto route_path = "/user/:user";
  3390. Server svr;
  3391. svr.Get("/hi", [](const Request &, Response &res) {
  3392. res.set_content("hi", "text/plain");
  3393. });
  3394. svr.Get(route_path, [](const Request &req, Response &res) {
  3395. res.set_content(req.path_params.at("user"), "text/plain");
  3396. });
  3397. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3398. if (req.matched_route == route_path) {
  3399. auto user = req.path_params.at("user");
  3400. if (user != "john") {
  3401. res.status = StatusCode::Forbidden_403;
  3402. res.set_content("error", "text/html");
  3403. return Server::HandlerResponse::Handled;
  3404. }
  3405. }
  3406. return Server::HandlerResponse::Unhandled;
  3407. });
  3408. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3409. auto se = detail::scope_exit([&] {
  3410. svr.stop();
  3411. thread.join();
  3412. ASSERT_FALSE(svr.is_running());
  3413. });
  3414. svr.wait_until_ready();
  3415. Client cli(HOST, PORT);
  3416. {
  3417. auto res = cli.Get("/hi");
  3418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3419. EXPECT_EQ(StatusCode::OK_200, res->status);
  3420. EXPECT_EQ("hi", res->body);
  3421. }
  3422. {
  3423. auto res = cli.Get("/user/john");
  3424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("john", res->body);
  3427. }
  3428. {
  3429. auto res = cli.Get("/user/invalid-user");
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3432. EXPECT_EQ("error", res->body);
  3433. }
  3434. }
  3435. // The pre-request handler must run before the request body is read, so a
  3436. // rejected request never forces the server to buffer a (potentially large)
  3437. // body. Here the posted body is larger than the payload limit: if the body
  3438. // were read first the server would answer 413, but because the pre-request
  3439. // handler runs first it answers 403 and the body is never read.
  3440. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3441. Server svr;
  3442. svr.set_payload_max_length(8);
  3443. auto handler_ran = false;
  3444. svr.Post("/reject", [&](const Request &req, Response &res) {
  3445. handler_ran = true;
  3446. res.set_content(req.body, "text/plain");
  3447. });
  3448. svr.Post("/accept", [](const Request &req, Response &res) {
  3449. res.set_content(req.body, "text/plain");
  3450. });
  3451. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3452. if (req.matched_route == "/reject") {
  3453. res.status = StatusCode::Forbidden_403;
  3454. res.set_content("denied", "text/plain");
  3455. return Server::HandlerResponse::Handled;
  3456. }
  3457. return Server::HandlerResponse::Unhandled;
  3458. });
  3459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, PORT);
  3467. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3468. // rejects with 403 before the body is read, so 413 is never reached.
  3469. {
  3470. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3472. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3473. EXPECT_EQ("denied", res->body);
  3474. EXPECT_FALSE(handler_ran);
  3475. }
  3476. // An approved route still reads the body and enforces the payload limit.
  3477. {
  3478. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3480. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3481. }
  3482. }
  3483. TEST(UserDataTest, BasicOperations) {
  3484. httplib::UserData ud;
  3485. // Initially empty
  3486. EXPECT_FALSE(ud.has("key"));
  3487. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3488. // set and get
  3489. ud.set("key", 42);
  3490. EXPECT_TRUE(ud.has("key"));
  3491. auto *p = ud.get<int>("key");
  3492. ASSERT_NE(nullptr, p);
  3493. EXPECT_EQ(42, *p);
  3494. // Type mismatch → nullptr
  3495. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3496. // Overwrite with different type
  3497. ud.set("key", std::string("hello"));
  3498. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3499. auto *s = ud.get<std::string>("key");
  3500. ASSERT_NE(nullptr, s);
  3501. EXPECT_EQ("hello", *s);
  3502. // erase
  3503. ud.erase("key");
  3504. EXPECT_FALSE(ud.has("key"));
  3505. // clear
  3506. ud.set("a", 1);
  3507. ud.set("b", 2);
  3508. ud.clear();
  3509. EXPECT_FALSE(ud.has("a"));
  3510. EXPECT_FALSE(ud.has("b"));
  3511. }
  3512. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3513. struct AuthCtx {
  3514. std::string user_id;
  3515. };
  3516. Server svr;
  3517. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3518. res.user_data.set("auth", AuthCtx{"alice"});
  3519. return Server::HandlerResponse::Unhandled;
  3520. });
  3521. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3522. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3523. ASSERT_NE(nullptr, ctx);
  3524. res.set_content("Hello " + ctx->user_id, "text/plain");
  3525. });
  3526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, PORT);
  3534. auto res = cli.Get("/me");
  3535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3536. EXPECT_EQ(StatusCode::OK_200, res->status);
  3537. EXPECT_EQ("Hello alice", res->body);
  3538. }
  3539. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3540. struct RoleCtx {
  3541. std::string role;
  3542. };
  3543. Server svr;
  3544. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3545. res.user_data.set("role", RoleCtx{"admin"});
  3546. return Server::HandlerResponse::Unhandled;
  3547. });
  3548. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3549. auto *ctx = res.user_data.get<RoleCtx>("role");
  3550. ASSERT_NE(nullptr, ctx);
  3551. res.set_content(ctx->role, "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, PORT);
  3561. auto res = cli.Get("/role");
  3562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. EXPECT_EQ("admin", res->body);
  3565. }
  3566. TEST(InvalidFormatTest, StatusCode) {
  3567. Server svr;
  3568. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!\n", "text/plain");
  3570. res.status = 9999; // Status should be a three-digit code...
  3571. });
  3572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3573. auto se = detail::scope_exit([&] {
  3574. svr.stop();
  3575. thread.join();
  3576. ASSERT_FALSE(svr.is_running());
  3577. });
  3578. svr.wait_until_ready();
  3579. {
  3580. Client cli(HOST, PORT);
  3581. auto res = cli.Get("/hi");
  3582. ASSERT_FALSE(res);
  3583. }
  3584. }
  3585. TEST(URLFragmentTest, WithFragment) {
  3586. Server svr;
  3587. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3588. EXPECT_TRUE(req.target == "/hi");
  3589. });
  3590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3591. auto se = detail::scope_exit([&] {
  3592. svr.stop();
  3593. thread.join();
  3594. ASSERT_FALSE(svr.is_running());
  3595. });
  3596. svr.wait_until_ready();
  3597. {
  3598. Client cli(HOST, PORT);
  3599. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3600. EXPECT_TRUE(res);
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. res = cli.Get("/hi%23key1=val1=key2=val2");
  3603. EXPECT_TRUE(res);
  3604. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3605. }
  3606. }
  3607. TEST(HeaderWriter, SetHeaderWriter) {
  3608. Server svr;
  3609. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3610. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3611. return detail::write_headers(strm, hdrs);
  3612. });
  3613. svr.Get("/hi", [](const Request &req, Response &res) {
  3614. auto it = req.headers.find("CustomClientHeader");
  3615. EXPECT_TRUE(it != req.headers.end());
  3616. EXPECT_EQ(it->second, "CustomClientValue");
  3617. res.set_content("Hello World!\n", "text/plain");
  3618. });
  3619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. thread.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. {
  3627. Client cli(HOST, PORT);
  3628. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3629. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3630. return detail::write_headers(strm, hdrs);
  3631. });
  3632. auto res = cli.Get("/hi");
  3633. EXPECT_TRUE(res);
  3634. EXPECT_EQ(StatusCode::OK_200, res->status);
  3635. auto it = res->headers.find("CustomServerHeader");
  3636. EXPECT_TRUE(it != res->headers.end());
  3637. EXPECT_EQ(it->second, "CustomServerValue");
  3638. }
  3639. }
  3640. class ServerTest : public ::testing::Test {
  3641. protected:
  3642. ServerTest()
  3643. : cli_(HOST, PORT)
  3644. #ifdef CPPHTTPLIB_SSL_ENABLED
  3645. ,
  3646. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3647. #endif
  3648. {
  3649. #ifdef CPPHTTPLIB_SSL_ENABLED
  3650. cli_.enable_server_certificate_verification(false);
  3651. #endif
  3652. // Allow LARGE_DATA (100MB) responses
  3653. cli_.set_payload_max_length(200 * 1024 * 1024);
  3654. }
  3655. virtual void SetUp() {
  3656. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3657. svr_.set_payload_max_length(200 * 1024 * 1024);
  3658. svr_.set_mount_point("/", "./www");
  3659. svr_.set_mount_point("/mount", "./www2");
  3660. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3661. svr_.Get("/hi",
  3662. [&](const Request & /*req*/, Response &res) {
  3663. res.set_content("Hello World!", "text/plain");
  3664. })
  3665. .Get("/file_content",
  3666. [&](const Request & /*req*/, Response &res) {
  3667. res.set_file_content("./www/dir/test.html");
  3668. })
  3669. .Get("/file_content_with_content_type",
  3670. [&](const Request & /*req*/, Response &res) {
  3671. res.set_file_content("./www/file", "text/plain");
  3672. })
  3673. .Get("/invalid_file_content",
  3674. [&](const Request & /*req*/, Response &res) {
  3675. res.set_file_content("./www/dir/invalid_file_path");
  3676. })
  3677. .Get("/http_response_splitting",
  3678. [&](const Request & /*req*/, Response &res) {
  3679. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3680. EXPECT_EQ(0U, res.headers.size());
  3681. EXPECT_FALSE(res.has_header("a"));
  3682. res.set_header("a", "1\nSet-Cookie: a=1");
  3683. EXPECT_EQ(0U, res.headers.size());
  3684. EXPECT_FALSE(res.has_header("a"));
  3685. res.set_header("a", "1\rSet-Cookie: a=1");
  3686. EXPECT_EQ(0U, res.headers.size());
  3687. EXPECT_FALSE(res.has_header("a"));
  3688. res.set_header("a\r\nb", "0");
  3689. EXPECT_EQ(0U, res.headers.size());
  3690. EXPECT_FALSE(res.has_header("a"));
  3691. res.set_header("a\rb", "0");
  3692. EXPECT_EQ(0U, res.headers.size());
  3693. EXPECT_FALSE(res.has_header("a"));
  3694. res.set_header("a\nb", "0");
  3695. EXPECT_EQ(0U, res.headers.size());
  3696. EXPECT_FALSE(res.has_header("a"));
  3697. res.set_redirect("1\r\nSet-Cookie: a=1");
  3698. EXPECT_EQ(0U, res.headers.size());
  3699. EXPECT_FALSE(res.has_header("Location"));
  3700. })
  3701. .Get("/slow",
  3702. [&](const Request & /*req*/, Response &res) {
  3703. std::this_thread::sleep_for(std::chrono::seconds(4));
  3704. res.set_content("slow", "text/plain");
  3705. })
  3706. #if 0
  3707. .Post("/slowpost",
  3708. [&](const Request & /*req*/, Response &res) {
  3709. std::this_thread::sleep_for(std::chrono::seconds(2));
  3710. res.set_content("slow", "text/plain");
  3711. })
  3712. #endif
  3713. .Get("/remote_addr",
  3714. [&](const Request &req, Response &res) {
  3715. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3716. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3717. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3718. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3719. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3720. #endif
  3721. res.set_content(req.remote_addr, "text/plain");
  3722. })
  3723. .Get("/local_addr",
  3724. [&](const Request &req, Response &res) {
  3725. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3726. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3727. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3728. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3729. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3730. #endif
  3731. auto local_addr = req.local_addr;
  3732. auto local_port = std::to_string(req.local_port);
  3733. res.set_content(local_addr.append(":").append(local_port),
  3734. "text/plain");
  3735. })
  3736. .Get("/endwith%",
  3737. [&](const Request & /*req*/, Response &res) {
  3738. res.set_content("Hello World!", "text/plain");
  3739. })
  3740. .Get("/a\\+\\+b",
  3741. [&](const Request &req, Response &res) {
  3742. ASSERT_TRUE(req.has_param("a +b"));
  3743. auto val = req.get_param_value("a +b");
  3744. res.set_content(val, "text/plain");
  3745. })
  3746. .Get("/", [&](const Request & /*req*/,
  3747. Response &res) { res.set_redirect("/hi"); })
  3748. .Post("/1",
  3749. [](const Request & /*req*/, Response &res) {
  3750. res.set_redirect("/2", StatusCode::SeeOther_303);
  3751. })
  3752. .Get("/2",
  3753. [](const Request & /*req*/, Response &res) {
  3754. res.set_content("redirected.", "text/plain");
  3755. res.status = StatusCode::OK_200;
  3756. })
  3757. .Post("/person",
  3758. [&](const Request &req, Response &res) {
  3759. if (req.has_param("name") && req.has_param("note")) {
  3760. persons_[req.get_param_value("name")] =
  3761. req.get_param_value("note");
  3762. } else {
  3763. res.status = StatusCode::BadRequest_400;
  3764. }
  3765. })
  3766. .Put("/person",
  3767. [&](const Request &req, Response &res) {
  3768. if (req.has_param("name") && req.has_param("note")) {
  3769. persons_[req.get_param_value("name")] =
  3770. req.get_param_value("note");
  3771. } else {
  3772. res.status = StatusCode::BadRequest_400;
  3773. }
  3774. })
  3775. .Get("/person/(.*)",
  3776. [&](const Request &req, Response &res) {
  3777. string name = req.matches[1];
  3778. if (persons_.find(name) != persons_.end()) {
  3779. auto note = persons_[name];
  3780. res.set_content(note, "text/plain");
  3781. } else {
  3782. res.status = StatusCode::NotFound_404;
  3783. }
  3784. })
  3785. .Delete("/person",
  3786. [&](const Request &req, Response &res) {
  3787. if (req.has_param("name")) {
  3788. string name = req.get_param_value("name");
  3789. if (persons_.find(name) != persons_.end()) {
  3790. persons_.erase(name);
  3791. res.set_content("DELETED", "text/plain");
  3792. } else {
  3793. res.status = StatusCode::NotFound_404;
  3794. }
  3795. } else {
  3796. res.status = StatusCode::BadRequest_400;
  3797. }
  3798. })
  3799. .Post("/x-www-form-urlencoded-json",
  3800. [&](const Request &req, Response &res) {
  3801. auto json = req.get_param_value("json");
  3802. ASSERT_EQ(JSON_DATA, json);
  3803. res.set_content(json, "appliation/json");
  3804. res.status = StatusCode::OK_200;
  3805. })
  3806. .Get("/streamed-chunked",
  3807. [&](const Request & /*req*/, Response &res) {
  3808. res.set_chunked_content_provider(
  3809. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3810. sink.os << "123";
  3811. sink.os << "456";
  3812. sink.os << "789";
  3813. sink.done();
  3814. return true;
  3815. });
  3816. })
  3817. .Get("/streamed-chunked-with-prohibited-trailer",
  3818. [&](const Request & /*req*/, Response &res) {
  3819. auto i = new int(0);
  3820. // Declare both a prohibited trailer (Content-Length) and an
  3821. // allowed one
  3822. res.set_header("Trailer", "Content-Length, X-Allowed");
  3823. res.set_chunked_content_provider(
  3824. "text/plain",
  3825. [i](size_t /*offset*/, DataSink &sink) {
  3826. switch (*i) {
  3827. case 0: sink.os << "123"; break;
  3828. case 1: sink.os << "456"; break;
  3829. case 2: sink.os << "789"; break;
  3830. case 3: {
  3831. sink.done_with_trailer(
  3832. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3833. } break;
  3834. }
  3835. (*i)++;
  3836. return true;
  3837. },
  3838. [i](bool success) {
  3839. EXPECT_TRUE(success);
  3840. delete i;
  3841. });
  3842. })
  3843. .Get("/streamed-chunked2",
  3844. [&](const Request & /*req*/, Response &res) {
  3845. auto i = new int(0);
  3846. res.set_chunked_content_provider(
  3847. "text/plain",
  3848. [i](size_t /*offset*/, DataSink &sink) {
  3849. switch (*i) {
  3850. case 0: sink.os << "123"; break;
  3851. case 1: sink.os << "456"; break;
  3852. case 2: sink.os << "789"; break;
  3853. case 3: sink.done(); break;
  3854. }
  3855. (*i)++;
  3856. return true;
  3857. },
  3858. [i](bool success) {
  3859. EXPECT_TRUE(success);
  3860. delete i;
  3861. });
  3862. })
  3863. .Get("/streamed-chunked-with-trailer",
  3864. [&](const Request & /*req*/, Response &res) {
  3865. auto i = new int(0);
  3866. res.set_header("Trailer", "Dummy1, Dummy2");
  3867. res.set_chunked_content_provider(
  3868. "text/plain",
  3869. [i](size_t /*offset*/, DataSink &sink) {
  3870. switch (*i) {
  3871. case 0: sink.os << "123"; break;
  3872. case 1: sink.os << "456"; break;
  3873. case 2: sink.os << "789"; break;
  3874. case 3: {
  3875. sink.done_with_trailer(
  3876. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3877. } break;
  3878. }
  3879. (*i)++;
  3880. return true;
  3881. },
  3882. [i](bool success) {
  3883. EXPECT_TRUE(success);
  3884. delete i;
  3885. });
  3886. })
  3887. .Get("/streamed",
  3888. [&](const Request & /*req*/, Response &res) {
  3889. res.set_content_provider(
  3890. 6, "text/plain",
  3891. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3892. sink.os << (offset < 3 ? "a" : "b");
  3893. return true;
  3894. });
  3895. })
  3896. .Get("/streamed-without-length",
  3897. [&](const Request & /*req*/, Response &res) {
  3898. auto data = new std::string("abcdefg");
  3899. res.set_content_provider(
  3900. "text/plain",
  3901. [data](size_t offset, DataSink &sink) {
  3902. if (offset < data->size()) {
  3903. sink.os << data->substr(offset);
  3904. }
  3905. sink.done();
  3906. return true;
  3907. },
  3908. [data](bool success) {
  3909. EXPECT_TRUE(success);
  3910. delete data;
  3911. });
  3912. })
  3913. .Get("/streamed-with-range",
  3914. [&](const Request &req, Response &res) {
  3915. auto data = new std::string("abcdefg");
  3916. // An explicit status keeps the server from picking the 206 it
  3917. // would otherwise choose for a ranged request, so the response
  3918. // is not a partial representation.
  3919. auto status = req.get_param_value("status");
  3920. if (status == "200") {
  3921. res.status = StatusCode::OK_200;
  3922. } else if (status == "403") {
  3923. res.status = StatusCode::Forbidden_403;
  3924. }
  3925. res.set_content_provider(
  3926. data->size(), "text/plain",
  3927. [data](size_t offset, size_t length, DataSink &sink) {
  3928. size_t DATA_CHUNK_SIZE = 4;
  3929. const auto &d = *data;
  3930. auto out_len =
  3931. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3932. auto ret =
  3933. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3934. EXPECT_TRUE(ret);
  3935. return true;
  3936. },
  3937. [data, &req](bool success) {
  3938. EXPECT_EQ(success, !req.has_param("error"));
  3939. delete data;
  3940. });
  3941. })
  3942. .Get("/streamed-cancel",
  3943. [&](const Request & /*req*/, Response &res) {
  3944. res.set_content_provider(
  3945. size_t(-1), "text/plain",
  3946. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3947. sink.os << "data_chunk";
  3948. return true;
  3949. });
  3950. })
  3951. .Get("/regex-with-delimiter",
  3952. [&](const Request &req, Response & /*res*/) {
  3953. ASSERT_TRUE(req.has_param("key"));
  3954. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3955. })
  3956. .Get("/with-range",
  3957. [&](const Request & /*req*/, Response &res) {
  3958. res.set_content("abcdefg", "text/plain");
  3959. })
  3960. .Get("/test-start-time",
  3961. [&](const Request &req, Response & /*res*/) {
  3962. EXPECT_NE(req.start_time_,
  3963. std::chrono::steady_clock::time_point::min());
  3964. })
  3965. .Get("/with-range-customized-response",
  3966. [&](const Request & /*req*/, Response &res) {
  3967. res.status = StatusCode::BadRequest_400;
  3968. res.set_content(JSON_DATA, "application/json");
  3969. })
  3970. .Post("/chunked",
  3971. [&](const Request &req, Response & /*res*/) {
  3972. EXPECT_EQ(req.body, "dechunked post body");
  3973. })
  3974. .Post("/large-chunked",
  3975. [&](const Request &req, Response & /*res*/) {
  3976. std::string expected(6 * 30 * 1024u, 'a');
  3977. EXPECT_EQ(req.body, expected);
  3978. })
  3979. .Post("/multipart",
  3980. [&](const Request &req, Response & /*res*/) {
  3981. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3982. req.form.get_field_count("text2") +
  3983. req.form.get_field_count("file3") +
  3984. req.form.get_field_count("file4"));
  3985. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3986. req.form.get_file_count("file2"));
  3987. ASSERT_TRUE(!req.form.has_file("???"));
  3988. ASSERT_TRUE(!req.form.has_field("???"));
  3989. ASSERT_TRUE(req.body.empty());
  3990. {
  3991. const auto &text = req.form.get_field("text1");
  3992. EXPECT_EQ("text default", text);
  3993. }
  3994. {
  3995. const auto &text = req.form.get_field("text2");
  3996. EXPECT_EQ("aωb", text);
  3997. }
  3998. {
  3999. const auto &file = req.form.get_file("file1");
  4000. EXPECT_EQ("hello.txt", file.filename);
  4001. EXPECT_EQ("text/plain", file.content_type);
  4002. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4003. }
  4004. {
  4005. const auto &file = req.form.get_file("file2");
  4006. EXPECT_EQ("world.json", file.filename);
  4007. EXPECT_EQ("application/json", file.content_type);
  4008. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4009. }
  4010. {
  4011. const auto &text = req.form.get_field("file3");
  4012. EXPECT_EQ(0u, text.size());
  4013. }
  4014. {
  4015. const auto &text = req.form.get_field("file4");
  4016. EXPECT_EQ(0u, text.size());
  4017. }
  4018. })
  4019. .Post("/multipart/multi_file_values",
  4020. [&](const Request &req, Response & /*res*/) {
  4021. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4022. req.form.get_field_count("multi_text1"));
  4023. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4024. ASSERT_TRUE(!req.form.has_file("???"));
  4025. ASSERT_TRUE(!req.form.has_field("???"));
  4026. ASSERT_TRUE(req.body.empty());
  4027. {
  4028. const auto &text = req.form.get_field("text");
  4029. EXPECT_EQ("default text", text);
  4030. }
  4031. {
  4032. const auto &text1_values = req.form.get_fields("multi_text1");
  4033. EXPECT_EQ(2u, text1_values.size());
  4034. EXPECT_EQ("aaaaa", text1_values[0]);
  4035. EXPECT_EQ("bbbbb", text1_values[1]);
  4036. }
  4037. {
  4038. const auto &file1_values = req.form.get_files("multi_file1");
  4039. EXPECT_EQ(2u, file1_values.size());
  4040. auto file1 = file1_values[0];
  4041. EXPECT_EQ(file1.filename, "hello.txt");
  4042. EXPECT_EQ(file1.content_type, "text/plain");
  4043. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4044. auto file2 = file1_values[1];
  4045. EXPECT_EQ(file2.filename, "world.json");
  4046. EXPECT_EQ(file2.content_type, "application/json");
  4047. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4048. }
  4049. })
  4050. .Post("/empty",
  4051. [&](const Request &req, Response &res) {
  4052. EXPECT_EQ(req.body, "");
  4053. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4054. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4055. res.set_content("empty", "text/plain");
  4056. })
  4057. .Post("/empty-no-content-type",
  4058. [&](const Request &req, Response &res) {
  4059. EXPECT_EQ(req.body, "");
  4060. EXPECT_FALSE(req.has_header("Content-Type"));
  4061. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4062. res.set_content("empty-no-content-type", "text/plain");
  4063. })
  4064. .Post("/path-only",
  4065. [&](const Request &req, Response &res) {
  4066. EXPECT_EQ(req.body, "");
  4067. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4068. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4069. res.set_content("path-only", "text/plain");
  4070. })
  4071. .Post("/path-headers-only",
  4072. [&](const Request &req, Response &res) {
  4073. EXPECT_EQ(req.body, "");
  4074. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4075. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4076. EXPECT_EQ("world", req.get_header_value("hello"));
  4077. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4078. res.set_content("path-headers-only", "text/plain");
  4079. })
  4080. .Post("/post-large",
  4081. [&](const Request &req, Response &res) {
  4082. EXPECT_EQ(req.body, LARGE_DATA);
  4083. res.set_content(req.body, "text/plain");
  4084. })
  4085. .Post("/post-loopback",
  4086. [&](const Request &, Response &res,
  4087. ContentReader const &content_reader) {
  4088. std::string body;
  4089. content_reader([&](const char *data, size_t data_length) {
  4090. body.append(data, data_length);
  4091. return true;
  4092. });
  4093. res.set_content(body, "text/plain");
  4094. })
  4095. .Put("/put-loopback",
  4096. [&](const Request &, Response &res,
  4097. ContentReader const &content_reader) {
  4098. std::string body;
  4099. content_reader([&](const char *data, size_t data_length) {
  4100. body.append(data, data_length);
  4101. return true;
  4102. });
  4103. res.set_content(body, "text/plain");
  4104. })
  4105. .Patch("/patch-loopback",
  4106. [&](const Request &, Response &res,
  4107. ContentReader const &content_reader) {
  4108. std::string body;
  4109. content_reader([&](const char *data, size_t data_length) {
  4110. body.append(data, data_length);
  4111. return true;
  4112. });
  4113. res.set_content(body, "text/plain");
  4114. })
  4115. .Put("/empty-no-content-type",
  4116. [&](const Request &req, Response &res) {
  4117. EXPECT_EQ(req.body, "");
  4118. EXPECT_FALSE(req.has_header("Content-Type"));
  4119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4120. res.set_content("empty-no-content-type", "text/plain");
  4121. })
  4122. .Put("/put",
  4123. [&](const Request &req, Response &res) {
  4124. EXPECT_EQ(req.body, "PUT");
  4125. res.set_content(req.body, "text/plain");
  4126. })
  4127. .Put("/put-large",
  4128. [&](const Request &req, Response &res) {
  4129. EXPECT_EQ(req.body, LARGE_DATA);
  4130. res.set_content(req.body, "text/plain");
  4131. })
  4132. .Patch("/patch",
  4133. [&](const Request &req, Response &res) {
  4134. EXPECT_EQ(req.body, "PATCH");
  4135. res.set_content(req.body, "text/plain");
  4136. })
  4137. .Delete("/delete",
  4138. [&](const Request & /*req*/, Response &res) {
  4139. res.set_content("DELETE", "text/plain");
  4140. })
  4141. .Delete("/delete-body",
  4142. [&](const Request &req, Response &res) {
  4143. EXPECT_EQ(req.body, "content");
  4144. res.set_content(req.body, "text/plain");
  4145. })
  4146. .Options(R"(\*)",
  4147. [&](const Request & /*req*/, Response &res) {
  4148. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4149. })
  4150. .Get("/request-target",
  4151. [&](const Request &req, Response & /*res*/) {
  4152. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4153. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4154. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4155. })
  4156. .Get("/long-query-value",
  4157. [&](const Request &req, Response & /*res*/) {
  4158. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4159. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4160. })
  4161. .Get("/too-long-query-value",
  4162. [&](const Request &req, Response & /*res*/) {
  4163. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4164. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4165. })
  4166. .Get("/array-param",
  4167. [&](const Request &req, Response & /*res*/) {
  4168. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4169. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4170. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4171. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4172. })
  4173. .Get("/array-param-values",
  4174. [&](const Request &req, Response & /*res*/) {
  4175. auto values = req.get_param_values("array");
  4176. EXPECT_EQ(3u, values.size());
  4177. EXPECT_EQ("value1", values[0]);
  4178. EXPECT_EQ("value2", values[1]);
  4179. EXPECT_EQ("value3", values[2]);
  4180. auto empty = req.get_param_values("nonexistent");
  4181. EXPECT_TRUE(empty.empty());
  4182. })
  4183. .Post("/validate-no-multiple-headers",
  4184. [&](const Request &req, Response & /*res*/) {
  4185. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4186. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4187. })
  4188. .Post("/content_receiver",
  4189. [&](const Request &req, Response &res,
  4190. const ContentReader &content_reader) {
  4191. if (req.is_multipart_form_data()) {
  4192. std::vector<FormData> items;
  4193. content_reader(
  4194. [&](const FormData &file) {
  4195. items.push_back(file);
  4196. return true;
  4197. },
  4198. [&](const char *data, size_t data_length) {
  4199. items.back().content.append(data, data_length);
  4200. return true;
  4201. });
  4202. EXPECT_EQ(5u, items.size());
  4203. {
  4204. const auto &file = get_file_value(items, "text1");
  4205. EXPECT_TRUE(file.filename.empty());
  4206. EXPECT_EQ("text default", file.content);
  4207. }
  4208. {
  4209. const auto &file = get_file_value(items, "text2");
  4210. EXPECT_TRUE(file.filename.empty());
  4211. EXPECT_EQ("aωb", file.content);
  4212. }
  4213. {
  4214. const auto &file = get_file_value(items, "file1");
  4215. EXPECT_EQ("hello.txt", file.filename);
  4216. EXPECT_EQ("text/plain", file.content_type);
  4217. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4218. }
  4219. {
  4220. const auto &file = get_file_value(items, "file2");
  4221. EXPECT_EQ("world.json", file.filename);
  4222. EXPECT_EQ("application/json", file.content_type);
  4223. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4224. }
  4225. {
  4226. const auto &file = get_file_value(items, "file3");
  4227. EXPECT_TRUE(file.filename.empty());
  4228. EXPECT_EQ("application/octet-stream", file.content_type);
  4229. EXPECT_EQ(0u, file.content.size());
  4230. }
  4231. } else {
  4232. std::string body;
  4233. content_reader([&](const char *data, size_t data_length) {
  4234. EXPECT_EQ(7U, data_length);
  4235. body.append(data, data_length);
  4236. return true;
  4237. });
  4238. EXPECT_EQ(body, "content");
  4239. res.set_content(body, "text/plain");
  4240. }
  4241. })
  4242. .Put("/content_receiver",
  4243. [&](const Request & /*req*/, Response &res,
  4244. const ContentReader &content_reader) {
  4245. std::string body;
  4246. content_reader([&](const char *data, size_t data_length) {
  4247. body.append(data, data_length);
  4248. return true;
  4249. });
  4250. EXPECT_EQ(body, "content");
  4251. res.set_content(body, "text/plain");
  4252. })
  4253. .Patch("/content_receiver",
  4254. [&](const Request & /*req*/, Response &res,
  4255. const ContentReader &content_reader) {
  4256. std::string body;
  4257. content_reader([&](const char *data, size_t data_length) {
  4258. body.append(data, data_length);
  4259. return true;
  4260. });
  4261. EXPECT_EQ(body, "content");
  4262. res.set_content(body, "text/plain");
  4263. })
  4264. .Post("/query-string-and-body",
  4265. [&](const Request &req, Response & /*res*/) {
  4266. ASSERT_TRUE(req.has_param("key"));
  4267. EXPECT_EQ(req.get_param_value("key"), "value");
  4268. EXPECT_EQ(req.body, "content");
  4269. })
  4270. .Get("/last-request",
  4271. [&](const Request &req, Response & /*res*/) {
  4272. EXPECT_EQ("close", req.get_header_value("Connection"));
  4273. })
  4274. .Get(R"(/redirect/(\d+))",
  4275. [&](const Request &req, Response &res) {
  4276. auto num = std::stoi(req.matches[1]) + 1;
  4277. std::string url = "/redirect/" + std::to_string(num);
  4278. res.set_redirect(url);
  4279. })
  4280. .Post("/binary",
  4281. [&](const Request &req, Response &res) {
  4282. EXPECT_EQ(4U, req.body.size());
  4283. EXPECT_EQ("application/octet-stream",
  4284. req.get_header_value("Content-Type"));
  4285. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4286. res.set_content(req.body, "application/octet-stream");
  4287. })
  4288. .Put("/binary",
  4289. [&](const Request &req, Response &res) {
  4290. EXPECT_EQ(4U, req.body.size());
  4291. EXPECT_EQ("application/octet-stream",
  4292. req.get_header_value("Content-Type"));
  4293. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4294. res.set_content(req.body, "application/octet-stream");
  4295. })
  4296. .Patch("/binary",
  4297. [&](const Request &req, Response &res) {
  4298. EXPECT_EQ(4U, req.body.size());
  4299. EXPECT_EQ("application/octet-stream",
  4300. req.get_header_value("Content-Type"));
  4301. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4302. res.set_content(req.body, "application/octet-stream");
  4303. })
  4304. .Delete("/binary",
  4305. [&](const Request &req, Response &res) {
  4306. EXPECT_EQ(4U, req.body.size());
  4307. EXPECT_EQ("application/octet-stream",
  4308. req.get_header_value("Content-Type"));
  4309. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4310. res.set_content(req.body, "application/octet-stream");
  4311. })
  4312. .Get("/issue1772",
  4313. [&](const Request & /*req*/, Response &res) {
  4314. res.status = 401;
  4315. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4316. })
  4317. .Delete("/issue609",
  4318. [](const httplib::Request &, httplib::Response &res,
  4319. const httplib::ContentReader &) {
  4320. res.set_content("ok", "text/plain");
  4321. })
  4322. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4323. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4324. .Get("/compress",
  4325. [&](const Request & /*req*/, Response &res) {
  4326. res.set_content(
  4327. "12345678901234567890123456789012345678901234567890123456789"
  4328. "01234567890123456789012345678901234567890",
  4329. "text/plain");
  4330. })
  4331. .Get("/compress-with-charset",
  4332. [&](const Request & /*req*/, Response &res) {
  4333. res.set_content(
  4334. "12345678901234567890123456789012345678901234567890123456789"
  4335. "01234567890123456789012345678901234567890",
  4336. "application/json; charset=utf-8");
  4337. })
  4338. .Get("/nocompress",
  4339. [&](const Request & /*req*/, Response &res) {
  4340. res.set_content(
  4341. "12345678901234567890123456789012345678901234567890123456789"
  4342. "01234567890123456789012345678901234567890",
  4343. "application/octet-stream");
  4344. })
  4345. .Post("/compress-multipart",
  4346. [&](const Request &req, Response & /*res*/) {
  4347. EXPECT_EQ(2u, req.form.fields.size());
  4348. ASSERT_TRUE(!req.form.has_field("???"));
  4349. {
  4350. const auto &text = req.form.get_field("key1");
  4351. EXPECT_EQ("test", text);
  4352. }
  4353. {
  4354. const auto &text = req.form.get_field("key2");
  4355. EXPECT_EQ("--abcdefg123", text);
  4356. }
  4357. })
  4358. #endif
  4359. ;
  4360. persons_["john"] = "programmer";
  4361. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4362. svr_.wait_until_ready();
  4363. }
  4364. virtual void TearDown() {
  4365. svr_.stop();
  4366. if (!request_threads_.empty()) {
  4367. std::this_thread::sleep_for(std::chrono::seconds(1));
  4368. for (auto &t : request_threads_) {
  4369. t.join();
  4370. }
  4371. }
  4372. t_.join();
  4373. }
  4374. map<string, string> persons_;
  4375. #ifdef CPPHTTPLIB_SSL_ENABLED
  4376. SSLClient cli_;
  4377. SSLServer svr_;
  4378. #else
  4379. Client cli_;
  4380. Server svr_;
  4381. #endif
  4382. thread t_;
  4383. std::vector<thread> request_threads_;
  4384. };
  4385. TEST_F(ServerTest, GetMethod200) {
  4386. auto res = cli_.Get("/hi");
  4387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4388. EXPECT_EQ("HTTP/1.1", res->version);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ("OK", res->reason);
  4391. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4392. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4393. EXPECT_EQ("Hello World!", res->body);
  4394. }
  4395. TEST_F(ServerTest, GetEmptyFile) {
  4396. auto res = cli_.Get("/empty_file");
  4397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4398. EXPECT_EQ(StatusCode::OK_200, res->status);
  4399. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4400. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4401. EXPECT_EQ("", res->body);
  4402. }
  4403. TEST_F(ServerTest, GetFileContent) {
  4404. auto res = cli_.Get("/file_content");
  4405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4406. EXPECT_EQ(StatusCode::OK_200, res->status);
  4407. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4408. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4409. EXPECT_EQ("test.html", res->body);
  4410. }
  4411. TEST_F(ServerTest, GetFileContentWithRange) {
  4412. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4415. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4416. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4417. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4418. EXPECT_EQ("est", res->body);
  4419. }
  4420. TEST_F(ServerTest, GetFileContentWithContentType) {
  4421. auto res = cli_.Get("/file_content_with_content_type");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4425. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4426. EXPECT_EQ("file\n", res->body);
  4427. }
  4428. TEST_F(ServerTest, GetInvalidFileContent) {
  4429. auto res = cli_.Get("/invalid_file_content");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4432. }
  4433. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4434. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4436. EXPECT_EQ("HTTP/1.1", res->version);
  4437. EXPECT_EQ(StatusCode::OK_200, res->status);
  4438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4439. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4440. EXPECT_EQ("Hello World!", res->body);
  4441. }
  4442. TEST_F(ServerTest, GetMethod302) {
  4443. auto res = cli_.Get("/");
  4444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4445. EXPECT_EQ(StatusCode::Found_302, res->status);
  4446. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4447. }
  4448. TEST_F(ServerTest, GetMethod302Redirect) {
  4449. cli_.set_follow_location(true);
  4450. auto res = cli_.Get("/");
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::OK_200, res->status);
  4453. EXPECT_EQ("Hello World!", res->body);
  4454. EXPECT_EQ("/hi", res->location);
  4455. }
  4456. TEST_F(ServerTest, GetMethod404) {
  4457. auto res = cli_.Get("/invalid");
  4458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4460. }
  4461. TEST_F(ServerTest, HeadMethod200) {
  4462. auto res = cli_.Head("/hi");
  4463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4464. EXPECT_EQ(StatusCode::OK_200, res->status);
  4465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4466. EXPECT_TRUE(res->body.empty());
  4467. }
  4468. TEST_F(ServerTest, HeadMethod200Static) {
  4469. auto res = cli_.Head("/mount/dir/index.html");
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::OK_200, res->status);
  4472. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4473. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4474. EXPECT_TRUE(res->body.empty());
  4475. }
  4476. TEST_F(ServerTest, HeadMethod404) {
  4477. auto res = cli_.Head("/invalid");
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4480. EXPECT_TRUE(res->body.empty());
  4481. }
  4482. TEST_F(ServerTest, GetMethodPersonJohn) {
  4483. auto res = cli_.Get("/person/john");
  4484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4485. EXPECT_EQ(StatusCode::OK_200, res->status);
  4486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4487. EXPECT_EQ("programmer", res->body);
  4488. }
  4489. TEST_F(ServerTest, PostMethod1) {
  4490. auto res = cli_.Get("/person/john1");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4493. res = cli_.Post("/person", "name=john1&note=coder",
  4494. "application/x-www-form-urlencoded");
  4495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4496. ASSERT_EQ(StatusCode::OK_200, res->status);
  4497. res = cli_.Get("/person/john1");
  4498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4499. ASSERT_EQ(StatusCode::OK_200, res->status);
  4500. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4501. ASSERT_EQ("coder", res->body);
  4502. }
  4503. TEST_F(ServerTest, PostMethod2) {
  4504. auto res = cli_.Get("/person/john2");
  4505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4506. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4507. Params params;
  4508. params.emplace("name", "john2");
  4509. params.emplace("note", "coder");
  4510. res = cli_.Post("/person", params);
  4511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4512. ASSERT_EQ(StatusCode::OK_200, res->status);
  4513. res = cli_.Get("/person/john2");
  4514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4515. ASSERT_EQ(StatusCode::OK_200, res->status);
  4516. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4517. ASSERT_EQ("coder", res->body);
  4518. }
  4519. TEST_F(ServerTest, PutMethod3) {
  4520. auto res = cli_.Get("/person/john3");
  4521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4522. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4523. Params params;
  4524. params.emplace("name", "john3");
  4525. params.emplace("note", "coder");
  4526. res = cli_.Put("/person", params);
  4527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4528. ASSERT_EQ(StatusCode::OK_200, res->status);
  4529. res = cli_.Get("/person/john3");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. ASSERT_EQ(StatusCode::OK_200, res->status);
  4532. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4533. ASSERT_EQ("coder", res->body);
  4534. }
  4535. TEST_F(ServerTest, DeleteMethod1) {
  4536. auto res = cli_.Get("/person/john4");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4539. Params params;
  4540. params.emplace("name", "john4");
  4541. params.emplace("note", "coder");
  4542. res = cli_.Post("/person", params);
  4543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4544. ASSERT_EQ(StatusCode::OK_200, res->status);
  4545. res = cli_.Get("/person/john4");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. ASSERT_EQ(StatusCode::OK_200, res->status);
  4548. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4549. ASSERT_EQ("coder", res->body);
  4550. Params delete_params;
  4551. delete_params.emplace("name", "john4");
  4552. res = cli_.Delete("/person", delete_params);
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. ASSERT_EQ(StatusCode::OK_200, res->status);
  4555. ASSERT_EQ("DELETED", res->body);
  4556. res = cli_.Get("/person/john4");
  4557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4558. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4559. }
  4560. TEST_F(ServerTest, DeleteMethod2) {
  4561. auto res = cli_.Get("/person/john5");
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4564. Params params;
  4565. params.emplace("name", "john5");
  4566. params.emplace("note", "developer");
  4567. res = cli_.Post("/person", params);
  4568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4569. ASSERT_EQ(StatusCode::OK_200, res->status);
  4570. res = cli_.Get("/person/john5");
  4571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4572. ASSERT_EQ(StatusCode::OK_200, res->status);
  4573. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4574. ASSERT_EQ("developer", res->body);
  4575. Params delete_params;
  4576. delete_params.emplace("name", "john5");
  4577. Headers headers;
  4578. headers.emplace("Custom-Header", "test-value");
  4579. res = cli_.Delete("/person", headers, delete_params);
  4580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4581. ASSERT_EQ(StatusCode::OK_200, res->status);
  4582. ASSERT_EQ("DELETED", res->body);
  4583. res = cli_.Get("/person/john5");
  4584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4585. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4586. }
  4587. TEST_F(ServerTest, DeleteMethod3) {
  4588. auto res = cli_.Get("/person/john6");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4591. Params params;
  4592. params.emplace("name", "john6");
  4593. params.emplace("note", "tester");
  4594. res = cli_.Post("/person", params);
  4595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4596. ASSERT_EQ(StatusCode::OK_200, res->status);
  4597. res = cli_.Get("/person/john6");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. ASSERT_EQ(StatusCode::OK_200, res->status);
  4600. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4601. ASSERT_EQ("tester", res->body);
  4602. Params delete_params;
  4603. delete_params.emplace("name", "john6");
  4604. Headers headers;
  4605. headers.emplace("Custom-Header", "test-value");
  4606. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4608. ASSERT_EQ(StatusCode::OK_200, res->status);
  4609. ASSERT_EQ("DELETED", res->body);
  4610. res = cli_.Get("/person/john6");
  4611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4612. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4613. }
  4614. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4615. Params params;
  4616. params.emplace("json", JSON_DATA);
  4617. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4619. ASSERT_EQ(StatusCode::OK_200, res->status);
  4620. ASSERT_EQ(JSON_DATA, res->body);
  4621. }
  4622. TEST_F(ServerTest, PostEmptyContent) {
  4623. auto res = cli_.Post("/empty", "", "text/plain");
  4624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4625. ASSERT_EQ(StatusCode::OK_200, res->status);
  4626. ASSERT_EQ("empty", res->body);
  4627. }
  4628. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4629. auto res = cli_.Post("/empty-no-content-type");
  4630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4631. ASSERT_EQ(StatusCode::OK_200, res->status);
  4632. ASSERT_EQ("empty-no-content-type", res->body);
  4633. }
  4634. TEST_F(ServerTest, PostPathOnly) {
  4635. auto res = cli_.Post("/path-only");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. ASSERT_EQ(StatusCode::OK_200, res->status);
  4638. ASSERT_EQ("path-only", res->body);
  4639. }
  4640. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4641. auto res = cli_.Post("/path-headers-only",
  4642. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4644. ASSERT_EQ(StatusCode::OK_200, res->status);
  4645. ASSERT_EQ("path-headers-only", res->body);
  4646. }
  4647. TEST_F(ServerTest, PostLarge) {
  4648. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. ASSERT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ(LARGE_DATA, res->body);
  4652. }
  4653. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4654. auto res = cli_.Put("/empty-no-content-type");
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. ASSERT_EQ(StatusCode::OK_200, res->status);
  4657. ASSERT_EQ("empty-no-content-type", res->body);
  4658. }
  4659. TEST_F(ServerTest, GetMethodDir) {
  4660. auto res = cli_.Get("/dir/");
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. EXPECT_EQ(StatusCode::OK_200, res->status);
  4663. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4664. auto body = R"(<html>
  4665. <head>
  4666. </head>
  4667. <body>
  4668. <a href="/dir/test.html">Test</a>
  4669. <a href="/hi">hi</a>
  4670. </body>
  4671. </html>
  4672. )";
  4673. EXPECT_EQ(body, res->body);
  4674. }
  4675. TEST_F(ServerTest, GetMethodDirTest) {
  4676. auto res = cli_.Get("/dir/test.html");
  4677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4678. EXPECT_EQ(StatusCode::OK_200, res->status);
  4679. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4680. EXPECT_EQ("test.html", res->body);
  4681. }
  4682. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4683. auto res = cli_.Get("/dir/../dir/test.html");
  4684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4687. EXPECT_EQ("test.html", res->body);
  4688. }
  4689. TEST_F(ServerTest, GetMethodInvalidPath) {
  4690. auto res = cli_.Get("/dir/../test.html");
  4691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4693. }
  4694. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4695. auto res = cli_.Get("/../www/dir/test.html");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4698. }
  4699. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4700. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4703. }
  4704. TEST_F(ServerTest, GetMethodDirMountTest) {
  4705. auto res = cli_.Get("/mount/dir/test.html");
  4706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4709. EXPECT_EQ("test.html", res->body);
  4710. }
  4711. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4712. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. EXPECT_EQ(StatusCode::OK_200, res->status);
  4715. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4716. EXPECT_EQ("test.html", res->body);
  4717. }
  4718. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4719. auto res = cli_.Get("/mount/dir/../test.html");
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4722. }
  4723. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4724. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4727. }
  4728. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4729. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4732. }
  4733. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4734. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4737. }
  4738. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4739. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4741. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4742. }
  4743. TEST_F(ServerTest, PostMethod303) {
  4744. auto res = cli_.Post("/1", "body", "text/plain");
  4745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4746. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4747. EXPECT_EQ("/2", res->get_header_value("Location"));
  4748. }
  4749. TEST_F(ServerTest, PostMethod303Redirect) {
  4750. cli_.set_follow_location(true);
  4751. auto res = cli_.Post("/1", "body", "text/plain");
  4752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4753. EXPECT_EQ(StatusCode::OK_200, res->status);
  4754. EXPECT_EQ("redirected.", res->body);
  4755. EXPECT_EQ("/2", res->location);
  4756. }
  4757. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4758. auto res = cli_.Get("/dir/test.abcde");
  4759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4762. EXPECT_EQ("abcde", res->body);
  4763. }
  4764. TEST_F(ServerTest, StaticFileRange) {
  4765. auto res =
  4766. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4769. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4770. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4771. EXPECT_EQ(true, res->has_header("Content-Range"));
  4772. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4773. EXPECT_EQ(std::string("cd"), res->body);
  4774. }
  4775. TEST_F(ServerTest, StaticFileRanges) {
  4776. auto res = cli_.Get("/dir/test.abcde",
  4777. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4779. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4780. EXPECT_TRUE(
  4781. res->get_header_value("Content-Type")
  4782. .find(
  4783. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4784. 0);
  4785. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4786. }
  4787. TEST_F(ServerTest, StaticFileRangeHead) {
  4788. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4791. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4792. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4793. EXPECT_EQ(true, res->has_header("Content-Range"));
  4794. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4795. }
  4796. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4797. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4801. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4802. EXPECT_EQ(true, res->has_header("Content-Range"));
  4803. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4804. res->get_header_value("Content-Range"));
  4805. EXPECT_EQ("LAST\n", res->body);
  4806. }
  4807. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4808. auto res =
  4809. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4813. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4814. EXPECT_EQ(true, res->has_header("Content-Range"));
  4815. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4816. }
  4817. TEST_F(ServerTest, StaticFileBigFile) {
  4818. auto res = cli_.Get("/dir/1MB.txt");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::OK_200, res->status);
  4821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4822. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4823. }
  4824. TEST_F(ServerTest, InvalidBaseDirMount) {
  4825. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4826. }
  4827. TEST_F(ServerTest, Binary) {
  4828. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4829. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4830. "application/octet-stream");
  4831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4832. ASSERT_EQ(StatusCode::OK_200, res->status);
  4833. ASSERT_EQ(4U, res->body.size());
  4834. res = cli_.Put("/binary", binary.data(), binary.size(),
  4835. "application/octet-stream");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. ASSERT_EQ(StatusCode::OK_200, res->status);
  4838. ASSERT_EQ(4U, res->body.size());
  4839. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4840. "application/octet-stream");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. ASSERT_EQ(StatusCode::OK_200, res->status);
  4843. ASSERT_EQ(4U, res->body.size());
  4844. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4845. "application/octet-stream");
  4846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4847. ASSERT_EQ(StatusCode::OK_200, res->status);
  4848. ASSERT_EQ(4U, res->body.size());
  4849. }
  4850. TEST_F(ServerTest, BinaryString) {
  4851. auto binary = std::string("\x00\x01\x02\x03", 4);
  4852. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. ASSERT_EQ(StatusCode::OK_200, res->status);
  4855. ASSERT_EQ(4U, res->body.size());
  4856. res = cli_.Put("/binary", binary, "application/octet-stream");
  4857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4858. ASSERT_EQ(StatusCode::OK_200, res->status);
  4859. ASSERT_EQ(4U, res->body.size());
  4860. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4862. ASSERT_EQ(StatusCode::OK_200, res->status);
  4863. ASSERT_EQ(4U, res->body.size());
  4864. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4866. ASSERT_EQ(StatusCode::OK_200, res->status);
  4867. ASSERT_EQ(4U, res->body.size());
  4868. }
  4869. TEST_F(ServerTest, EmptyRequest) {
  4870. auto res = cli_.Get("");
  4871. ASSERT_TRUE(!res);
  4872. EXPECT_EQ(Error::Connection, res.error());
  4873. }
  4874. TEST_F(ServerTest, LongRequest) {
  4875. std::string request;
  4876. for (size_t i = 0; i < 545; i++) {
  4877. request += "/TooLongRequest";
  4878. }
  4879. request += "OK";
  4880. auto res = cli_.Get(request.c_str());
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4883. }
  4884. TEST_F(ServerTest, TooLongRequest) {
  4885. std::string request;
  4886. for (size_t i = 0; i < 546; i++) {
  4887. request += "/TooLongRequest";
  4888. }
  4889. request += "_NG";
  4890. auto start = std::chrono::high_resolution_clock::now();
  4891. cli_.set_keep_alive(true);
  4892. auto res = cli_.Get(request.c_str());
  4893. auto end = std::chrono::high_resolution_clock::now();
  4894. auto elapsed =
  4895. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4896. .count();
  4897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4898. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4899. EXPECT_LE(elapsed, 1000);
  4900. EXPECT_EQ("close", res->get_header_value("Connection"));
  4901. EXPECT_FALSE(cli_.is_socket_open());
  4902. }
  4903. TEST_F(ServerTest, AlmostTooLongRequest) {
  4904. // test for #2046 - URI length check shouldn't include other content on req
  4905. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4906. // leading /, space, HTTP/1.1)
  4907. std::string request =
  4908. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4909. auto res = cli_.Get(request.c_str());
  4910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4912. }
  4913. TEST_F(ServerTest, LongHeader) {
  4914. Request req;
  4915. req.method = "GET";
  4916. req.path = "/hi";
  4917. std::string host_and_port;
  4918. host_and_port += HOST;
  4919. host_and_port += ":";
  4920. host_and_port += std::to_string(PORT);
  4921. req.headers.emplace("Host", host_and_port.c_str());
  4922. req.headers.emplace("Accept", "*/*");
  4923. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4924. req.headers.emplace(
  4925. "Header-Name",
  4926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4954. "@@@@@@@@@@@@@@@@");
  4955. auto res = std::make_shared<Response>();
  4956. auto error = Error::Success;
  4957. auto ret = cli_.send(req, *res, error);
  4958. ASSERT_TRUE(ret);
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. }
  4961. TEST_F(ServerTest, LongQueryValue) {
  4962. auto start = std::chrono::high_resolution_clock::now();
  4963. cli_.set_keep_alive(true);
  4964. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4965. auto end = std::chrono::high_resolution_clock::now();
  4966. auto elapsed =
  4967. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4968. .count();
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4971. EXPECT_LE(elapsed, 1000);
  4972. EXPECT_EQ("close", res->get_header_value("Connection"));
  4973. EXPECT_FALSE(cli_.is_socket_open());
  4974. }
  4975. TEST_F(ServerTest, TooLongQueryValue) {
  4976. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4977. ASSERT_FALSE(res);
  4978. EXPECT_EQ(Error::Read, res.error());
  4979. }
  4980. TEST_F(ServerTest, TooLongHeader) {
  4981. Request req;
  4982. req.method = "GET";
  4983. req.path = "/hi";
  4984. std::string host_and_port;
  4985. host_and_port += HOST;
  4986. host_and_port += ":";
  4987. host_and_port += std::to_string(PORT);
  4988. req.headers.emplace("Host", host_and_port.c_str());
  4989. req.headers.emplace("Accept", "*/*");
  4990. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4991. req.headers.emplace(
  4992. "Header-Name",
  4993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5021. "@@@@@@@@@@@@@@@@@");
  5022. auto res = std::make_shared<Response>();
  5023. auto error = Error::Success;
  5024. auto ret = cli_.send(req, *res, error);
  5025. ASSERT_TRUE(ret);
  5026. EXPECT_EQ(StatusCode::OK_200, res->status);
  5027. }
  5028. TEST_F(ServerTest, HeaderCountAtLimit) {
  5029. // Test with headers just under the 100 limit
  5030. httplib::Headers headers;
  5031. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5032. // This should keep us just under the 100 header limit
  5033. for (int i = 0; i < 95; i++) {
  5034. std::string name = "X-Test-Header-" + std::to_string(i);
  5035. std::string value = "value" + std::to_string(i);
  5036. headers.emplace(name, value);
  5037. }
  5038. // This should work fine as we're under the limit
  5039. auto res = cli_.Get("/hi", headers);
  5040. EXPECT_TRUE(res);
  5041. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5042. }
  5043. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5044. // Test with many headers to exceed the 100 limit
  5045. httplib::Headers headers;
  5046. // Add 150 headers to definitely exceed the 100 limit
  5047. for (int i = 0; i < 150; i++) {
  5048. std::string name = "X-Test-Header-" + std::to_string(i);
  5049. std::string value = "value" + std::to_string(i);
  5050. headers.emplace(name, value);
  5051. }
  5052. // This should fail due to exceeding header count limit
  5053. cli_.set_keep_alive(true);
  5054. auto res = cli_.Get("/hi", headers);
  5055. // The server should respond with 400 Bad Request
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5058. EXPECT_EQ("close", res->get_header_value("Connection"));
  5059. EXPECT_FALSE(cli_.is_socket_open());
  5060. }
  5061. TEST_F(ServerTest, PercentEncoding) {
  5062. auto res = cli_.Get("/e%6edwith%");
  5063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5064. EXPECT_EQ(StatusCode::OK_200, res->status);
  5065. }
  5066. TEST_F(ServerTest, PercentEncodingUnicode) {
  5067. auto res = cli_.Get("/e%u006edwith%");
  5068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5069. EXPECT_EQ(StatusCode::OK_200, res->status);
  5070. }
  5071. TEST_F(ServerTest, InvalidPercentEncoding) {
  5072. auto res = cli_.Get("/%endwith%");
  5073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5075. }
  5076. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5077. auto res = cli_.Get("/%uendwith%");
  5078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5080. }
  5081. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5082. auto res = cli_.Get("/hello?aaa=bbb%");
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5085. }
  5086. TEST_F(ServerTest, PlusSignEncoding) {
  5087. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5089. EXPECT_EQ(StatusCode::OK_200, res->status);
  5090. EXPECT_EQ("a +b", res->body);
  5091. }
  5092. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5093. // This test simulates a potential DoS attack using many headers
  5094. // to verify our security fix prevents memory exhaustion
  5095. httplib::Headers attack_headers;
  5096. // Attempt to add many headers like an attacker would (200 headers to far
  5097. // exceed limit)
  5098. for (int i = 0; i < 200; i++) {
  5099. std::string name = "X-Attack-Header-" + std::to_string(i);
  5100. std::string value = "attack_payload_" + std::to_string(i);
  5101. attack_headers.emplace(name, value);
  5102. }
  5103. // Try to POST with excessive headers
  5104. cli_.set_keep_alive(true);
  5105. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5106. // Should either fail or return 400 Bad Request due to security limit
  5107. if (res) {
  5108. // If we get a response, it should be 400 Bad Request
  5109. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5110. EXPECT_EQ("close", res->get_header_value("Connection"));
  5111. }
  5112. EXPECT_FALSE(cli_.is_socket_open());
  5113. }
  5114. TEST_F(ServerTest, MultipartFormData) {
  5115. UploadFormDataItems items = {
  5116. {"text1", "text default", "", ""},
  5117. {"text2", "aωb", "", ""},
  5118. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5119. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5120. {"file3", "", "", "application/octet-stream"},
  5121. {"file4", "", "", " application/json tmp-string "}};
  5122. auto res = cli_.Post("/multipart", items);
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. }
  5126. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5127. UploadFormDataItems items = {
  5128. {"text", "default text", "", ""},
  5129. {"multi_text1", "aaaaa", "", ""},
  5130. {"multi_text1", "bbbbb", "", ""},
  5131. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5132. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5133. "application/json"},
  5134. };
  5135. auto res = cli_.Post("/multipart/multi_file_values", items);
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. EXPECT_EQ(StatusCode::OK_200, res->status);
  5138. }
  5139. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5140. auto res = cli_.Get("/hi");
  5141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5144. EXPECT_EQ("Hello World!", res->body);
  5145. }
  5146. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5147. Request req;
  5148. req.method = "POST";
  5149. req.path = "/chunked";
  5150. std::string host_and_port;
  5151. host_and_port += HOST;
  5152. host_and_port += ":";
  5153. host_and_port += std::to_string(PORT);
  5154. req.headers.emplace("Host", host_and_port.c_str());
  5155. req.headers.emplace("Accept", "*/*");
  5156. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5157. req.headers.emplace("Content-Type", "text/plain");
  5158. req.headers.emplace("Content-Length", "0");
  5159. req.headers.emplace(
  5160. "Transfer-Encoding",
  5161. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5162. // Client does not chunk, so make a chunked body manually.
  5163. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5164. auto res = std::make_shared<Response>();
  5165. auto error = Error::Success;
  5166. auto ret = cli_.send(req, *res, error);
  5167. ASSERT_TRUE(ret);
  5168. EXPECT_EQ(StatusCode::OK_200, res->status);
  5169. }
  5170. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5171. // rather than treat them as valid lengths.
  5172. template <typename ClientT>
  5173. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5174. Request req;
  5175. req.method = "POST";
  5176. req.path = "/chunked";
  5177. std::string host_and_port;
  5178. host_and_port += HOST;
  5179. host_and_port += ":";
  5180. host_and_port += std::to_string(PORT);
  5181. req.headers.emplace("Host", host_and_port.c_str());
  5182. req.headers.emplace("Content-Length", "0");
  5183. req.headers.emplace("Transfer-Encoding", "chunked");
  5184. req.body = body;
  5185. auto res = std::make_shared<Response>();
  5186. auto error = Error::Success;
  5187. ASSERT_TRUE(cli.send(req, *res, error));
  5188. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5189. }
  5190. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5191. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5192. }
  5193. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5194. expect_chunked_body_rejected(
  5195. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5196. }
  5197. TEST_F(ServerTest, GetStreamed2) {
  5198. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5201. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5202. EXPECT_EQ(true, res->has_header("Content-Range"));
  5203. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5204. EXPECT_EQ(std::string("ab"), res->body);
  5205. }
  5206. TEST_F(ServerTest, GetStreamed) {
  5207. auto res = cli_.Get("/streamed");
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5211. EXPECT_EQ(std::string("aaabbb"), res->body);
  5212. }
  5213. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5214. auto res = cli_.Get("/streamed-without-length",
  5215. Headers{make_range_header({{0, -1}})});
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ(false, res->has_header("Content-Length"));
  5219. EXPECT_EQ(false, res->has_header("Content-Range"));
  5220. EXPECT_EQ(std::string("abcdefg"), res->body);
  5221. }
  5222. TEST_F(ServerTest, GetStreamedWithRange1) {
  5223. auto res =
  5224. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5227. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5228. EXPECT_EQ(true, res->has_header("Content-Range"));
  5229. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5230. EXPECT_EQ(std::string("def"), res->body);
  5231. }
  5232. TEST_F(ServerTest, GetStreamedWithRange2) {
  5233. auto res =
  5234. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5236. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5237. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5238. EXPECT_EQ(true, res->has_header("Content-Range"));
  5239. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5240. EXPECT_EQ(std::string("bcdefg"), res->body);
  5241. }
  5242. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5243. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5246. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5247. EXPECT_EQ(true, res->has_header("Content-Range"));
  5248. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5249. EXPECT_EQ(std::string("efg"), res->body);
  5250. }
  5251. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5252. auto res =
  5253. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5256. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5257. EXPECT_EQ(false, res->has_header("Content-Range"));
  5258. EXPECT_EQ(0U, res->body.size());
  5259. }
  5260. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5261. // Only a 206 is served as a partial representation. Under any other status
  5262. // `apply_ranges()` reported the full content length, so the body must match
  5263. // that header, and the content provider must never be asked for an offset
  5264. // outside the representation.
  5265. auto check = [&](int status, const char *range) {
  5266. auto path =
  5267. std::string("/streamed-with-range?status=") + std::to_string(status);
  5268. auto ctx = path + " Range: " + range;
  5269. auto res = cli_.Get(path, Headers{{"Range", range}});
  5270. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5271. EXPECT_EQ(status, res->status) << ctx;
  5272. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5274. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5275. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5276. };
  5277. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5278. check(403, "bytes=3-5");
  5279. // The offset is far past the representation.
  5280. check(403, "bytes=100000-100200");
  5281. // `first_pos` is still -1 here, and the bounds asserts in
  5282. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5283. check(403, "bytes=-3");
  5284. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5285. // multipart branch would have written one that is empty.
  5286. check(403, "bytes=1-2, 4-5");
  5287. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5288. // covers the whole representation.
  5289. check(200, "bytes=3-5");
  5290. check(200, "bytes=1-2, 4-5");
  5291. }
  5292. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5293. auto res =
  5294. cli_.Get("/streamed-with-range",
  5295. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5296. "92233720368547758079223372036854775807"}});
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5299. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5300. EXPECT_EQ(false, res->has_header("Content-Range"));
  5301. EXPECT_EQ(0U, res->body.size());
  5302. }
  5303. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5304. auto res = cli_.Get(
  5305. "/with-range",
  5306. Headers{{"Range",
  5307. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5308. {"Accept-Encoding", ""}});
  5309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5311. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5312. EXPECT_EQ(true, res->has_header("Content-Range"));
  5313. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5314. EXPECT_EQ(std::string("abcdefg"), res->body);
  5315. }
  5316. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5317. auto res = cli_.Get("/with-range", Headers{
  5318. {"Range", "bytes=0-"},
  5319. {"Accept-Encoding", ""},
  5320. });
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5323. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5324. EXPECT_EQ(true, res->has_header("Content-Range"));
  5325. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5326. EXPECT_EQ(std::string("abcdefg"), res->body);
  5327. }
  5328. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5329. auto res = cli_.Get("/streamed-with-range",
  5330. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5333. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5334. EXPECT_EQ(false, res->has_header("Content-Range"));
  5335. EXPECT_EQ(267U, res->body.size());
  5336. // Check that both range contents are present
  5337. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5338. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5339. // Check that Content-Range headers are present for both ranges
  5340. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5341. std::string::npos);
  5342. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5343. std::string::npos);
  5344. }
  5345. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5346. Ranges ranges;
  5347. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5348. ranges.emplace_back(0, -1);
  5349. }
  5350. auto res = cli_.Get("/streamed-with-range?error",
  5351. Headers{{make_range_header(ranges)}});
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5354. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5355. EXPECT_EQ(false, res->has_header("Content-Range"));
  5356. EXPECT_EQ(0U, res->body.size());
  5357. }
  5358. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5359. auto res = cli_.Get("/streamed-with-range",
  5360. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5363. EXPECT_EQ(5U, res->body.size());
  5364. // Check that overlapping ranges are coalesced into a single range
  5365. EXPECT_EQ("bcdef", res->body);
  5366. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5367. // Should be single range, not multipart
  5368. EXPECT_TRUE(res->has_header("Content-Range"));
  5369. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5370. }
  5371. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5372. auto res = cli_.Get("/streamed-with-range",
  5373. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5376. EXPECT_EQ(268U, res->body.size());
  5377. // Check that both range contents are present
  5378. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5379. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5380. // Check that Content-Range headers are present for both ranges
  5381. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5382. std::string::npos);
  5383. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5384. std::string::npos);
  5385. }
  5386. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5387. auto res = cli_.Get("/streamed-with-range",
  5388. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5391. EXPECT_EQ(269U, res->body.size());
  5392. // Check that both duplicate range contents are present
  5393. size_t first_abc = res->body.find("abc\r\n");
  5394. EXPECT_TRUE(first_abc != std::string::npos);
  5395. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5396. EXPECT_TRUE(second_abc != std::string::npos);
  5397. // Check that Content-Range headers are present for both ranges
  5398. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5399. EXPECT_TRUE(first_range != std::string::npos);
  5400. size_t second_range =
  5401. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5402. EXPECT_TRUE(second_range != std::string::npos);
  5403. }
  5404. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5405. auto res =
  5406. cli_.Get("/streamed-with-range?error",
  5407. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5409. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5410. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5411. EXPECT_EQ(false, res->has_header("Content-Range"));
  5412. EXPECT_EQ(0U, res->body.size());
  5413. }
  5414. TEST_F(ServerTest, GetStreamedEndless) {
  5415. uint64_t offset = 0;
  5416. auto res = cli_.Get("/streamed-cancel",
  5417. [&](const char * /*data*/, uint64_t data_length) {
  5418. if (offset < 100) {
  5419. offset += data_length;
  5420. return true;
  5421. }
  5422. return false;
  5423. });
  5424. ASSERT_TRUE(!res);
  5425. EXPECT_EQ(Error::Canceled, res.error());
  5426. }
  5427. TEST_F(ServerTest, ClientStop) {
  5428. std::atomic_size_t count{4};
  5429. std::vector<std::thread> threads;
  5430. for (auto i = count.load(); i != 0; --i) {
  5431. threads.emplace_back([&]() {
  5432. auto res = cli_.Get("/streamed-cancel",
  5433. [&](const char *, uint64_t) { return true; });
  5434. --count;
  5435. ASSERT_TRUE(!res);
  5436. EXPECT_TRUE(res.error() == Error::Canceled ||
  5437. res.error() == Error::Read || res.error() == Error::Write);
  5438. });
  5439. }
  5440. std::this_thread::sleep_for(std::chrono::seconds(2));
  5441. while (count != 0) {
  5442. cli_.stop();
  5443. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5444. }
  5445. for (auto &t : threads) {
  5446. t.join();
  5447. }
  5448. }
  5449. TEST_F(ServerTest, GetWithRange1) {
  5450. auto res = cli_.Get("/with-range", Headers{
  5451. make_range_header({{3, 5}}),
  5452. {"Accept-Encoding", ""},
  5453. });
  5454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5455. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5456. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5457. EXPECT_EQ(true, res->has_header("Content-Range"));
  5458. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5459. EXPECT_EQ(std::string("def"), res->body);
  5460. }
  5461. TEST_F(ServerTest, GetWithRange2) {
  5462. auto res = cli_.Get("/with-range", Headers{
  5463. make_range_header({{1, -1}}),
  5464. {"Accept-Encoding", ""},
  5465. });
  5466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5468. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5469. EXPECT_EQ(true, res->has_header("Content-Range"));
  5470. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5471. EXPECT_EQ(std::string("bcdefg"), res->body);
  5472. }
  5473. TEST_F(ServerTest, GetWithRange3) {
  5474. auto res = cli_.Get("/with-range", Headers{
  5475. make_range_header({{0, 0}}),
  5476. {"Accept-Encoding", ""},
  5477. });
  5478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5479. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5480. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5481. EXPECT_EQ(true, res->has_header("Content-Range"));
  5482. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5483. EXPECT_EQ(std::string("a"), res->body);
  5484. }
  5485. TEST_F(ServerTest, GetWithRange4) {
  5486. auto res = cli_.Get("/with-range", Headers{
  5487. make_range_header({{-1, 2}}),
  5488. {"Accept-Encoding", ""},
  5489. });
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5492. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5493. EXPECT_EQ(true, res->has_header("Content-Range"));
  5494. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5495. EXPECT_EQ(std::string("fg"), res->body);
  5496. }
  5497. TEST_F(ServerTest, GetWithRange5) {
  5498. auto res = cli_.Get("/with-range", Headers{
  5499. make_range_header({{0, 5}}),
  5500. {"Accept-Encoding", ""},
  5501. });
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5504. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5505. EXPECT_EQ(true, res->has_header("Content-Range"));
  5506. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5507. EXPECT_EQ(std::string("abcdef"), res->body);
  5508. }
  5509. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5510. auto res =
  5511. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5514. }
  5515. TEST_F(ServerTest, GetWithRangeMultipart) {
  5516. auto res =
  5517. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5519. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5520. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5521. EXPECT_EQ(false, res->has_header("Content-Range"));
  5522. EXPECT_EQ(267U, res->body.size());
  5523. }
  5524. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5525. auto res = cli_.Get("/with-range",
  5526. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5529. }
  5530. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5531. auto res = cli_.Get("/with-range-customized-response",
  5532. Headers{{make_range_header({{1, 2}})}});
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5535. EXPECT_EQ(true, res->has_header("Content-Length"));
  5536. EXPECT_EQ(false, res->has_header("Content-Range"));
  5537. EXPECT_EQ(JSON_DATA, res->body);
  5538. }
  5539. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5540. auto res = cli_.Get("/with-range-customized-response",
  5541. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5544. EXPECT_EQ(true, res->has_header("Content-Length"));
  5545. EXPECT_EQ(false, res->has_header("Content-Range"));
  5546. EXPECT_EQ(JSON_DATA, res->body);
  5547. }
  5548. TEST_F(ServerTest, Issue1772) {
  5549. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5551. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5552. }
  5553. TEST_F(ServerTest, Issue609) {
  5554. auto res = cli_.Delete("/issue609");
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ(std::string("ok"), res->body);
  5558. }
  5559. TEST_F(ServerTest, GetStreamedChunked) {
  5560. auto res = cli_.Get("/streamed-chunked");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ(std::string("123456789"), res->body);
  5564. }
  5565. TEST_F(ServerTest, GetStreamedChunked2) {
  5566. auto res = cli_.Get("/streamed-chunked2");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ(std::string("123456789"), res->body);
  5570. }
  5571. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5572. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ(StatusCode::OK_200, res->status);
  5575. EXPECT_EQ(std::string("123456789"), res->body);
  5576. EXPECT_TRUE(res->has_header("Trailer"));
  5577. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5578. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5579. // Trailers are now stored separately from headers (security fix)
  5580. EXPECT_EQ(2U, res->trailers.size());
  5581. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5582. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5583. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5584. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5585. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5586. // Verify trailers are NOT in headers (security verification)
  5587. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5588. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5589. }
  5590. TEST_F(ServerTest, LargeChunkedPost) {
  5591. Request req;
  5592. req.method = "POST";
  5593. req.path = "/large-chunked";
  5594. std::string host_and_port;
  5595. host_and_port += HOST;
  5596. host_and_port += ":";
  5597. host_and_port += std::to_string(PORT);
  5598. req.headers.emplace("Host", host_and_port.c_str());
  5599. req.headers.emplace("Accept", "*/*");
  5600. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5601. req.headers.emplace("Content-Type", "text/plain");
  5602. req.headers.emplace("Content-Length", "0");
  5603. req.headers.emplace("Transfer-Encoding", "chunked");
  5604. std::string long_string(30 * 1024u, 'a');
  5605. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5606. // Attempt to make a large enough post to exceed OS buffers, to test that
  5607. // the server handles short reads if the full chunk data isn't available.
  5608. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5609. auto res = std::make_shared<Response>();
  5610. auto error = Error::Success;
  5611. auto ret = cli_.send(req, *res, error);
  5612. ASSERT_TRUE(ret);
  5613. EXPECT_EQ(StatusCode::OK_200, res->status);
  5614. }
  5615. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5616. auto res = cli_.Get("/remote_addr");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5620. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5621. }
  5622. TEST_F(ServerTest, GetMethodLocalAddr) {
  5623. auto res = cli_.Get("/local_addr");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. EXPECT_EQ(StatusCode::OK_200, res->status);
  5626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5627. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5628. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5629. }
  5630. TEST_F(ServerTest, HTTPResponseSplitting) {
  5631. auto res = cli_.Get("/http_response_splitting");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. EXPECT_EQ(StatusCode::OK_200, res->status);
  5634. }
  5635. TEST_F(ServerTest, SlowRequest) {
  5636. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5637. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5638. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5639. }
  5640. #if 0
  5641. TEST_F(ServerTest, SlowPost) {
  5642. char buffer[64 * 1024];
  5643. memset(buffer, 0x42, sizeof(buffer));
  5644. auto res = cli_.Post(
  5645. "/slowpost", 64 * 1024 * 1024,
  5646. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5647. auto ret = sink.write(buffer, sizeof(buffer));
  5648. EXPECT_TRUE(ret);
  5649. return true;
  5650. },
  5651. "text/plain");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. }
  5655. TEST_F(ServerTest, SlowPostFail) {
  5656. char buffer[64 * 1024];
  5657. memset(buffer, 0x42, sizeof(buffer));
  5658. cli_.set_write_timeout(std::chrono::seconds(0));
  5659. auto res = cli_.Post(
  5660. "/slowpost", 64 * 1024 * 1024,
  5661. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5662. sink.write(buffer, sizeof(buffer));
  5663. return true;
  5664. },
  5665. "text/plain");
  5666. ASSERT_TRUE(!res);
  5667. EXPECT_EQ(Error::Write, res.error());
  5668. }
  5669. #endif
  5670. TEST_F(ServerTest, Put) {
  5671. auto res = cli_.Put("/put", "PUT", "text/plain");
  5672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5673. EXPECT_EQ(StatusCode::OK_200, res->status);
  5674. EXPECT_EQ("PUT", res->body);
  5675. }
  5676. TEST_F(ServerTest, PutWithContentProvider) {
  5677. auto res = cli_.Put(
  5678. "/put", 3,
  5679. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5680. sink.os << "PUT";
  5681. return true;
  5682. },
  5683. "text/plain");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. EXPECT_EQ(StatusCode::OK_200, res->status);
  5686. EXPECT_EQ("PUT", res->body);
  5687. }
  5688. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5689. auto res = cli_.Post(
  5690. "/post", 42,
  5691. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5692. return false;
  5693. },
  5694. "text/plain");
  5695. ASSERT_TRUE(!res);
  5696. EXPECT_EQ(Error::Canceled, res.error());
  5697. }
  5698. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5699. auto res = cli_.Put(
  5700. "/put",
  5701. [](size_t /*offset*/, DataSink &sink) {
  5702. sink.os << "PUT";
  5703. sink.done();
  5704. return true;
  5705. },
  5706. "text/plain");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. EXPECT_EQ(StatusCode::OK_200, res->status);
  5709. EXPECT_EQ("PUT", res->body);
  5710. }
  5711. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5712. auto res = cli_.Post(
  5713. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5714. "text/plain");
  5715. ASSERT_TRUE(!res);
  5716. EXPECT_EQ(Error::Canceled, res.error());
  5717. }
  5718. TEST_F(ServerTest, PostLoopBack) {
  5719. std::string body;
  5720. auto res = cli_.Post(
  5721. "/post-loopback", 9,
  5722. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5723. EXPECT_EQ(9u, length);
  5724. sink.write("123", 3);
  5725. sink.write("456", 3);
  5726. sink.write("789", 3);
  5727. return true;
  5728. },
  5729. "text/plain",
  5730. [&body](const char *data, size_t data_length) {
  5731. body.append(data, data_length);
  5732. return true;
  5733. });
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::OK_200, res->status);
  5736. EXPECT_EQ("123456789", body);
  5737. }
  5738. TEST_F(ServerTest, PutLoopBack) {
  5739. std::string body;
  5740. auto res = cli_.Put(
  5741. "/put-loopback", 9,
  5742. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5743. EXPECT_EQ(9u, length);
  5744. sink.write("123", 3);
  5745. sink.write("456", 3);
  5746. sink.write("789", 3);
  5747. return true;
  5748. },
  5749. "text/plain",
  5750. [&body](const char *data, size_t data_length) {
  5751. body.append(data, data_length);
  5752. return true;
  5753. });
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. EXPECT_EQ("123456789", body);
  5757. }
  5758. TEST_F(ServerTest, PatchLoopBack) {
  5759. std::string body;
  5760. auto res = cli_.Patch(
  5761. "/patch-loopback", 9,
  5762. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5763. EXPECT_EQ(9u, length);
  5764. sink.write("123", 3);
  5765. sink.write("456", 3);
  5766. sink.write("789", 3);
  5767. return true;
  5768. },
  5769. "text/plain",
  5770. [&body](const char *data, size_t data_length) {
  5771. body.append(data, data_length);
  5772. return true;
  5773. });
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_EQ("123456789", body);
  5777. }
  5778. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5779. std::string body;
  5780. auto res = cli_.Post(
  5781. "/post-loopback",
  5782. [](size_t /*offset*/, DataSink &sink) {
  5783. sink.write("123", 3);
  5784. sink.write("456", 3);
  5785. sink.write("789", 3);
  5786. sink.done();
  5787. return true;
  5788. },
  5789. "text/plain",
  5790. [&body](const char *data, size_t data_length) {
  5791. body.append(data, data_length);
  5792. return true;
  5793. });
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ("123456789", body);
  5797. }
  5798. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5799. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5800. cli_.set_compress(true);
  5801. auto res = cli_.Put(
  5802. "/put", 3,
  5803. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5804. sink.os << "PUT";
  5805. return true;
  5806. },
  5807. "text/plain");
  5808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. EXPECT_EQ("PUT", res->body);
  5811. }
  5812. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5813. cli_.set_compress(true);
  5814. auto res = cli_.Post(
  5815. "/post", 42,
  5816. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5817. return false;
  5818. },
  5819. "text/plain");
  5820. ASSERT_TRUE(!res);
  5821. EXPECT_EQ(Error::Canceled, res.error());
  5822. }
  5823. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5824. cli_.set_compress(true);
  5825. auto res = cli_.Put(
  5826. "/put",
  5827. [](size_t /*offset*/, DataSink &sink) {
  5828. sink.os << "PUT";
  5829. sink.done();
  5830. return true;
  5831. },
  5832. "text/plain");
  5833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5834. EXPECT_EQ(StatusCode::OK_200, res->status);
  5835. EXPECT_EQ("PUT", res->body);
  5836. }
  5837. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5838. cli_.set_compress(true);
  5839. auto res = cli_.Post(
  5840. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5841. "text/plain");
  5842. ASSERT_TRUE(!res);
  5843. EXPECT_EQ(Error::Canceled, res.error());
  5844. }
  5845. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5846. cli_.set_compress(true);
  5847. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. EXPECT_EQ(StatusCode::OK_200, res->status);
  5850. EXPECT_EQ(LARGE_DATA, res->body);
  5851. }
  5852. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5853. #ifdef CPPHTTPLIB_SSL_ENABLED
  5854. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5855. Client cli(s.c_str());
  5856. cli.enable_server_certificate_verification(false);
  5857. #else
  5858. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5859. Client cli(s.c_str());
  5860. #endif
  5861. cli.set_compress(true);
  5862. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. EXPECT_EQ(LARGE_DATA, res->body);
  5866. // The compressed size should be less than a 10th of the original. May vary
  5867. // depending on the zlib library.
  5868. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5869. static_cast<uint64_t>(10 * 1024 * 1024));
  5870. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5871. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5872. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5873. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5874. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5875. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5876. #endif
  5877. }
  5878. TEST_F(ServerTest, PutContentWithDeflate) {
  5879. cli_.set_compress(false);
  5880. Headers headers;
  5881. headers.emplace("Content-Encoding", "deflate");
  5882. // PUT in deflate format:
  5883. auto res = cli_.Put("/put", headers,
  5884. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5886. EXPECT_EQ(StatusCode::OK_200, res->status);
  5887. EXPECT_EQ("PUT", res->body);
  5888. }
  5889. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5890. Headers headers;
  5891. headers.emplace("Accept-Encoding", "gzip, deflate");
  5892. auto res = cli_.Get("/streamed-chunked", headers);
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::OK_200, res->status);
  5895. EXPECT_EQ(std::string("123456789"), res->body);
  5896. }
  5897. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5898. Headers headers;
  5899. headers.emplace("Accept-Encoding", "gzip, deflate");
  5900. auto res = cli_.Get("/streamed-chunked2", headers);
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ(std::string("123456789"), res->body);
  5904. }
  5905. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5906. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. }
  5910. TEST(GzipDecompressor, ChunkedDecompression) {
  5911. std::string data;
  5912. for (size_t i = 0; i < 32 * 1024; ++i) {
  5913. data.push_back(static_cast<char>('a' + i % 26));
  5914. }
  5915. std::string compressed_data;
  5916. {
  5917. httplib::detail::gzip_compressor compressor;
  5918. bool result = compressor.compress(
  5919. data.data(), data.size(),
  5920. /*last=*/true,
  5921. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5922. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5923. compressed_data_size);
  5924. return true;
  5925. });
  5926. ASSERT_TRUE(result);
  5927. }
  5928. std::string decompressed_data;
  5929. {
  5930. httplib::detail::gzip_decompressor decompressor;
  5931. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5932. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5933. size_t chunk_size = 130;
  5934. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5935. chunk_begin += chunk_size) {
  5936. size_t current_chunk_size =
  5937. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5938. bool result = decompressor.decompress(
  5939. compressed_data.data() + chunk_begin, current_chunk_size,
  5940. [&](const char *decompressed_data_chunk,
  5941. size_t decompressed_data_chunk_size) {
  5942. decompressed_data.insert(decompressed_data.size(),
  5943. decompressed_data_chunk,
  5944. decompressed_data_chunk_size);
  5945. return true;
  5946. });
  5947. ASSERT_TRUE(result);
  5948. }
  5949. }
  5950. ASSERT_EQ(data, decompressed_data);
  5951. }
  5952. TEST(GzipDecompressor, DeflateDecompression) {
  5953. std::string original_text = "Raw deflate without gzip";
  5954. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5955. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5956. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5957. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5958. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5959. std::string decompressed_data;
  5960. {
  5961. httplib::detail::gzip_decompressor decompressor;
  5962. bool result = decompressor.decompress(
  5963. compressed_data.data(), compressed_data.size(),
  5964. [&](const char *decompressed_data_chunk,
  5965. size_t decompressed_data_chunk_size) {
  5966. decompressed_data.insert(decompressed_data.size(),
  5967. decompressed_data_chunk,
  5968. decompressed_data_chunk_size);
  5969. return true;
  5970. });
  5971. ASSERT_TRUE(result);
  5972. }
  5973. ASSERT_EQ(original_text, decompressed_data);
  5974. }
  5975. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5976. std::string original_text = "Raw deflate without gzip";
  5977. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5978. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5979. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5980. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5981. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5982. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5983. std::string decompressed_data;
  5984. {
  5985. httplib::detail::gzip_decompressor decompressor;
  5986. bool result = decompressor.decompress(
  5987. compressed_data.data(), compressed_data.size(),
  5988. [&](const char *decompressed_data_chunk,
  5989. size_t decompressed_data_chunk_size) {
  5990. decompressed_data.insert(decompressed_data.size(),
  5991. decompressed_data_chunk,
  5992. decompressed_data_chunk_size);
  5993. return true;
  5994. });
  5995. ASSERT_TRUE(result);
  5996. }
  5997. ASSERT_EQ(original_text, decompressed_data);
  5998. }
  5999. #endif
  6000. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6001. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6002. Headers headers;
  6003. headers.emplace("Accept-Encoding", "br");
  6004. auto res = cli_.Get("/streamed-chunked", headers);
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::OK_200, res->status);
  6007. EXPECT_EQ(std::string("123456789"), res->body);
  6008. }
  6009. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6010. Headers headers;
  6011. headers.emplace("Accept-Encoding", "br");
  6012. auto res = cli_.Get("/streamed-chunked2", headers);
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ(std::string("123456789"), res->body);
  6016. }
  6017. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6018. cli_.set_compress(true);
  6019. auto res = cli_.Put(
  6020. "/put", 3,
  6021. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6022. sink.os << "PUT";
  6023. return true;
  6024. },
  6025. "text/plain");
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("PUT", res->body);
  6029. }
  6030. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6031. cli_.set_compress(true);
  6032. auto res = cli_.Put(
  6033. "/put",
  6034. [](size_t /*offset*/, DataSink &sink) {
  6035. sink.os << "PUT";
  6036. sink.done();
  6037. return true;
  6038. },
  6039. "text/plain");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("PUT", res->body);
  6043. }
  6044. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6045. cli_.set_compress(true);
  6046. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::OK_200, res->status);
  6049. EXPECT_EQ(LARGE_DATA, res->body);
  6050. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6051. }
  6052. #endif
  6053. TEST_F(ServerTest, Patch) {
  6054. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. EXPECT_EQ(StatusCode::OK_200, res->status);
  6057. EXPECT_EQ("PATCH", res->body);
  6058. }
  6059. TEST_F(ServerTest, Delete) {
  6060. auto res = cli_.Delete("/delete");
  6061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6062. EXPECT_EQ(StatusCode::OK_200, res->status);
  6063. EXPECT_EQ("DELETE", res->body);
  6064. }
  6065. TEST_F(ServerTest, DeleteContentReceiver) {
  6066. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6068. EXPECT_EQ(StatusCode::OK_200, res->status);
  6069. EXPECT_EQ("content", res->body);
  6070. }
  6071. TEST_F(ServerTest, Options) {
  6072. auto res = cli_.Options("*");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::OK_200, res->status);
  6075. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6076. EXPECT_TRUE(res->body.empty());
  6077. }
  6078. TEST_F(ServerTest, URL) {
  6079. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6081. EXPECT_EQ(StatusCode::OK_200, res->status);
  6082. }
  6083. TEST_F(ServerTest, ArrayParam) {
  6084. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. }
  6088. TEST_F(ServerTest, ArrayParamValues) {
  6089. auto res =
  6090. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. }
  6094. TEST_F(ServerTest, NoMultipleHeaders) {
  6095. Headers headers = {{"Content-Length", "5"}};
  6096. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6097. "text/plain");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. }
  6101. TEST_F(ServerTest, PostContentReceiver) {
  6102. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::OK_200, res->status);
  6105. ASSERT_EQ("content", res->body);
  6106. }
  6107. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6108. UploadFormDataItems items = {
  6109. {"text1", "text default", "", ""},
  6110. {"text2", "aωb", "", ""},
  6111. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6112. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6113. {"file3", "", "", "application/octet-stream"},
  6114. };
  6115. auto res = cli_.Post("/content_receiver", items);
  6116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6117. EXPECT_EQ(StatusCode::OK_200, res->status);
  6118. }
  6119. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6120. UploadFormDataItems items = {
  6121. {"text1", "text default", "", ""},
  6122. {"text2", "aωb", "", ""},
  6123. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6124. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6125. {"file3", "", "", "application/octet-stream"},
  6126. };
  6127. auto boundary = std::string("+++++");
  6128. std::string body;
  6129. for (const auto &item : items) {
  6130. body += "--" + boundary + "\r\n";
  6131. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6132. if (!item.filename.empty()) {
  6133. body += "; filename=\"" + item.filename + "\"";
  6134. }
  6135. body += "\r\n";
  6136. if (!item.content_type.empty()) {
  6137. body += "Content-Type: " + item.content_type + "\r\n";
  6138. }
  6139. body += "\r\n";
  6140. body += item.content + "\r\n";
  6141. }
  6142. body += "--" + boundary + "--\r\n";
  6143. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6144. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6146. EXPECT_EQ(StatusCode::OK_200, res->status);
  6147. }
  6148. TEST(MultipartFormDataTest, FieldEscaping) {
  6149. Server svr;
  6150. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6151. const ContentReader &content_reader) {
  6152. ASSERT_TRUE(req.is_multipart_form_data());
  6153. std::vector<FormData> received;
  6154. content_reader(
  6155. [&](const FormData &file) {
  6156. received.push_back(file);
  6157. return true;
  6158. },
  6159. [&](const char *data, size_t data_length) {
  6160. received.back().content.append(data, data_length);
  6161. return true;
  6162. });
  6163. // '"', CR and LF in names and filenames are escaped following the
  6164. // WHATWG HTML standard, so each part still parses as a single part
  6165. // with no injected headers. Content types get CR/LF escaped too,
  6166. // while '"' (legal there, e.g. quoted charset) is preserved.
  6167. ASSERT_EQ(4U, received.size());
  6168. EXPECT_EQ("na%22me", received[0].name);
  6169. EXPECT_EQ("quoted name", received[0].content);
  6170. EXPECT_EQ("file", received[1].name);
  6171. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6172. received[1].filename);
  6173. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6174. EXPECT_EQ("injected", received[1].content);
  6175. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6176. EXPECT_EQ("my%22file.txt", received[2].filename);
  6177. EXPECT_EQ("cr lf name", received[2].content);
  6178. EXPECT_EQ("typed", received[3].name);
  6179. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6180. received[3].content_type);
  6181. EXPECT_EQ("typed content", received[3].content);
  6182. });
  6183. auto port = svr.bind_to_any_port("localhost");
  6184. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6185. auto se = detail::scope_exit([&] {
  6186. svr.stop();
  6187. t.join();
  6188. ASSERT_FALSE(svr.is_running());
  6189. });
  6190. svr.wait_until_ready();
  6191. Client cli("localhost", port);
  6192. UploadFormDataItems items = {
  6193. {"na\"me", "quoted name", "", ""},
  6194. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6195. "application/octet-stream"},
  6196. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6197. {"typed", "typed content", "",
  6198. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6199. };
  6200. auto res = cli.Post("/post", items);
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. }
  6204. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6205. const UploadFormDataItems items = {
  6206. {"name1", "Content 1", "", ""},
  6207. {"name2", "Content 2", "file2.txt", "text/plain"},
  6208. };
  6209. Server svr;
  6210. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6211. const ContentReader &content_reader) {
  6212. ASSERT_TRUE(req.is_multipart_form_data());
  6213. std::vector<FormData> received;
  6214. content_reader(
  6215. [&](const FormData &file) {
  6216. received.push_back(file);
  6217. return true;
  6218. },
  6219. [&](const char *data, size_t data_length) {
  6220. received.back().content.append(data, data_length);
  6221. return true;
  6222. });
  6223. ASSERT_EQ(2U, received.size());
  6224. EXPECT_EQ("name1", received[0].name);
  6225. EXPECT_EQ("Content 1", received[0].content);
  6226. EXPECT_EQ("name2", received[1].name);
  6227. EXPECT_EQ("Content 2", received[1].content);
  6228. EXPECT_EQ("file2.txt", received[1].filename);
  6229. EXPECT_EQ("text/plain", received[1].content_type);
  6230. });
  6231. auto port = svr.bind_to_any_port("localhost");
  6232. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6233. auto se = detail::scope_exit([&] {
  6234. svr.stop();
  6235. t.join();
  6236. ASSERT_FALSE(svr.is_running());
  6237. });
  6238. svr.wait_until_ready();
  6239. Client cli("localhost", port);
  6240. // Whole-body serialization with a generated boundary
  6241. {
  6242. MultipartFormDataWriter writer;
  6243. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6244. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6245. writer.content_type());
  6246. auto body = writer.serialize(items);
  6247. EXPECT_EQ(body.size(), writer.content_length(items));
  6248. auto res = cli.Post("/post", body, writer.content_type());
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. }
  6252. // Per-part framing with a custom boundary via a content provider
  6253. {
  6254. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6255. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6256. MultipartFormDataWriter writer("custom-boundary_123");
  6257. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6258. std::string body;
  6259. for (const auto &item : items) {
  6260. body += writer.item_begin(item);
  6261. body += item.content;
  6262. body += MultipartFormDataWriter::item_end();
  6263. }
  6264. body += writer.finish();
  6265. EXPECT_EQ(body.size(), writer.content_length(items));
  6266. auto res = cli.Post(
  6267. "/post", body.size(),
  6268. [&](size_t offset, size_t length, DataSink &sink) {
  6269. sink.write(body.data() + offset, length);
  6270. return true;
  6271. },
  6272. writer.content_type());
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. }
  6277. TEST_F(ServerTest, PostContentReceiverGzip) {
  6278. cli_.set_compress(true);
  6279. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. ASSERT_EQ(StatusCode::OK_200, res->status);
  6282. ASSERT_EQ("content", res->body);
  6283. }
  6284. TEST_F(ServerTest, PutContentReceiver) {
  6285. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. ASSERT_EQ(StatusCode::OK_200, res->status);
  6288. ASSERT_EQ("content", res->body);
  6289. }
  6290. TEST_F(ServerTest, PatchContentReceiver) {
  6291. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6293. ASSERT_EQ(StatusCode::OK_200, res->status);
  6294. ASSERT_EQ("content", res->body);
  6295. }
  6296. template <typename ClientType>
  6297. void TestWithHeadersAndContentReceiver(
  6298. ClientType &cli,
  6299. std::function<Result(ClientType &, const std::string &, const Headers &,
  6300. const std::string &, const std::string &,
  6301. ContentReceiver, DownloadProgress)>
  6302. request_func) {
  6303. Headers headers;
  6304. headers.emplace("X-Custom-Header", "test-value");
  6305. std::string received_body;
  6306. auto res = request_func(
  6307. cli, "/content_receiver", headers, "content", "application/json",
  6308. [&](const char *data, size_t data_length) {
  6309. received_body.append(data, data_length);
  6310. return true;
  6311. },
  6312. nullptr);
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. EXPECT_EQ("content", received_body);
  6316. }
  6317. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6318. #ifdef CPPHTTPLIB_SSL_ENABLED
  6319. using ClientT = SSLClient;
  6320. #else
  6321. using ClientT = Client;
  6322. #endif
  6323. TestWithHeadersAndContentReceiver<ClientT>(
  6324. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6325. const std::string &body, const std::string &content_type,
  6326. ContentReceiver receiver, DownloadProgress progress) {
  6327. return cli.Post(path, headers, body, content_type, receiver, progress);
  6328. });
  6329. }
  6330. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6331. #ifdef CPPHTTPLIB_SSL_ENABLED
  6332. using ClientT = SSLClient;
  6333. #else
  6334. using ClientT = Client;
  6335. #endif
  6336. TestWithHeadersAndContentReceiver<ClientT>(
  6337. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6338. const std::string &body, const std::string &content_type,
  6339. ContentReceiver receiver, DownloadProgress progress) {
  6340. return cli.Put(path, headers, body, content_type, receiver, progress);
  6341. });
  6342. }
  6343. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6344. #ifdef CPPHTTPLIB_SSL_ENABLED
  6345. using ClientT = SSLClient;
  6346. #else
  6347. using ClientT = Client;
  6348. #endif
  6349. TestWithHeadersAndContentReceiver<ClientT>(
  6350. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6351. const std::string &body, const std::string &content_type,
  6352. ContentReceiver receiver, DownloadProgress progress) {
  6353. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6354. });
  6355. }
  6356. template <typename ClientType>
  6357. void TestWithHeadersAndContentReceiverWithProgress(
  6358. ClientType &cli,
  6359. std::function<Result(ClientType &, const std::string &, const Headers &,
  6360. const std::string &, const std::string &,
  6361. ContentReceiver, DownloadProgress)>
  6362. request_func) {
  6363. Headers headers;
  6364. headers.emplace("X-Test-Header", "progress-test");
  6365. std::string received_body;
  6366. auto progress_called = false;
  6367. auto res = request_func(
  6368. cli, "/content_receiver", headers, "content", "text/plain",
  6369. [&](const char *data, size_t data_length) {
  6370. received_body.append(data, data_length);
  6371. return true;
  6372. },
  6373. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6374. progress_called = true;
  6375. return true;
  6376. });
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. EXPECT_EQ("content", received_body);
  6380. EXPECT_TRUE(progress_called);
  6381. }
  6382. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6383. #ifdef CPPHTTPLIB_SSL_ENABLED
  6384. using ClientT = SSLClient;
  6385. #else
  6386. using ClientT = Client;
  6387. #endif
  6388. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6389. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6390. const std::string &body, const std::string &content_type,
  6391. ContentReceiver receiver, DownloadProgress progress) {
  6392. return cli.Post(path, headers, body, content_type, receiver, progress);
  6393. });
  6394. }
  6395. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6396. #ifdef CPPHTTPLIB_SSL_ENABLED
  6397. using ClientT = SSLClient;
  6398. #else
  6399. using ClientT = Client;
  6400. #endif
  6401. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6402. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6403. const std::string &body, const std::string &content_type,
  6404. ContentReceiver receiver, DownloadProgress progress) {
  6405. return cli.Put(path, headers, body, content_type, receiver, progress);
  6406. });
  6407. }
  6408. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6409. #ifdef CPPHTTPLIB_SSL_ENABLED
  6410. using ClientT = SSLClient;
  6411. #else
  6412. using ClientT = Client;
  6413. #endif
  6414. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6415. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6416. const std::string &body, const std::string &content_type,
  6417. ContentReceiver receiver, DownloadProgress progress) {
  6418. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6419. });
  6420. }
  6421. template <typename ClientType>
  6422. void TestWithHeadersAndContentReceiverError(
  6423. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6424. const Headers &, const std::string &,
  6425. const std::string &, ContentReceiver)>
  6426. request_func) {
  6427. Headers headers;
  6428. headers.emplace("X-Error-Test", "true");
  6429. std::string received_body;
  6430. auto receiver_failed = false;
  6431. auto res =
  6432. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6433. [&](const char *data, size_t data_length) {
  6434. received_body.append(data, data_length);
  6435. receiver_failed = true;
  6436. return false;
  6437. });
  6438. ASSERT_FALSE(res);
  6439. EXPECT_TRUE(receiver_failed);
  6440. }
  6441. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6442. #ifdef CPPHTTPLIB_SSL_ENABLED
  6443. using ClientT = SSLClient;
  6444. #else
  6445. using ClientT = Client;
  6446. #endif
  6447. TestWithHeadersAndContentReceiverError<ClientT>(
  6448. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6449. const std::string &body, const std::string &content_type,
  6450. ContentReceiver receiver) {
  6451. return cli.Post(path, headers, body, content_type, receiver);
  6452. });
  6453. }
  6454. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6455. #ifdef CPPHTTPLIB_SSL_ENABLED
  6456. using ClientT = SSLClient;
  6457. #else
  6458. using ClientT = Client;
  6459. #endif
  6460. TestWithHeadersAndContentReceiverError<ClientT>(
  6461. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6462. const std::string &body, const std::string &content_type,
  6463. ContentReceiver receiver) {
  6464. return cli.Put(path, headers, body, content_type, receiver);
  6465. });
  6466. }
  6467. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6468. #ifdef CPPHTTPLIB_SSL_ENABLED
  6469. using ClientT = SSLClient;
  6470. #else
  6471. using ClientT = Client;
  6472. #endif
  6473. TestWithHeadersAndContentReceiverError<ClientT>(
  6474. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6475. const std::string &body, const std::string &content_type,
  6476. ContentReceiver receiver) {
  6477. return cli.Patch(path, headers, body, content_type, receiver);
  6478. });
  6479. }
  6480. TEST_F(ServerTest, PostQueryStringAndBody) {
  6481. auto res =
  6482. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. ASSERT_EQ(StatusCode::OK_200, res->status);
  6485. }
  6486. TEST_F(ServerTest, HTTP2Magic) {
  6487. Request req;
  6488. req.method = "PRI";
  6489. req.path = "*";
  6490. req.body = "SM";
  6491. auto res = std::make_shared<Response>();
  6492. auto error = Error::Success;
  6493. auto ret = cli_.send(req, *res, error);
  6494. ASSERT_TRUE(ret);
  6495. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6496. }
  6497. TEST_F(ServerTest, KeepAlive) {
  6498. auto res = cli_.Get("/hi");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::OK_200, res->status);
  6501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6502. EXPECT_EQ("Hello World!", res->body);
  6503. res = cli_.Get("/hi");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::OK_200, res->status);
  6506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6507. EXPECT_EQ("Hello World!", res->body);
  6508. res = cli_.Get("/hi");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::OK_200, res->status);
  6511. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6512. EXPECT_EQ("Hello World!", res->body);
  6513. res = cli_.Get("/not-exist");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6516. res = cli_.Post("/empty", "", "text/plain");
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6520. EXPECT_EQ("empty", res->body);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. res = cli_.Post(
  6523. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6524. "text/plain");
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::OK_200, res->status);
  6527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6528. EXPECT_EQ("empty", res->body);
  6529. cli_.set_keep_alive(false);
  6530. res = cli_.Get("/last-request");
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::OK_200, res->status);
  6533. EXPECT_EQ("close", res->get_header_value("Connection"));
  6534. }
  6535. TEST_F(ServerTest, TooManyRedirect) {
  6536. cli_.set_follow_location(true);
  6537. auto res = cli_.Get("/redirect/0");
  6538. ASSERT_TRUE(!res);
  6539. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6540. }
  6541. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6542. Request req;
  6543. req.method = "FOOBAR";
  6544. req.path = "/hi";
  6545. cli_.set_keep_alive(true);
  6546. auto res = cli_.send(req);
  6547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6548. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6549. EXPECT_EQ("close", res->get_header_value("Connection"));
  6550. EXPECT_FALSE(cli_.is_socket_open());
  6551. }
  6552. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6553. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6554. TEST_F(ServerTest, Gzip) {
  6555. Headers headers;
  6556. headers.emplace("Accept-Encoding", "gzip, deflate");
  6557. auto res = cli_.Get("/compress", headers);
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6561. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6563. "7890123456789012345678901234567890",
  6564. res->body);
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. }
  6567. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6568. Headers headers;
  6569. headers.emplace("Accept-Encoding", "gzip, deflate");
  6570. auto res = cli_.Get("/compress-with-charset", headers);
  6571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6572. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6573. EXPECT_EQ("application/json; charset=utf-8",
  6574. res->get_header_value("Content-Type"));
  6575. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6576. "7890123456789012345678901234567890",
  6577. res->body);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6581. Headers headers;
  6582. headers.emplace("Accept-Encoding", "");
  6583. auto res = cli_.Get("/compress", headers);
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6587. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6588. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6589. "7890123456789012345678901234567890",
  6590. res->body);
  6591. EXPECT_EQ(StatusCode::OK_200, res->status);
  6592. }
  6593. TEST_F(ServerTest, GzipWithContentReceiver) {
  6594. Headers headers;
  6595. headers.emplace("Accept-Encoding", "gzip, deflate");
  6596. std::string body;
  6597. auto res = cli_.Get("/compress", headers,
  6598. [&](const char *data, uint64_t data_length) {
  6599. EXPECT_EQ(100U, data_length);
  6600. body.append(data, data_length);
  6601. return true;
  6602. });
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6606. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6607. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6608. "7890123456789012345678901234567890",
  6609. body);
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. }
  6612. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6613. Headers headers;
  6614. headers.emplace("Accept-Encoding", "gzip, deflate");
  6615. cli_.set_decompress(false);
  6616. auto res = cli_.Get("/compress", headers);
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6620. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6621. EXPECT_EQ(33U, res->body.size());
  6622. EXPECT_EQ(StatusCode::OK_200, res->status);
  6623. }
  6624. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6625. Headers headers;
  6626. headers.emplace("Accept-Encoding", "");
  6627. std::string body;
  6628. auto res = cli_.Get("/compress", headers,
  6629. [&](const char *data, uint64_t data_length) {
  6630. EXPECT_EQ(100U, data_length);
  6631. body.append(data, data_length);
  6632. return true;
  6633. });
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6637. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6638. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6639. "7890123456789012345678901234567890",
  6640. body);
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. }
  6643. TEST_F(ServerTest, NoGzip) {
  6644. Headers headers;
  6645. headers.emplace("Accept-Encoding", "gzip, deflate");
  6646. auto res = cli_.Get("/nocompress", headers);
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6649. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6650. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6651. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6652. "7890123456789012345678901234567890",
  6653. res->body);
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. }
  6656. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6657. Headers headers;
  6658. headers.emplace("Accept-Encoding", "gzip, deflate");
  6659. std::string body;
  6660. auto res = cli_.Get("/nocompress", headers,
  6661. [&](const char *data, uint64_t data_length) {
  6662. EXPECT_EQ(100U, data_length);
  6663. body.append(data, data_length);
  6664. return true;
  6665. });
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6668. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6669. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6670. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6671. "7890123456789012345678901234567890",
  6672. body);
  6673. EXPECT_EQ(StatusCode::OK_200, res->status);
  6674. }
  6675. TEST_F(ServerTest, MultipartFormDataGzip) {
  6676. UploadFormDataItems items = {
  6677. {"key1", "test", "", ""},
  6678. {"key2", "--abcdefg123", "", ""},
  6679. };
  6680. cli_.set_compress(true);
  6681. auto res = cli_.Post("/compress-multipart", items);
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. }
  6685. #endif
  6686. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6687. TEST_F(ServerTest, Brotli) {
  6688. Headers headers;
  6689. headers.emplace("Accept-Encoding", "br");
  6690. auto res = cli_.Get("/compress", headers);
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6693. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6694. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6695. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6696. "7890123456789012345678901234567890",
  6697. res->body);
  6698. EXPECT_EQ(StatusCode::OK_200, res->status);
  6699. }
  6700. #endif
  6701. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6702. TEST_F(ServerTest, Zstd) {
  6703. Headers headers;
  6704. headers.emplace("Accept-Encoding", "zstd");
  6705. auto res = cli_.Get("/compress", headers);
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6708. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6709. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6710. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6711. "7890123456789012345678901234567890",
  6712. res->body);
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. }
  6715. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6716. Headers headers;
  6717. headers.emplace("Accept-Encoding", "");
  6718. auto res = cli_.Get("/compress", headers);
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6722. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6723. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6724. "7890123456789012345678901234567890",
  6725. res->body);
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. }
  6728. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6729. Headers headers;
  6730. headers.emplace("Accept-Encoding", "zstd");
  6731. std::string body;
  6732. auto res = cli_.Get("/compress", headers,
  6733. [&](const char *data, uint64_t data_length) {
  6734. EXPECT_EQ(100U, data_length);
  6735. body.append(data, data_length);
  6736. return true;
  6737. });
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6742. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6743. "7890123456789012345678901234567890",
  6744. body);
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6748. Headers headers;
  6749. headers.emplace("Accept-Encoding", "zstd");
  6750. cli_.set_decompress(false);
  6751. auto res = cli_.Get("/compress", headers);
  6752. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6753. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6754. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6755. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6758. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6759. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. ASSERT_EQ(26U, res->body.size());
  6762. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6763. 0);
  6764. }
  6765. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6766. Headers headers;
  6767. headers.emplace("Accept-Encoding", "");
  6768. std::string body;
  6769. auto res = cli_.Get("/compress", headers,
  6770. [&](const char *data, uint64_t data_length) {
  6771. EXPECT_EQ(100U, data_length);
  6772. body.append(data, data_length);
  6773. return true;
  6774. });
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6778. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6779. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6780. "7890123456789012345678901234567890",
  6781. body);
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. }
  6784. TEST_F(ServerTest, NoZstd) {
  6785. Headers headers;
  6786. headers.emplace("Accept-Encoding", "zstd");
  6787. auto res = cli_.Get("/nocompress", headers);
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6790. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6791. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6792. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6793. "7890123456789012345678901234567890",
  6794. res->body);
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. }
  6797. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6798. Headers headers;
  6799. headers.emplace("Accept-Encoding", "zstd");
  6800. std::string body;
  6801. auto res = cli_.Get("/nocompress", headers,
  6802. [&](const char *data, uint64_t data_length) {
  6803. EXPECT_EQ(100U, data_length);
  6804. body.append(data, data_length);
  6805. return true;
  6806. });
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6809. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6810. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6811. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6812. "7890123456789012345678901234567890",
  6813. body);
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. }
  6816. // TODO: How to enable zstd ??
  6817. TEST_F(ServerTest, MultipartFormDataZstd) {
  6818. UploadFormDataItems items = {
  6819. {"key1", "test", "", ""},
  6820. {"key2", "--abcdefg123", "", ""},
  6821. };
  6822. Headers headers;
  6823. headers.emplace("Accept-Encoding", "zstd");
  6824. cli_.set_compress(true);
  6825. auto res = cli_.Post("/compress-multipart", headers, items);
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6830. Headers headers;
  6831. headers.emplace("Accept-Encoding", "zstd");
  6832. cli_.set_compress(true);
  6833. auto res = cli_.Put(
  6834. "/put", headers, 3,
  6835. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6836. sink.os << "PUT";
  6837. return true;
  6838. },
  6839. "text/plain");
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. EXPECT_EQ("PUT", res->body);
  6843. }
  6844. // Pre-compression logging tests
  6845. TEST_F(ServerTest, PreCompressionLogging) {
  6846. // Test data for compression (matches the actual /compress endpoint content)
  6847. const std::string test_content =
  6848. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6849. "3456789012345678901234567890";
  6850. // Variables to capture logging data
  6851. std::string pre_compression_body;
  6852. std::string pre_compression_content_type;
  6853. std::string pre_compression_content_encoding;
  6854. std::string post_compression_body;
  6855. std::string post_compression_content_type;
  6856. std::string post_compression_content_encoding;
  6857. // Set up pre-compression logger
  6858. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6859. const Response &res) {
  6860. pre_compression_body = res.body;
  6861. pre_compression_content_type = res.get_header_value("Content-Type");
  6862. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6863. });
  6864. // Set up post-compression logger
  6865. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6866. post_compression_body = res.body;
  6867. post_compression_content_type = res.get_header_value("Content-Type");
  6868. post_compression_content_encoding =
  6869. res.get_header_value("Content-Encoding");
  6870. });
  6871. // Test with gzip compression
  6872. Headers headers;
  6873. headers.emplace("Accept-Encoding", "gzip");
  6874. auto res = cli_.Get("/compress", headers);
  6875. // Verify response was compressed
  6876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6877. EXPECT_EQ(StatusCode::OK_200, res->status);
  6878. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6879. // Verify pre-compression logger captured uncompressed content
  6880. EXPECT_EQ(test_content, pre_compression_body);
  6881. EXPECT_EQ("text/plain", pre_compression_content_type);
  6882. EXPECT_TRUE(pre_compression_content_encoding
  6883. .empty()); // No encoding header before compression
  6884. // Verify post-compression logger captured compressed content
  6885. EXPECT_NE(test_content,
  6886. post_compression_body); // Should be different after compression
  6887. EXPECT_EQ("text/plain", post_compression_content_type);
  6888. EXPECT_EQ("gzip", post_compression_content_encoding);
  6889. // Verify compressed content is smaller
  6890. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6891. }
  6892. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6893. const std::string test_content =
  6894. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6895. "3456789012345678901234567890";
  6896. std::string pre_compression_body;
  6897. std::string post_compression_body;
  6898. svr_.set_pre_compression_logger(
  6899. [&](const Request & /*req*/, const Response &res) {
  6900. pre_compression_body = res.body;
  6901. });
  6902. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6903. post_compression_body = res.body;
  6904. });
  6905. Headers headers;
  6906. headers.emplace("Accept-Encoding", "br");
  6907. auto res = cli_.Get("/compress", headers);
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. EXPECT_EQ(StatusCode::OK_200, res->status);
  6910. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6911. // Verify pre-compression content is uncompressed
  6912. EXPECT_EQ(test_content, pre_compression_body);
  6913. // Verify post-compression content is compressed
  6914. EXPECT_NE(test_content, post_compression_body);
  6915. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6916. }
  6917. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6918. const std::string test_content =
  6919. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6920. "3456789012345678901234567890";
  6921. std::string pre_compression_body;
  6922. std::string post_compression_body;
  6923. svr_.set_pre_compression_logger(
  6924. [&](const Request & /*req*/, const Response &res) {
  6925. pre_compression_body = res.body;
  6926. });
  6927. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6928. post_compression_body = res.body;
  6929. });
  6930. // Request without compression (use /nocompress endpoint)
  6931. Headers headers;
  6932. auto res = cli_.Get("/nocompress", headers);
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6936. // Pre-compression logger should not be called when no compression is applied
  6937. EXPECT_TRUE(
  6938. pre_compression_body.empty()); // Pre-compression logger not called
  6939. EXPECT_EQ(
  6940. test_content,
  6941. post_compression_body); // Post-compression logger captures final content
  6942. }
  6943. TEST_F(ServerTest, LoggerSeesContentLength) {
  6944. size_t logged_content_length = 0;
  6945. std::string logged_content_length_header;
  6946. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6947. logged_content_length = res.content_length_;
  6948. logged_content_length_header = res.get_header_value("Content-Length");
  6949. });
  6950. auto res = cli_.Get("/nocompress");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. EXPECT_EQ(res->body.size(), logged_content_length);
  6954. EXPECT_EQ(std::to_string(logged_content_length),
  6955. logged_content_length_header);
  6956. }
  6957. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6958. const std::string test_content =
  6959. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6960. "3456789012345678901234567890";
  6961. std::string pre_compression_body;
  6962. bool pre_logger_called = false;
  6963. // Set only pre-compression logger
  6964. svr_.set_pre_compression_logger(
  6965. [&](const Request & /*req*/, const Response &res) {
  6966. pre_compression_body = res.body;
  6967. pre_logger_called = true;
  6968. });
  6969. Headers headers;
  6970. headers.emplace("Accept-Encoding", "gzip");
  6971. auto res = cli_.Get("/compress", headers);
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::OK_200, res->status);
  6974. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6975. // Verify pre-compression logger was called
  6976. EXPECT_TRUE(pre_logger_called);
  6977. EXPECT_EQ(test_content, pre_compression_body);
  6978. }
  6979. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6980. {
  6981. // Test with Expect: 100-continue header - success case
  6982. // Server returns 100 Continue, client sends body, server returns 200 OK
  6983. Request req;
  6984. req.method = "POST";
  6985. req.path = "/post-large";
  6986. req.set_header("Expect", "100-continue");
  6987. req.body = LARGE_DATA;
  6988. Response res;
  6989. auto error = Error::Success;
  6990. cli_.set_keep_alive(true);
  6991. auto ret = cli_.send(req, res, error);
  6992. EXPECT_TRUE(ret);
  6993. EXPECT_EQ(StatusCode::OK_200, res.status);
  6994. EXPECT_EQ(LARGE_DATA, res.body);
  6995. }
  6996. {
  6997. // Test with Expect: 100-continue header - error case
  6998. // Client should not send the body when server returns an error
  6999. Request req;
  7000. req.method = "POST";
  7001. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7002. req.set_header("Expect", "100-continue");
  7003. req.body = LARGE_DATA;
  7004. Response res;
  7005. auto error = Error::Success;
  7006. auto start = std::chrono::high_resolution_clock::now();
  7007. cli_.set_keep_alive(true);
  7008. auto ret = cli_.send(req, res, error);
  7009. auto end = std::chrono::high_resolution_clock::now();
  7010. auto elapsed =
  7011. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7012. .count();
  7013. // With Expect: 100-continue, request completes successfully but with error
  7014. EXPECT_TRUE(ret);
  7015. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7016. EXPECT_EQ("close", res.get_header_value("Connection"));
  7017. EXPECT_FALSE(cli_.is_socket_open());
  7018. EXPECT_LE(elapsed, 2000);
  7019. }
  7020. {
  7021. // Send an extra GET request to ensure error recovery without hanging
  7022. Request req;
  7023. req.method = "GET";
  7024. req.path = "/hi";
  7025. auto start = std::chrono::high_resolution_clock::now();
  7026. auto res = cli_.send(req);
  7027. auto end = std::chrono::high_resolution_clock::now();
  7028. auto elapsed =
  7029. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7030. .count();
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("Hello World!", res->body);
  7034. EXPECT_LE(elapsed, 500);
  7035. }
  7036. }
  7037. TEST(ZstdDecompressor, ChunkedDecompression) {
  7038. std::string data;
  7039. for (size_t i = 0; i < 32 * 1024; ++i) {
  7040. data.push_back(static_cast<char>('a' + i % 26));
  7041. }
  7042. std::string compressed_data;
  7043. {
  7044. httplib::detail::zstd_compressor compressor;
  7045. bool result = compressor.compress(
  7046. data.data(), data.size(),
  7047. /*last=*/true,
  7048. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7049. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7050. compressed_data_size);
  7051. return true;
  7052. });
  7053. ASSERT_TRUE(result);
  7054. }
  7055. std::string decompressed_data;
  7056. {
  7057. httplib::detail::zstd_decompressor decompressor;
  7058. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7059. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7060. size_t chunk_size = 130;
  7061. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7062. chunk_begin += chunk_size) {
  7063. size_t current_chunk_size =
  7064. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7065. bool result = decompressor.decompress(
  7066. compressed_data.data() + chunk_begin, current_chunk_size,
  7067. [&](const char *decompressed_data_chunk,
  7068. size_t decompressed_data_chunk_size) {
  7069. decompressed_data.insert(decompressed_data.size(),
  7070. decompressed_data_chunk,
  7071. decompressed_data_chunk_size);
  7072. return true;
  7073. });
  7074. ASSERT_TRUE(result);
  7075. }
  7076. }
  7077. ASSERT_EQ(data, decompressed_data);
  7078. }
  7079. TEST(ZstdDecompressor, Decompress) {
  7080. std::string original_text = "Compressed with ZSTD";
  7081. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7082. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7083. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7084. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7085. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7086. std::string decompressed_data;
  7087. {
  7088. httplib::detail::zstd_decompressor decompressor;
  7089. bool result = decompressor.decompress(
  7090. compressed_data.data(), compressed_data.size(),
  7091. [&](const char *decompressed_data_chunk,
  7092. size_t decompressed_data_chunk_size) {
  7093. decompressed_data.insert(decompressed_data.size(),
  7094. decompressed_data_chunk,
  7095. decompressed_data_chunk_size);
  7096. return true;
  7097. });
  7098. ASSERT_TRUE(result);
  7099. }
  7100. ASSERT_EQ(original_text, decompressed_data);
  7101. }
  7102. #endif
  7103. // Sends a raw request to a server listening at HOST:PORT.
  7104. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7105. std::string *resp = nullptr) {
  7106. auto error = Error::Success;
  7107. auto client_sock = detail::create_client_socket(
  7108. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  7109. /*connection_timeout_sec=*/5, 0,
  7110. /*read_timeout_sec=*/5, 0,
  7111. /*write_timeout_sec=*/5, 0, std::string(), error);
  7112. if (client_sock == INVALID_SOCKET) { return false; }
  7113. auto ret = detail::process_client_socket(
  7114. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7115. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7116. if (req.size() !=
  7117. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7118. return false;
  7119. }
  7120. char buf[512];
  7121. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7122. while (line_reader.getline()) {
  7123. if (resp) { *resp += line_reader.ptr(); }
  7124. }
  7125. return true;
  7126. });
  7127. detail::close_socket(client_sock);
  7128. return ret;
  7129. }
  7130. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7131. Server svr;
  7132. std::string header_value;
  7133. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7134. header_value = req.get_header_value("foo");
  7135. res.set_content("ok", "text/plain");
  7136. });
  7137. thread t = thread([&] { svr.listen(HOST, PORT); });
  7138. auto se = detail::scope_exit([&] {
  7139. svr.stop();
  7140. t.join();
  7141. ASSERT_FALSE(svr.is_running());
  7142. });
  7143. svr.wait_until_ready();
  7144. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7145. // like characters are not treated the same - use vertical tab and escape.
  7146. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7147. "foo: \t \v bar \x1B\t \r\n"
  7148. "Connection: close\r\n"
  7149. "\r\n";
  7150. std::string res;
  7151. ASSERT_TRUE(send_request(5, req, &res));
  7152. EXPECT_EQ(header_value, "");
  7153. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7154. }
  7155. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7156. Server svr;
  7157. std::string received;
  7158. svr.Get("/order", [&](const Request &req, Response &res) {
  7159. received = entries_to_string(req.headers);
  7160. res.set_content("ok", "text/plain");
  7161. });
  7162. thread t = thread([&] { svr.listen(HOST, PORT); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. t.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. const std::string req = "GET /order HTTP/1.1\r\n"
  7170. "X-First: 1\r\n"
  7171. "X-Dup: a\r\n"
  7172. "X-Second: 2\r\n"
  7173. "X-Dup: b\r\n"
  7174. "Connection: close\r\n"
  7175. "\r\n";
  7176. std::string res;
  7177. ASSERT_TRUE(send_request(5, req, &res));
  7178. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7179. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7180. }
  7181. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7182. Server svr;
  7183. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7184. res.set_header("Set-Cookie", "first=1");
  7185. res.set_header("X-Between", "y");
  7186. res.set_header("Set-Cookie", "second=2");
  7187. res.set_content("ok", "text/plain");
  7188. });
  7189. thread t = thread([&] { svr.listen(HOST, PORT); });
  7190. auto se = detail::scope_exit([&] {
  7191. svr.stop();
  7192. t.join();
  7193. ASSERT_FALSE(svr.is_running());
  7194. });
  7195. svr.wait_until_ready();
  7196. Client cli(HOST, PORT);
  7197. auto res = cli.Get("/cookies");
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7200. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7201. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7202. }
  7203. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7204. Server svr;
  7205. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7206. auto i = new int(0);
  7207. res.set_header("Trailer", "X-Safe, X-Reflected");
  7208. res.set_chunked_content_provider(
  7209. "text/plain",
  7210. [i](size_t /*offset*/, DataSink &sink) {
  7211. if (*i == 0) {
  7212. sink.os << "body";
  7213. } else {
  7214. Headers trailer;
  7215. // A valid trailer that must survive.
  7216. trailer.emplace("X-Safe", "safe");
  7217. // Attacker-controlled value carrying CR/LF (response splitting).
  7218. trailer.emplace("X-Reflected",
  7219. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7220. // Attacker-controlled name carrying CR/LF.
  7221. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7222. sink.done_with_trailer(trailer);
  7223. }
  7224. (*i)++;
  7225. return true;
  7226. },
  7227. [i](bool /*success*/) { delete i; });
  7228. });
  7229. thread t = thread([&] { svr.listen(HOST, PORT); });
  7230. auto se = detail::scope_exit([&] {
  7231. svr.stop();
  7232. t.join();
  7233. ASSERT_FALSE(svr.is_running());
  7234. });
  7235. svr.wait_until_ready();
  7236. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7237. "Host: " + HOST +
  7238. "\r\n"
  7239. "Connection: close\r\n"
  7240. "\r\n";
  7241. std::string res;
  7242. ASSERT_TRUE(send_request(5, req, &res));
  7243. // The injected fields must not appear anywhere in the raw response.
  7244. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7245. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7246. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7247. // Invalid trailers are dropped entirely, matching set_header().
  7248. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7249. // The valid trailer still passes through.
  7250. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7251. }
  7252. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7253. Server svr;
  7254. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7255. // res.headers is a public field an application can populate directly,
  7256. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7257. // A valid header that must survive.
  7258. res.headers.emplace("X-Safe", "safe");
  7259. // Attacker-controlled value carrying CR/LF (response splitting).
  7260. res.headers.emplace("X-Reflected",
  7261. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7262. // Attacker-controlled name carrying CR/LF.
  7263. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7264. res.set_content("body", "text/plain");
  7265. });
  7266. thread t = thread([&] { svr.listen(HOST, PORT); });
  7267. auto se = detail::scope_exit([&] {
  7268. svr.stop();
  7269. t.join();
  7270. ASSERT_FALSE(svr.is_running());
  7271. });
  7272. svr.wait_until_ready();
  7273. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7274. "Host: " + HOST +
  7275. "\r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. std::string res;
  7279. ASSERT_TRUE(send_request(5, req, &res));
  7280. // The injected fields must not appear anywhere in the raw response.
  7281. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7282. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7283. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7284. // Invalid headers are dropped entirely, matching set_header().
  7285. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7286. // The valid header still passes through.
  7287. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7288. }
  7289. // Forward declaration: in split builds split.py strips `inline` and moves the
  7290. // definition into httplib.cc, so detail::write_request_line is not visible from
  7291. // the public httplib.h. Re-declaring it here lets the tests link against the
  7292. // symbol in both header-only and split builds.
  7293. namespace httplib {
  7294. namespace detail {
  7295. ssize_t write_request_line(Stream &strm, const std::string &method,
  7296. const std::string &path);
  7297. } // namespace detail
  7298. } // namespace httplib
  7299. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7300. // A well-formed target is written verbatim.
  7301. {
  7302. detail::BufferStream strm;
  7303. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7304. EXPECT_GT(n, 0);
  7305. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7306. }
  7307. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7308. // otherwise it splits the request line and injects a header or a whole
  7309. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7310. // when path encoding is disabled.
  7311. const std::string evil_targets[] = {
  7312. "/a\r\nInjected: pwned",
  7313. "/a\rInjected",
  7314. "/a\nInjected",
  7315. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7316. };
  7317. for (const auto &evil : evil_targets) {
  7318. detail::BufferStream strm;
  7319. auto n = detail::write_request_line(strm, "GET", evil);
  7320. EXPECT_LT(n, 0);
  7321. EXPECT_TRUE(strm.get_buffer().empty());
  7322. }
  7323. }
  7324. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7325. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7326. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7327. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7328. // client must fail cleanly with Error::Write instead of putting a
  7329. // request-line-less, header-injecting request on the wire.
  7330. Server svr;
  7331. svr.Get("/a", [](const Request &, Response &res) {
  7332. res.set_content("ok", "text/plain");
  7333. });
  7334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7335. auto se = detail::scope_exit([&] {
  7336. svr.stop();
  7337. thread.join();
  7338. ASSERT_FALSE(svr.is_running());
  7339. });
  7340. svr.wait_until_ready();
  7341. {
  7342. Client cli(HOST, PORT);
  7343. cli.set_path_encode(false);
  7344. // The request is rejected before anything is written, so the connection
  7345. // stays silent and the subsequent response read would otherwise block for
  7346. // the full default read timeout. Shorten it -- the assertion is on the
  7347. // error, not the timeout.
  7348. cli.set_read_timeout(1, 0);
  7349. auto res = cli.Get("/a\r\nInjected: pwned");
  7350. EXPECT_FALSE(res);
  7351. EXPECT_EQ(Error::Write, res.error());
  7352. }
  7353. }
  7354. // Sends a raw request and verifies that there isn't a crash or exception.
  7355. static void test_raw_request(const std::string &req,
  7356. std::string *out = nullptr) {
  7357. Server svr;
  7358. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7359. res.set_content("ok", "text/plain");
  7360. });
  7361. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7362. res.set_content("ok", "text/plain");
  7363. });
  7364. svr.Get("/header_field_value_check",
  7365. [&](const Request & /*req*/, Response &res) {
  7366. res.set_content("ok", "text/plain");
  7367. });
  7368. // Server read timeout must be longer than the client read timeout for the
  7369. // bug to reproduce, probably to force the server to process a request
  7370. // without a trailing blank line.
  7371. const time_t client_read_timeout_sec = 1;
  7372. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7373. bool listen_thread_ok = false;
  7374. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. EXPECT_TRUE(listen_thread_ok);
  7380. });
  7381. svr.wait_until_ready();
  7382. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7383. }
  7384. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7385. // A certain header line causes an exception if the header property is parsed
  7386. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7387. test_raw_request(
  7388. "GET /hi HTTP/1.1\r\n"
  7389. " : "
  7390. " "
  7391. " ");
  7392. }
  7393. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7394. // A certain header line causes an exception if the header property *name* is
  7395. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7396. // greedy matcher and requires backtracking when there are a lot of ":"
  7397. // characters.
  7398. // This occurs with libc++ but not libstdc++.
  7399. test_raw_request(
  7400. "GET /hi HTTP/1.1\r\n"
  7401. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7402. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7403. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7404. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7405. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7406. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7407. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7408. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7409. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7410. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7411. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7412. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7413. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7414. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7415. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7416. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7417. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7418. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7419. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7420. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7421. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7422. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7423. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7424. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7425. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7426. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7427. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7428. "&&&%%%");
  7429. }
  7430. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7431. // Make sure this doesn't crash the server.
  7432. // In a previous version of the header line regex, the "\r" rendered the line
  7433. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7434. // a new position where the leading white space ended and the field value
  7435. // began.
  7436. // The crash occurs with libc++ but not libstdc++.
  7437. test_raw_request("GET /hi HTTP/1.1\r\n"
  7438. "a:" +
  7439. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7440. "\r\n"
  7441. "\r\n");
  7442. }
  7443. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7444. std::string out;
  7445. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7446. "Content-Type: text/plain\r\n"
  7447. "Transfer-Encoding: chunked\r\n"
  7448. "\r\n"
  7449. "nothex\r\n",
  7450. &out);
  7451. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7452. }
  7453. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7454. std::string out;
  7455. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7456. "Content-Type: text/plain\r\n"
  7457. "Transfer-Encoding: chunked\r\n"
  7458. "\r\n"
  7459. "3\r\n"
  7460. "xyz\r\n"
  7461. "NaN\r\n",
  7462. &out);
  7463. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7464. }
  7465. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7466. std::string out;
  7467. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7468. "Content-Type: text/plain\r\n"
  7469. "Transfer-Encoding: chunked\r\n"
  7470. "\r\n"
  7471. // Length is too large for 64 bits.
  7472. "1ffffffffffffffff\r\n"
  7473. "xyz\r\n",
  7474. &out);
  7475. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7476. }
  7477. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7478. test_raw_request("GET /hi HTTP/1.1\r\n"
  7479. "Content-Type: text/plain\r\n\r");
  7480. }
  7481. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7482. std::string out;
  7483. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7484. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7485. }
  7486. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7487. Server svr;
  7488. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7489. EXPECT_TRUE(!req.remote_addr.empty());
  7490. });
  7491. thread t = thread([&] { svr.listen(HOST, PORT); });
  7492. auto se = detail::scope_exit([&] {
  7493. svr.stop();
  7494. t.join();
  7495. ASSERT_FALSE(svr.is_running());
  7496. });
  7497. svr.wait_until_ready();
  7498. // Send an invalid request line to trigger Bad Request
  7499. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7500. std::string out;
  7501. ASSERT_TRUE(send_request(5, bad_req, &out));
  7502. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7503. }
  7504. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7505. std::string out;
  7506. std::string request(
  7507. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7508. test_raw_request(request, &out);
  7509. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7510. }
  7511. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7512. std::string out;
  7513. std::string request(
  7514. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7515. test_raw_request(request, &out);
  7516. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7517. }
  7518. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7519. std::string out;
  7520. std::string request(
  7521. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7522. test_raw_request(request, &out);
  7523. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7524. }
  7525. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7526. std::string out;
  7527. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7528. "Test: \r\n\r\n",
  7529. &out);
  7530. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7531. }
  7532. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7533. Server svr;
  7534. std::string x_custom;
  7535. std::string cookie;
  7536. std::string xff;
  7537. std::string x_unicode;
  7538. std::string x_iis;
  7539. svr.Get("/check", [&](const Request &req, Response &res) {
  7540. x_custom = req.get_header_value("X-Custom");
  7541. cookie = req.get_header_value("Cookie");
  7542. xff = req.get_header_value("X-Forwarded-For");
  7543. x_unicode = req.get_header_value("X-Unicode");
  7544. x_iis = req.get_header_value("X-IIS");
  7545. res.set_content("ok", "text/plain");
  7546. });
  7547. thread t = thread([&] { svr.listen(HOST, PORT); });
  7548. auto se = detail::scope_exit([&] {
  7549. svr.stop();
  7550. t.join();
  7551. ASSERT_FALSE(svr.is_running());
  7552. });
  7553. svr.wait_until_ready();
  7554. const std::string req = "GET /check HTTP/1.1\r\n"
  7555. "Host: localhost\r\n"
  7556. "X-Custom: a%0D%0AInjected: b\r\n"
  7557. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7558. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7559. "X-Unicode: %E3%81%82\r\n"
  7560. "X-IIS: %u00E9\r\n"
  7561. "Connection: close\r\n"
  7562. "\r\n";
  7563. std::string res;
  7564. ASSERT_TRUE(send_request(5, req, &res));
  7565. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7566. // Every value must be returned verbatim (wire form), with no decoding.
  7567. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7568. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7569. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7570. EXPECT_EQ("%E3%81%82", x_unicode);
  7571. EXPECT_EQ("%u00E9", x_iis);
  7572. }
  7573. // Applications that previously relied on automatic percent-decoding can
  7574. // reproduce the old behavior by explicitly calling decode_path_component()
  7575. // or, for RFC 3986 conformance, decode_uri_component().
  7576. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7577. Server svr;
  7578. std::string decoded;
  7579. svr.Get("/check", [&](const Request &req, Response &res) {
  7580. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7581. res.set_content("ok", "text/plain");
  7582. });
  7583. thread t = thread([&] { svr.listen(HOST, PORT); });
  7584. auto se = detail::scope_exit([&] {
  7585. svr.stop();
  7586. t.join();
  7587. ASSERT_FALSE(svr.is_running());
  7588. });
  7589. svr.wait_until_ready();
  7590. const std::string req = "GET /check HTTP/1.1\r\n"
  7591. "Host: localhost\r\n"
  7592. "X-Custom: hello%20world\r\n"
  7593. "Connection: close\r\n"
  7594. "\r\n";
  7595. std::string res;
  7596. ASSERT_TRUE(send_request(5, req, &res));
  7597. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7598. EXPECT_EQ("hello world", decoded);
  7599. }
  7600. // Regression test for #2033. Browsers send Referer values that include
  7601. // percent-encoded characters such as %0A inside the URL. Decoding the
  7602. // header value would either trip the post-decode CR/LF/NUL guard (the
  7603. // original bug, returning 400) or, after that guard was relaxed, silently
  7604. // store a literal LF — both unacceptable. The wire form must round-trip.
  7605. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7606. Server svr;
  7607. std::string referer;
  7608. svr.Get("/check", [&](const Request &req, Response &res) {
  7609. referer = req.get_header_value("Referer");
  7610. res.set_content("ok", "text/plain");
  7611. });
  7612. thread t = thread([&] { svr.listen(HOST, PORT); });
  7613. auto se = detail::scope_exit([&] {
  7614. svr.stop();
  7615. t.join();
  7616. ASSERT_FALSE(svr.is_running());
  7617. });
  7618. svr.wait_until_ready();
  7619. const std::string req = "GET /check HTTP/1.1\r\n"
  7620. "Host: localhost\r\n"
  7621. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7622. "Connection: close\r\n"
  7623. "\r\n";
  7624. std::string res;
  7625. ASSERT_TRUE(send_request(5, req, &res));
  7626. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7627. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7628. }
  7629. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7630. Server svr;
  7631. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7632. res.set_header("Cache-Control", "no-cache");
  7633. res.set_chunked_content_provider(
  7634. "text/event-stream", [](size_t offset, DataSink &sink) {
  7635. std::string s = "data:";
  7636. s += std::to_string(offset);
  7637. s += "\n\n";
  7638. auto ret = sink.write(s.data(), s.size());
  7639. EXPECT_TRUE(ret);
  7640. std::this_thread::sleep_for(std::chrono::seconds(1));
  7641. return true;
  7642. });
  7643. });
  7644. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7645. svr.wait_until_ready();
  7646. Client client(HOST, PORT);
  7647. const Headers headers = {{"Accept", "text/event-stream"}};
  7648. auto get_thread = std::thread([&client, &headers]() {
  7649. auto res = client.Get(
  7650. "/events", headers,
  7651. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7652. });
  7653. auto se = detail::scope_exit([&] {
  7654. svr.stop();
  7655. get_thread.join();
  7656. listen_thread.join();
  7657. ASSERT_FALSE(svr.is_running());
  7658. });
  7659. // Give GET time to get a few messages.
  7660. std::this_thread::sleep_for(std::chrono::seconds(2));
  7661. }
  7662. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7663. httplib::Server svr;
  7664. svr.Post("/hi",
  7665. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7666. res.status = StatusCode::OK_200;
  7667. });
  7668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7669. svr.wait_until_ready();
  7670. Client cli(HOST, PORT);
  7671. auto res = cli.Post("/hi", "data", "text/plain");
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. svr.stop();
  7675. thread.join();
  7676. ASSERT_FALSE(svr.is_running());
  7677. res = cli.Post("/hi", "data", "text/plain");
  7678. ASSERT_FALSE(res);
  7679. }
  7680. TEST(ServerStopTest, ListenFailure) {
  7681. Server svr;
  7682. auto t = thread([&]() {
  7683. auto ret = svr.listen("????", PORT);
  7684. EXPECT_FALSE(ret);
  7685. });
  7686. svr.wait_until_ready();
  7687. svr.stop();
  7688. t.join();
  7689. }
  7690. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7691. TEST(ServerStopTest, Decommision) {
  7692. Server svr;
  7693. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7694. for (int i = 0; i < 4; i++) {
  7695. auto is_even = !(i % 2);
  7696. std::thread t{[&] {
  7697. try {
  7698. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7699. if (is_even) {
  7700. throw std::runtime_error("Some thing that happens to go wrong.");
  7701. }
  7702. svr.listen(HOST, PORT);
  7703. } catch (...) { svr.decommission(); }
  7704. }};
  7705. svr.wait_until_ready();
  7706. // Server is up
  7707. {
  7708. Client cli(HOST, PORT);
  7709. auto res = cli.Get("/hi");
  7710. if (is_even) {
  7711. EXPECT_FALSE(res);
  7712. } else {
  7713. EXPECT_TRUE(res);
  7714. EXPECT_EQ("hi...", res->body);
  7715. }
  7716. }
  7717. svr.stop();
  7718. t.join();
  7719. // Server is down...
  7720. {
  7721. Client cli(HOST, PORT);
  7722. auto res = cli.Get("/hi");
  7723. EXPECT_FALSE(res);
  7724. }
  7725. }
  7726. }
  7727. #endif
  7728. // Helper function for string body upload progress tests
  7729. template <typename SetupHandler, typename ClientCall>
  7730. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7731. ClientCall &&client_call,
  7732. const string &body) {
  7733. Server svr;
  7734. setup_handler(svr);
  7735. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7736. auto se = detail::scope_exit([&] {
  7737. svr.stop();
  7738. t.join();
  7739. });
  7740. svr.wait_until_ready();
  7741. Client cli(HOST, PORT);
  7742. vector<uint64_t> progress_values;
  7743. bool progress_called = false;
  7744. auto res =
  7745. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7746. progress_values.push_back(current);
  7747. progress_called = true;
  7748. return true;
  7749. });
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(200, res->status);
  7752. EXPECT_TRUE(progress_called);
  7753. }
  7754. TEST(UploadProgressTest, PostStringBodyBasic) {
  7755. TestStringBodyUploadProgress(
  7756. [](Server &svr) {
  7757. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7758. res.set_content("received", "text/plain");
  7759. });
  7760. },
  7761. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7762. return cli.Post("/test", body, "text/plain", progress_callback);
  7763. },
  7764. "test data for upload progress");
  7765. }
  7766. TEST(UploadProgressTest, PutStringBodyBasic) {
  7767. TestStringBodyUploadProgress(
  7768. [](Server &svr) {
  7769. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7770. res.set_content("put received", "text/plain");
  7771. });
  7772. },
  7773. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7774. return cli.Put("/test", body, "text/plain", progress_callback);
  7775. },
  7776. "put test data for upload progress");
  7777. }
  7778. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7779. TestStringBodyUploadProgress(
  7780. [](Server &svr) {
  7781. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7782. res.set_content("patch received", "text/plain");
  7783. });
  7784. },
  7785. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7786. return cli.Patch("/test", body, "text/plain", progress_callback);
  7787. },
  7788. "patch test data for upload progress");
  7789. }
  7790. // Helper function for content provider upload progress tests
  7791. template <typename SetupHandler, typename ClientCall>
  7792. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7793. ClientCall &&client_call) {
  7794. Server svr;
  7795. setup_handler(svr);
  7796. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7797. auto se = detail::scope_exit([&] {
  7798. svr.stop();
  7799. t.join();
  7800. });
  7801. svr.wait_until_ready();
  7802. Client cli(HOST, PORT);
  7803. vector<uint64_t> progress_values;
  7804. auto res =
  7805. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7806. progress_values.push_back(current);
  7807. return true;
  7808. });
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(200, res->status);
  7811. EXPECT_FALSE(progress_values.empty());
  7812. }
  7813. TEST(UploadProgressTest, PostContentProviderProgress) {
  7814. TestContentProviderUploadProgress(
  7815. [](Server &svr) {
  7816. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7817. res.set_content("provider received", "text/plain");
  7818. });
  7819. },
  7820. [](Client &cli, UploadProgress progress_callback) {
  7821. return cli.Post(
  7822. "/test", 10,
  7823. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7824. sink.os << "test data";
  7825. return true;
  7826. },
  7827. "text/plain", progress_callback);
  7828. });
  7829. }
  7830. // Helper function for multipart upload progress tests
  7831. template <typename SetupHandler, typename ClientCall>
  7832. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7833. ClientCall &&client_call,
  7834. const string &endpoint) {
  7835. Server svr;
  7836. setup_handler(svr);
  7837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7838. auto se = detail::scope_exit([&] {
  7839. svr.stop();
  7840. t.join();
  7841. });
  7842. svr.wait_until_ready();
  7843. Client cli(HOST, PORT);
  7844. vector<uint64_t> progress_values;
  7845. UploadFormDataItems items = {
  7846. {"field1", "value1", "", ""},
  7847. {"field2", "longer value for progress tracking test", "", ""},
  7848. {"file1", "file content data for upload progress", "test.txt",
  7849. "text/plain"}};
  7850. auto res = client_call(cli, endpoint, items,
  7851. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7852. progress_values.push_back(current);
  7853. return true;
  7854. });
  7855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7856. EXPECT_EQ(200, res->status);
  7857. EXPECT_FALSE(progress_values.empty());
  7858. }
  7859. TEST(UploadProgressTest, PostMultipartProgress) {
  7860. TestMultipartUploadProgress(
  7861. [](Server &svr) {
  7862. svr.Post("/multipart", [](const Request &req, Response &res) {
  7863. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7864. res.set_content("multipart received", "text/plain");
  7865. });
  7866. },
  7867. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7868. UploadProgress progress_callback) {
  7869. return cli.Post(endpoint, items, progress_callback);
  7870. },
  7871. "/multipart");
  7872. }
  7873. // Helper function for basic download progress tests
  7874. template <typename SetupHandler, typename ClientCall>
  7875. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7876. ClientCall &&client_call, const string &endpoint,
  7877. size_t expected_content_size) {
  7878. Server svr;
  7879. setup_handler(svr);
  7880. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7881. auto se = detail::scope_exit([&] {
  7882. svr.stop();
  7883. t.join();
  7884. });
  7885. svr.wait_until_ready();
  7886. Client cli(HOST, PORT);
  7887. vector<uint64_t> progress_values;
  7888. auto res = client_call(cli, endpoint,
  7889. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7890. progress_values.push_back(current);
  7891. return true;
  7892. });
  7893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7894. EXPECT_EQ(200, res->status);
  7895. EXPECT_FALSE(progress_values.empty());
  7896. EXPECT_EQ(expected_content_size, res->body.size());
  7897. }
  7898. TEST(DownloadProgressTest, GetBasic) {
  7899. TestBasicDownloadProgress(
  7900. [](Server &svr) {
  7901. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7902. string content(1000, 'D');
  7903. res.set_content(content, "text/plain");
  7904. });
  7905. },
  7906. [](Client &cli, const string &endpoint,
  7907. DownloadProgress progress_callback) {
  7908. return cli.Get(endpoint, progress_callback);
  7909. },
  7910. "/download", 1000u);
  7911. }
  7912. // Helper function for content receiver download progress tests
  7913. template <typename SetupHandler, typename ClientCall>
  7914. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7915. ClientCall &&client_call,
  7916. const string &endpoint,
  7917. size_t expected_content_size) {
  7918. Server svr;
  7919. setup_handler(svr);
  7920. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7921. auto se = detail::scope_exit([&] {
  7922. svr.stop();
  7923. t.join();
  7924. });
  7925. svr.wait_until_ready();
  7926. Client cli(HOST, PORT);
  7927. vector<uint64_t> progress_values;
  7928. string received_body;
  7929. auto res = client_call(
  7930. cli, endpoint,
  7931. [&](const char *data, size_t data_length) -> bool {
  7932. received_body.append(data, data_length);
  7933. return true;
  7934. },
  7935. [&](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. EXPECT_EQ(expected_content_size, received_body.size());
  7943. EXPECT_TRUE(res->body.empty());
  7944. }
  7945. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7946. TestContentReceiverDownloadProgress(
  7947. [](Server &svr) {
  7948. svr.Get("/download-receiver",
  7949. [](const Request & /*req*/, Response &res) {
  7950. string content(2000, 'R');
  7951. res.set_content(content, "text/plain");
  7952. });
  7953. },
  7954. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7955. DownloadProgress progress_callback) {
  7956. return cli.Get(endpoint, content_receiver, progress_callback);
  7957. },
  7958. "/download-receiver", 2000u);
  7959. }
  7960. TEST(StreamingTest, NoContentLengthStreaming) {
  7961. Server svr;
  7962. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7963. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7964. if (offset < 6) {
  7965. sink.os << (offset < 3 ? "a" : "b");
  7966. } else {
  7967. sink.done();
  7968. }
  7969. return true;
  7970. });
  7971. });
  7972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7973. auto listen_se = detail::scope_exit([&] {
  7974. svr.stop();
  7975. listen_thread.join();
  7976. ASSERT_FALSE(svr.is_running());
  7977. });
  7978. svr.wait_until_ready();
  7979. Client client(HOST, PORT);
  7980. auto get_thread = std::thread([&client]() {
  7981. std::string s;
  7982. auto res =
  7983. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7984. s += std::string(data, len);
  7985. return true;
  7986. });
  7987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7988. EXPECT_EQ(StatusCode::OK_200, res->status);
  7989. EXPECT_EQ("aaabbb", s);
  7990. });
  7991. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7992. // Give GET time to get a few messages.
  7993. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7994. }
  7995. TEST(MountTest, Unmount) {
  7996. Server svr;
  7997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7998. auto se = detail::scope_exit([&] {
  7999. svr.stop();
  8000. listen_thread.join();
  8001. ASSERT_FALSE(svr.is_running());
  8002. });
  8003. svr.wait_until_ready();
  8004. Client cli("localhost", PORT);
  8005. svr.set_mount_point("/mount2", "./www2");
  8006. auto res = cli.Get("/");
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8009. res = cli.Get("/mount2/dir/test.html");
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. svr.set_mount_point("/", "./www");
  8013. res = cli.Get("/dir/");
  8014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8015. EXPECT_EQ(StatusCode::OK_200, res->status);
  8016. svr.remove_mount_point("/");
  8017. res = cli.Get("/dir/");
  8018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8020. svr.remove_mount_point("/mount2");
  8021. res = cli.Get("/mount2/dir/test.html");
  8022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8023. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8024. }
  8025. TEST(MountTest, Redicect) {
  8026. Server svr;
  8027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8028. auto se = detail::scope_exit([&] {
  8029. svr.stop();
  8030. listen_thread.join();
  8031. ASSERT_FALSE(svr.is_running());
  8032. });
  8033. svr.set_mount_point("/", "./www");
  8034. svr.wait_until_ready();
  8035. Client cli("localhost", PORT);
  8036. auto res = cli.Get("/dir/");
  8037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8038. EXPECT_EQ(StatusCode::OK_200, res->status);
  8039. res = cli.Get("/dir");
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8042. res = cli.Get("/file");
  8043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8044. EXPECT_EQ(StatusCode::OK_200, res->status);
  8045. res = cli.Get("/file/");
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8048. cli.set_follow_location(true);
  8049. res = cli.Get("/dir");
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ(StatusCode::OK_200, res->status);
  8052. }
  8053. TEST(MountTest, MultibytesPathName) {
  8054. Server svr;
  8055. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. listen_thread.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.set_mount_point("/", "./www");
  8062. svr.wait_until_ready();
  8063. Client cli("localhost", PORT);
  8064. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. EXPECT_EQ(StatusCode::OK_200, res->status);
  8067. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8068. }
  8069. #ifdef _WIN32
  8070. // Issue #2435: mmap::open() must succeed even when another handle holds
  8071. // the file open for writing (e.g. an active log file).
  8072. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8073. const char *path = "mmap_concurrent_writer_test.txt";
  8074. const char *content = "hello";
  8075. {
  8076. std::ofstream f(path, std::ios::binary);
  8077. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8078. }
  8079. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8080. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8081. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8082. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8083. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8084. detail::mmap m(path);
  8085. ASSERT_TRUE(m.is_open());
  8086. EXPECT_EQ(strlen(content), m.size());
  8087. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8088. }
  8089. #endif
  8090. #ifndef _WIN32
  8091. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8092. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8093. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8094. TEST(MmapTest, FailedMappingIsNotOpen) {
  8095. const char *path = "./mmap_failed_mapping_test_dir";
  8096. ASSERT_EQ(0, ::mkdir(path, 0755));
  8097. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8098. detail::mmap m(path);
  8099. EXPECT_FALSE(m.is_open());
  8100. EXPECT_EQ(0U, m.size());
  8101. EXPECT_NE(static_cast<const void *>(m.data()),
  8102. static_cast<const void *>(MAP_FAILED));
  8103. }
  8104. #endif
  8105. TEST(KeepAliveTest, ReadTimeout) {
  8106. Server svr;
  8107. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8108. std::this_thread::sleep_for(std::chrono::seconds(2));
  8109. res.set_content("a", "text/plain");
  8110. });
  8111. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8112. res.set_content("b", "text/plain");
  8113. });
  8114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8115. auto se = detail::scope_exit([&] {
  8116. svr.stop();
  8117. listen_thread.join();
  8118. ASSERT_FALSE(svr.is_running());
  8119. });
  8120. svr.wait_until_ready();
  8121. Client cli("localhost", PORT);
  8122. cli.set_keep_alive(true);
  8123. cli.set_read_timeout(std::chrono::seconds(1));
  8124. auto resa = cli.Get("/a");
  8125. ASSERT_FALSE(resa);
  8126. EXPECT_EQ(Error::Read, resa.error());
  8127. auto resb = cli.Get("/b");
  8128. ASSERT_TRUE(resb);
  8129. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8130. EXPECT_EQ("b", resb->body);
  8131. }
  8132. TEST(KeepAliveTest, MaxCount) {
  8133. size_t keep_alive_max_count = 3;
  8134. Server svr;
  8135. svr.set_keep_alive_max_count(keep_alive_max_count);
  8136. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8137. res.set_content("Hello World!", "text/plain");
  8138. });
  8139. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8140. auto se = detail::scope_exit([&] {
  8141. svr.stop();
  8142. listen_thread.join();
  8143. ASSERT_FALSE(svr.is_running());
  8144. });
  8145. svr.wait_until_ready();
  8146. Client cli(HOST, PORT);
  8147. cli.set_keep_alive(true);
  8148. for (size_t i = 0; i < 5; i++) {
  8149. auto result = cli.Get("/hi");
  8150. ASSERT_TRUE(result);
  8151. EXPECT_EQ(StatusCode::OK_200, result->status);
  8152. if (i == keep_alive_max_count - 1) {
  8153. EXPECT_EQ("close", result->get_header_value("Connection"));
  8154. } else {
  8155. EXPECT_FALSE(result->has_header("Connection"));
  8156. }
  8157. }
  8158. }
  8159. TEST(KeepAliveTest, Issue1041) {
  8160. Server svr;
  8161. svr.set_keep_alive_timeout(3);
  8162. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8163. res.set_content("Hello World!", "text/plain");
  8164. });
  8165. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8166. auto se = detail::scope_exit([&] {
  8167. svr.stop();
  8168. listen_thread.join();
  8169. ASSERT_FALSE(svr.is_running());
  8170. });
  8171. svr.wait_until_ready();
  8172. Client cli(HOST, PORT);
  8173. cli.set_keep_alive(true);
  8174. auto result = cli.Get("/hi");
  8175. ASSERT_TRUE(result);
  8176. EXPECT_EQ(StatusCode::OK_200, result->status);
  8177. std::this_thread::sleep_for(std::chrono::seconds(5));
  8178. result = cli.Get("/hi");
  8179. ASSERT_TRUE(result);
  8180. EXPECT_EQ(StatusCode::OK_200, result->status);
  8181. }
  8182. TEST(KeepAliveTest, Issue1959) {
  8183. Server svr;
  8184. svr.set_keep_alive_timeout(5);
  8185. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8186. res.set_content("a", "text/plain");
  8187. });
  8188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8189. auto se = detail::scope_exit([&] {
  8190. if (!svr.is_running()) return;
  8191. svr.stop();
  8192. listen_thread.join();
  8193. ASSERT_FALSE(svr.is_running());
  8194. });
  8195. svr.wait_until_ready();
  8196. Client cli("localhost", PORT);
  8197. cli.set_keep_alive(true);
  8198. using namespace std::chrono;
  8199. auto start = steady_clock::now();
  8200. cli.Get("/a");
  8201. svr.stop();
  8202. listen_thread.join();
  8203. auto end = steady_clock::now();
  8204. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8205. EXPECT_LT(elapsed, 5000);
  8206. }
  8207. #ifdef CPPHTTPLIB_SSL_ENABLED
  8208. TEST(KeepAliveTest, SSLClientReconnection) {
  8209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8210. ASSERT_TRUE(svr.is_valid());
  8211. svr.set_keep_alive_timeout(1);
  8212. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8213. res.set_content("Hello World!", "text/plain");
  8214. });
  8215. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8216. auto se = detail::scope_exit([&] {
  8217. svr.stop();
  8218. listen_thread.join();
  8219. ASSERT_FALSE(svr.is_running());
  8220. });
  8221. svr.wait_until_ready();
  8222. SSLClient cli(HOST, PORT);
  8223. cli.enable_server_certificate_verification(false);
  8224. cli.set_keep_alive(true);
  8225. auto result = cli.Get("/hi");
  8226. ASSERT_TRUE(result);
  8227. EXPECT_EQ(StatusCode::OK_200, result->status);
  8228. result = cli.Get("/hi");
  8229. ASSERT_TRUE(result);
  8230. EXPECT_EQ(StatusCode::OK_200, result->status);
  8231. std::this_thread::sleep_for(std::chrono::seconds(2));
  8232. // Recoonect
  8233. result = cli.Get("/hi");
  8234. ASSERT_TRUE(result);
  8235. EXPECT_EQ(StatusCode::OK_200, result->status);
  8236. result = cli.Get("/hi");
  8237. ASSERT_TRUE(result);
  8238. EXPECT_EQ(StatusCode::OK_200, result->status);
  8239. }
  8240. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8242. ASSERT_TRUE(svr.is_valid());
  8243. svr.set_keep_alive_timeout(1);
  8244. std::string content = "reconnect";
  8245. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8246. res.set_content("Hello World!", "text/plain");
  8247. });
  8248. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8249. auto se = detail::scope_exit([&] {
  8250. svr.stop();
  8251. listen_thread.join();
  8252. ASSERT_FALSE(svr.is_running());
  8253. });
  8254. svr.wait_until_ready();
  8255. SSLClient cli(HOST, PORT);
  8256. cli.enable_server_certificate_verification(false);
  8257. cli.set_keep_alive(true);
  8258. auto result = cli.Post(
  8259. "/hi", content.size(),
  8260. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8261. sink.write(content.c_str(), content.size());
  8262. return true;
  8263. },
  8264. "text/plain");
  8265. ASSERT_TRUE(result);
  8266. EXPECT_EQ(200, result->status);
  8267. std::this_thread::sleep_for(std::chrono::seconds(2));
  8268. // Recoonect
  8269. result = cli.Post(
  8270. "/hi", content.size(),
  8271. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8272. sink.write(content.c_str(), content.size());
  8273. return true;
  8274. },
  8275. "text/plain");
  8276. ASSERT_TRUE(result);
  8277. EXPECT_EQ(200, result->status);
  8278. result = cli.Post(
  8279. "/hi", content.size(),
  8280. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8281. sink.write(content.c_str(), content.size());
  8282. return true;
  8283. },
  8284. "text/plain");
  8285. ASSERT_TRUE(result);
  8286. EXPECT_EQ(200, result->status);
  8287. }
  8288. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8289. using namespace httplib::tls;
  8290. {
  8291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8292. ASSERT_TRUE(svr.is_valid());
  8293. svr.Get("/sni", [&](const Request &req, Response &res) {
  8294. std::string expected = req.sni();
  8295. EXPECT_EQ(expected, req.get_param_value("expected"));
  8296. res.set_content("ok", "text/plain");
  8297. });
  8298. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8299. auto se = detail::scope_exit([&] {
  8300. svr.stop();
  8301. listen_thread.join();
  8302. ASSERT_FALSE(svr.is_running());
  8303. });
  8304. svr.wait_until_ready();
  8305. {
  8306. SSLClient cli("localhost", PORT);
  8307. cli.enable_server_certificate_verification(false);
  8308. auto res = cli.Get("/sni?expected=localhost");
  8309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8310. }
  8311. {
  8312. SSLClient cli("::1", PORT);
  8313. cli.enable_server_certificate_verification(false);
  8314. auto res = cli.Get("/sni?expected=");
  8315. // NOTE: This may fail if the server is listening on IPv4 only
  8316. // (e.g., when localhost resolves to 127.0.0.1 only)
  8317. if (res) {
  8318. EXPECT_EQ(StatusCode::OK_200, res->status);
  8319. } else {
  8320. EXPECT_EQ(Error::Connection, res.error());
  8321. }
  8322. }
  8323. }
  8324. }
  8325. #endif
  8326. TEST(ClientProblemDetectionTest, ContentProvider) {
  8327. Server svr;
  8328. size_t content_length = 1024 * 1024;
  8329. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8330. res.set_content_provider(
  8331. content_length, "text/plain",
  8332. [&](size_t offset, size_t length, DataSink &sink) {
  8333. auto out_len = std::min(length, static_cast<size_t>(1024));
  8334. std::string out(out_len, '@');
  8335. sink.write(out.data(), out_len);
  8336. return offset < 4096;
  8337. },
  8338. [](bool success) { ASSERT_FALSE(success); });
  8339. });
  8340. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8341. res.set_content_provider(
  8342. 0, "text/plain",
  8343. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8344. EXPECT_TRUE(false);
  8345. return true;
  8346. },
  8347. [](bool success) { ASSERT_FALSE(success); });
  8348. });
  8349. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8350. auto se = detail::scope_exit([&] {
  8351. svr.stop();
  8352. listen_thread.join();
  8353. ASSERT_FALSE(svr.is_running());
  8354. });
  8355. svr.wait_until_ready();
  8356. Client cli("localhost", PORT);
  8357. {
  8358. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8359. size_t /*data_length*/) { return false; });
  8360. ASSERT_FALSE(res);
  8361. }
  8362. {
  8363. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8364. size_t /*data_length*/) { return false; });
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. }
  8367. }
  8368. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8369. Server svr;
  8370. svr.set_error_handler([](Request const &, Response &res) -> void {
  8371. res.set_chunked_content_provider(
  8372. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8373. sink.os << "hello";
  8374. sink.os << "world";
  8375. sink.done();
  8376. return true;
  8377. });
  8378. });
  8379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. listen_thread.join();
  8383. ASSERT_FALSE(svr.is_running());
  8384. });
  8385. svr.wait_until_ready();
  8386. Client cli("localhost", PORT);
  8387. auto res = cli.Get("/");
  8388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8390. EXPECT_EQ("helloworld", res->body);
  8391. }
  8392. TEST(LongPollingTest, ClientCloseDetection) {
  8393. Server svr;
  8394. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8395. res.set_chunked_content_provider(
  8396. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8397. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8398. sink.os << "hello";
  8399. auto count = 10;
  8400. while (count > 0 && sink.is_writable()) {
  8401. this_thread::sleep_for(chrono::milliseconds(10));
  8402. count--;
  8403. }
  8404. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8405. return true;
  8406. });
  8407. });
  8408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8409. auto se = detail::scope_exit([&] {
  8410. svr.stop();
  8411. listen_thread.join();
  8412. ASSERT_FALSE(svr.is_running());
  8413. });
  8414. svr.wait_until_ready();
  8415. Client cli("localhost", PORT);
  8416. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8417. EXPECT_EQ("hello", string(data, data_length));
  8418. return false; // close the socket immediately.
  8419. });
  8420. ASSERT_FALSE(res);
  8421. }
  8422. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8423. Server svr;
  8424. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8425. res.set_chunked_content_provider(
  8426. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8427. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8428. sink.os << "hello";
  8429. EXPECT_TRUE(sink.os.good());
  8430. // Wait for the client to close the connection
  8431. auto count = 10;
  8432. while (count > 0 && sink.is_writable()) {
  8433. this_thread::sleep_for(chrono::milliseconds(10));
  8434. count--;
  8435. }
  8436. // After client disconnect, write repeatedly until the socket
  8437. // write actually fails (small writes may be absorbed by the
  8438. // kernel buffer)
  8439. std::string chunk(1024, 'x');
  8440. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8441. sink.os << chunk;
  8442. }
  8443. EXPECT_TRUE(sink.os.fail());
  8444. return true;
  8445. });
  8446. });
  8447. auto port = svr.bind_to_any_port("localhost");
  8448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8449. auto se = detail::scope_exit([&] {
  8450. svr.stop();
  8451. listen_thread.join();
  8452. ASSERT_FALSE(svr.is_running());
  8453. });
  8454. svr.wait_until_ready();
  8455. Client cli("localhost", port);
  8456. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8457. EXPECT_EQ("hello", string(data, data_length));
  8458. return false; // close the socket immediately.
  8459. });
  8460. ASSERT_FALSE(res);
  8461. }
  8462. TEST(GetWithParametersTest, GetWithParameters) {
  8463. Server svr;
  8464. svr.Get("/", [&](const Request &req, Response &) {
  8465. EXPECT_EQ("world", req.get_param_value("hello"));
  8466. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8467. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8468. });
  8469. svr.Get("/params", [&](const Request &req, Response &) {
  8470. EXPECT_EQ("world", req.get_param_value("hello"));
  8471. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8472. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8473. });
  8474. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8475. EXPECT_EQ("resource-id", req.matches[1]);
  8476. EXPECT_EQ("foo", req.get_param_value("param1"));
  8477. EXPECT_EQ("bar", req.get_param_value("param2"));
  8478. });
  8479. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8480. EXPECT_EQ("user-id", req.path_params.at("id"));
  8481. EXPECT_EQ("foo", req.get_param_value("param1"));
  8482. EXPECT_EQ("bar", req.get_param_value("param2"));
  8483. });
  8484. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8485. auto se = detail::scope_exit([&] {
  8486. svr.stop();
  8487. listen_thread.join();
  8488. ASSERT_FALSE(svr.is_running());
  8489. });
  8490. svr.wait_until_ready();
  8491. {
  8492. Client cli(HOST, PORT);
  8493. Params params;
  8494. params.emplace("hello", "world");
  8495. params.emplace("hello2", "world2");
  8496. params.emplace("hello3", "world3");
  8497. auto res = cli.Get("/", params, Headers{});
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(StatusCode::OK_200, res->status);
  8500. }
  8501. {
  8502. Client cli(HOST, PORT);
  8503. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. {
  8508. Client cli(HOST, PORT);
  8509. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. }
  8513. {
  8514. Client cli(HOST, PORT);
  8515. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8517. EXPECT_EQ(StatusCode::OK_200, res->status);
  8518. }
  8519. }
  8520. TEST(GetWithParametersTest, GetWithParameters2) {
  8521. Server svr;
  8522. svr.Get("/", [&](const Request &req, Response &res) {
  8523. auto text = req.get_param_value("hello");
  8524. res.set_content(text, "text/plain");
  8525. });
  8526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. listen_thread.join();
  8530. ASSERT_FALSE(svr.is_running());
  8531. });
  8532. svr.wait_until_ready();
  8533. Client cli("localhost", PORT);
  8534. Params params;
  8535. params.emplace("hello", "world");
  8536. std::string body;
  8537. auto res = cli.Get("/", params, Headers{},
  8538. [&](const char *data, size_t data_length) {
  8539. body.append(data, data_length);
  8540. return true;
  8541. });
  8542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8543. EXPECT_EQ(StatusCode::OK_200, res->status);
  8544. EXPECT_EQ("world", body);
  8545. }
  8546. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8547. Server svr;
  8548. svr.Get("/search", [&](const Request &req, Response &res) {
  8549. auto q = req.get_param_value("q");
  8550. res.set_content(q, "text/plain");
  8551. });
  8552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8553. auto se = detail::scope_exit([&] {
  8554. svr.stop();
  8555. listen_thread.join();
  8556. ASSERT_FALSE(svr.is_running());
  8557. });
  8558. svr.wait_until_ready();
  8559. Client cli("localhost", PORT);
  8560. // Verify that Get(path, params) works without requiring Headers argument
  8561. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8563. EXPECT_EQ(StatusCode::OK_200, res->status);
  8564. EXPECT_EQ("cpp-httplib", res->body);
  8565. }
  8566. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8567. auto host = "httpbingo.org";
  8568. auto path = std::string{"/range/32"};
  8569. #ifdef CPPHTTPLIB_SSL_ENABLED
  8570. SSLClient cli(host);
  8571. #else
  8572. Client cli(host);
  8573. #endif
  8574. cli.set_default_headers({make_range_header({{1, 10}})});
  8575. cli.set_connection_timeout(5);
  8576. {
  8577. auto res = cli.Get(path);
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ("bcdefghijk", res->body);
  8580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8581. }
  8582. {
  8583. auto res = cli.Get(path);
  8584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8585. EXPECT_EQ("bcdefghijk", res->body);
  8586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8587. }
  8588. }
  8589. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8590. Server svr;
  8591. svr.set_default_headers({{"Hello", "World"}});
  8592. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8593. res.set_content("ok", "text/plain");
  8594. });
  8595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8596. auto se = detail::scope_exit([&] {
  8597. svr.stop();
  8598. listen_thread.join();
  8599. ASSERT_FALSE(svr.is_running());
  8600. });
  8601. svr.wait_until_ready();
  8602. Client cli("localhost", PORT);
  8603. auto res = cli.Get("/");
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(StatusCode::OK_200, res->status);
  8606. EXPECT_EQ("ok", res->body);
  8607. EXPECT_EQ("World", res->get_header_value("Hello"));
  8608. }
  8609. #ifdef CPPHTTPLIB_SSL_ENABLED
  8610. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8612. ASSERT_TRUE(svr.is_valid());
  8613. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8614. std::this_thread::sleep_for(std::chrono::seconds(2));
  8615. res.set_content("a", "text/plain");
  8616. });
  8617. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8618. res.set_content("b", "text/plain");
  8619. });
  8620. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8621. auto se = detail::scope_exit([&] {
  8622. svr.stop();
  8623. listen_thread.join();
  8624. ASSERT_FALSE(svr.is_running());
  8625. });
  8626. svr.wait_until_ready();
  8627. SSLClient cli("localhost", PORT);
  8628. cli.enable_server_certificate_verification(false);
  8629. cli.set_keep_alive(true);
  8630. cli.set_read_timeout(std::chrono::seconds(1));
  8631. auto resa = cli.Get("/a");
  8632. ASSERT_TRUE(!resa);
  8633. EXPECT_EQ(Error::Read, resa.error());
  8634. auto resb = cli.Get("/b");
  8635. ASSERT_TRUE(resb);
  8636. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8637. EXPECT_EQ("b", resb->body);
  8638. }
  8639. #endif
  8640. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8641. protected:
  8642. ServerTestWithAI_PASSIVE()
  8643. : cli_(HOST, PORT)
  8644. #ifdef CPPHTTPLIB_SSL_ENABLED
  8645. ,
  8646. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8647. #endif
  8648. {
  8649. #ifdef CPPHTTPLIB_SSL_ENABLED
  8650. cli_.enable_server_certificate_verification(false);
  8651. #endif
  8652. }
  8653. virtual void SetUp() {
  8654. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8655. res.set_content("Hello World!", "text/plain");
  8656. });
  8657. t_ = thread(
  8658. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8659. svr_.wait_until_ready();
  8660. }
  8661. virtual void TearDown() {
  8662. svr_.stop();
  8663. t_.join();
  8664. }
  8665. #ifdef CPPHTTPLIB_SSL_ENABLED
  8666. SSLClient cli_;
  8667. SSLServer svr_;
  8668. #else
  8669. Client cli_;
  8670. Server svr_;
  8671. #endif
  8672. thread t_;
  8673. };
  8674. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8675. auto res = cli_.Get("/hi");
  8676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8677. EXPECT_EQ(StatusCode::OK_200, res->status);
  8678. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8679. EXPECT_EQ("Hello World!", res->body);
  8680. }
  8681. class ServerUpDownTest : public ::testing::Test {
  8682. protected:
  8683. ServerUpDownTest() : cli_(HOST, PORT) {}
  8684. virtual void SetUp() {
  8685. t_ = thread([&]() {
  8686. svr_.bind_to_any_port(HOST);
  8687. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8688. ASSERT_TRUE(svr_.listen_after_bind());
  8689. });
  8690. svr_.wait_until_ready();
  8691. }
  8692. virtual void TearDown() {
  8693. svr_.stop();
  8694. t_.join();
  8695. }
  8696. Client cli_;
  8697. Server svr_;
  8698. thread t_;
  8699. };
  8700. TEST_F(ServerUpDownTest, QuickStartStop) {
  8701. // Should not crash, especially when run with
  8702. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8703. }
  8704. class PayloadMaxLengthTest : public ::testing::Test {
  8705. protected:
  8706. PayloadMaxLengthTest()
  8707. : cli_(HOST, PORT)
  8708. #ifdef CPPHTTPLIB_SSL_ENABLED
  8709. ,
  8710. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8711. #endif
  8712. {
  8713. #ifdef CPPHTTPLIB_SSL_ENABLED
  8714. cli_.enable_server_certificate_verification(false);
  8715. #endif
  8716. }
  8717. virtual void SetUp() {
  8718. svr_.set_payload_max_length(8);
  8719. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8720. res.set_content("test", "text/plain");
  8721. });
  8722. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8723. svr_.wait_until_ready();
  8724. }
  8725. virtual void TearDown() {
  8726. svr_.stop();
  8727. t_.join();
  8728. }
  8729. #ifdef CPPHTTPLIB_SSL_ENABLED
  8730. SSLClient cli_;
  8731. SSLServer svr_;
  8732. #else
  8733. Client cli_;
  8734. Server svr_;
  8735. #endif
  8736. thread t_;
  8737. };
  8738. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8739. auto res = cli_.Post("/test", "123456789", "text/plain");
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8742. res = cli_.Post("/test", "12345678", "text/plain");
  8743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8744. EXPECT_EQ(StatusCode::OK_200, res->status);
  8745. }
  8746. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8747. // Test chunked encoding with payload exceeding the 8-byte limit
  8748. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8749. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8751. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8752. }
  8753. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8754. // Test chunked encoding with payload within the 8-byte limit
  8755. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8756. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8758. EXPECT_EQ(StatusCode::OK_200, res->status);
  8759. }
  8760. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8761. // Test using send_request to send chunked data exceeding payload limit
  8762. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8763. "Host: " +
  8764. std::string(HOST) + ":" + std::to_string(PORT) +
  8765. "\r\n"
  8766. "Transfer-Encoding: chunked\r\n"
  8767. "Connection: close\r\n"
  8768. "\r\n"
  8769. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8770. "0123456789\r\n"
  8771. "0\r\n" // End chunk
  8772. "\r\n";
  8773. std::string response;
  8774. bool result = send_request(1, chunked_request, &response);
  8775. if (!result) {
  8776. // If send_request fails, it might be because the server closed the
  8777. // connection due to payload limit enforcement, which is acceptable
  8778. SUCCEED()
  8779. << "Server rejected oversized chunked request (connection closed)";
  8780. } else {
  8781. // If we got a response, check if it's an error response or connection was
  8782. // closed early Short response length indicates connection was closed due to
  8783. // payload limit
  8784. if (response.length() <= 10) {
  8785. SUCCEED() << "Server closed connection for oversized chunked request";
  8786. } else {
  8787. // Check for error status codes
  8788. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8789. response.find("Payload Too Large") != std::string::npos ||
  8790. response.find("400") != std::string::npos);
  8791. }
  8792. }
  8793. }
  8794. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8795. // Test request without Content-Length header exceeding payload limit
  8796. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8797. "Host: " +
  8798. std::string(HOST) + ":" +
  8799. std::to_string(PORT) +
  8800. "\r\n"
  8801. "Connection: close\r\n"
  8802. "\r\n";
  8803. // Add payload exceeding the 8-byte limit
  8804. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8805. request_without_content_length += large_payload;
  8806. std::string response;
  8807. bool result = send_request(1, request_without_content_length, &response);
  8808. if (!result) {
  8809. // If send_request fails, server likely closed connection due to payload
  8810. // limit
  8811. SUCCEED() << "Server rejected oversized request without Content-Length "
  8812. "(connection closed)";
  8813. } else {
  8814. // Check if server responded with error or closed connection early
  8815. if (response.length() <= 10) {
  8816. SUCCEED() << "Server closed connection for oversized request without "
  8817. "Content-Length";
  8818. } else {
  8819. // Check for error status codes
  8820. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8821. response.find("Payload Too Large") != std::string::npos ||
  8822. response.find("400") != std::string::npos);
  8823. }
  8824. }
  8825. }
  8826. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8827. // Test request without Content-Length header within payload limit
  8828. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8829. "Host: " +
  8830. std::string(HOST) + ":" +
  8831. std::to_string(PORT) +
  8832. "\r\n"
  8833. "Connection: close\r\n"
  8834. "\r\n";
  8835. // Add payload within the 8-byte limit
  8836. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8837. request_without_content_length += small_payload;
  8838. std::string response;
  8839. bool result = send_request(1, request_without_content_length, &response);
  8840. // For requests without Content-Length, the server may have different behavior
  8841. // The key is that it should not reject due to payload limit for small
  8842. // payloads
  8843. if (result) {
  8844. // Check for any HTTP response (success or error, but not connection closed)
  8845. if (response.length() > 10) {
  8846. SUCCEED()
  8847. << "Server processed request without Content-Length within limit";
  8848. } else {
  8849. // Short response might indicate connection closed, which is acceptable
  8850. SUCCEED() << "Server closed connection for request without "
  8851. "Content-Length (acceptable behavior)";
  8852. }
  8853. } else {
  8854. // Connection failure might be due to protocol requirements
  8855. SUCCEED() << "Connection issue with request without Content-Length "
  8856. "(environment-specific)";
  8857. }
  8858. }
  8859. class LargePayloadMaxLengthTest : public ::testing::Test {
  8860. protected:
  8861. LargePayloadMaxLengthTest()
  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. // Set 10MB payload limit
  8874. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8875. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8876. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8877. res.set_content("Large payload test", "text/plain");
  8878. });
  8879. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8880. svr_.wait_until_ready();
  8881. }
  8882. virtual void TearDown() {
  8883. svr_.stop();
  8884. t_.join();
  8885. }
  8886. #ifdef CPPHTTPLIB_SSL_ENABLED
  8887. SSLClient cli_;
  8888. SSLServer svr_;
  8889. #else
  8890. Client cli_;
  8891. Server svr_;
  8892. #endif
  8893. thread t_;
  8894. };
  8895. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8896. // Test chunked encoding with payload within 10MB limit
  8897. std::string medium_payload(5 * 1024 * 1024,
  8898. 'A'); // 5MB payload, within 10MB limit
  8899. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. }
  8903. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8904. // Test chunked encoding with payload exceeding 10MB limit
  8905. std::string large_payload(12 * 1024 * 1024,
  8906. 'B'); // 12MB payload, exceeds 10MB limit
  8907. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8908. // Server may either return 413 or close the connection
  8909. if (res) {
  8910. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8911. } else {
  8912. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8913. }
  8914. }
  8915. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8916. // Test request without Content-Length header within 10MB limit
  8917. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8918. "Host: " +
  8919. std::string(HOST) + ":" +
  8920. std::to_string(PORT) +
  8921. "\r\n"
  8922. "Connection: close\r\n"
  8923. "\r\n";
  8924. // Add 1MB payload (within 10MB limit)
  8925. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8926. request_without_content_length += medium_payload;
  8927. std::string response;
  8928. bool result = send_request(5, request_without_content_length, &response);
  8929. if (result) {
  8930. // Should get a proper HTTP response for payloads within limit
  8931. if (response.length() > 10) {
  8932. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8933. "10MB limit";
  8934. } else {
  8935. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8936. "Content-Length)";
  8937. }
  8938. } else {
  8939. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8940. }
  8941. }
  8942. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8943. // Test request without Content-Length header exceeding 10MB limit
  8944. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8945. "Host: " +
  8946. std::string(HOST) + ":" +
  8947. std::to_string(PORT) +
  8948. "\r\n"
  8949. "Connection: close\r\n"
  8950. "\r\n";
  8951. // Add 12MB payload (exceeds 10MB limit)
  8952. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8953. request_without_content_length += large_payload;
  8954. std::string response;
  8955. bool result = send_request(10, request_without_content_length, &response);
  8956. if (!result) {
  8957. // Server should close connection due to payload limit
  8958. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8959. "(connection closed)";
  8960. } else {
  8961. // Check for error response
  8962. if (response.length() <= 10) {
  8963. SUCCEED()
  8964. << "Server closed connection for 12MB request exceeding 10MB limit";
  8965. } else {
  8966. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8967. response.find("Payload Too Large") != std::string::npos ||
  8968. response.find("400") != std::string::npos);
  8969. }
  8970. }
  8971. }
  8972. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8973. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8974. // path.
  8975. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8976. Server svr;
  8977. const size_t LIMIT = 64 * 1024; // 64KB
  8978. svr.set_payload_max_length(LIMIT);
  8979. size_t total = 0;
  8980. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8981. const ContentReader &content_reader) {
  8982. content_reader([&](const char * /*data*/, size_t len) {
  8983. total += len;
  8984. return true;
  8985. });
  8986. res.status = 200;
  8987. res.set_content("stream_ok", "text/plain");
  8988. });
  8989. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8990. auto se = detail::scope_exit([&] {
  8991. svr.stop();
  8992. thread.join();
  8993. ASSERT_FALSE(svr.is_running());
  8994. });
  8995. svr.wait_until_ready();
  8996. // Prepare 256KB raw data and gzip-compress it
  8997. std::string raw(256 * 1024, 'A');
  8998. std::string gz;
  8999. {
  9000. z_stream zs{};
  9001. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9002. Z_DEFAULT_STRATEGY);
  9003. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9004. zs.avail_in = static_cast<uInt>(raw.size());
  9005. char outbuf[4096];
  9006. int ret;
  9007. do {
  9008. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9009. zs.avail_out = sizeof(outbuf);
  9010. ret = deflate(&zs, Z_FINISH);
  9011. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9012. } while (ret != Z_STREAM_END);
  9013. deflateEnd(&zs);
  9014. }
  9015. Client cli(HOST, PORT);
  9016. cli.set_connection_timeout(std::chrono::seconds(5));
  9017. Headers headers = {{"Content-Encoding", "gzip"}};
  9018. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9019. "application/octet-stream");
  9020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9021. // Server must reject oversized decompressed payloads with 413.
  9022. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9023. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9024. EXPECT_LE(total, LIMIT);
  9025. }
  9026. #endif
  9027. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9028. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9029. // the payload must be passed through untouched instead of being rejected.
  9030. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9031. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9032. Server svr;
  9033. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9034. res.set_content(body, "image/jpeg");
  9035. res.set_header("Content-Encoding", "UTF-8");
  9036. });
  9037. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9038. res.set_content(body, "image/jpeg");
  9039. res.set_header("Content-Encoding", "identity");
  9040. });
  9041. svr.Post("/echo", [](const Request &req, Response &res) {
  9042. res.set_content(req.body, "image/jpeg");
  9043. });
  9044. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9045. auto se = detail::scope_exit([&] {
  9046. svr.stop();
  9047. t.join();
  9048. ASSERT_FALSE(svr.is_running());
  9049. });
  9050. svr.wait_until_ready();
  9051. Client cli(HOST, PORT);
  9052. {
  9053. auto res = cli.Get("/image");
  9054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9055. EXPECT_EQ(StatusCode::OK_200, res->status);
  9056. EXPECT_EQ(body, res->body);
  9057. }
  9058. {
  9059. auto res = cli.Get("/identity");
  9060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9061. EXPECT_EQ(StatusCode::OK_200, res->status);
  9062. EXPECT_EQ(body, res->body);
  9063. }
  9064. {
  9065. // The same applies to a request body reaching the server.
  9066. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9067. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. EXPECT_EQ(body, res->body);
  9071. }
  9072. }
  9073. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9074. // gzip-encoded response even when the build has no zlib support.
  9075. static const char GZIPPED_HELLO_WORLD[] = {
  9076. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9077. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9078. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9079. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9080. // A content coding cpp-httplib recognizes but was not built with must be
  9081. // reported as such. Handing the still-compressed payload back to the caller
  9082. // would silently corrupt it.
  9083. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9084. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9085. Server svr;
  9086. // "image/jpeg" keeps the server from applying a content coding of its own,
  9087. // so the hand-crafted Content-Encoding below survives.
  9088. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9089. res.set_content(gzipped, "image/jpeg");
  9090. res.set_header("Content-Encoding", "gzip");
  9091. });
  9092. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9093. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9094. res.set_content(gzipped, "image/jpeg");
  9095. res.set_header("Content-Encoding", "GZIP");
  9096. });
  9097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9098. auto se = detail::scope_exit([&] {
  9099. svr.stop();
  9100. t.join();
  9101. ASSERT_FALSE(svr.is_running());
  9102. });
  9103. svr.wait_until_ready();
  9104. Client cli(HOST, PORT);
  9105. {
  9106. auto res = cli.Get("/gzipped");
  9107. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9109. EXPECT_EQ("Hello World!", res->body);
  9110. #else
  9111. ASSERT_FALSE(res);
  9112. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9113. #endif
  9114. }
  9115. {
  9116. // open_stream() must behave the same way.
  9117. auto handle = cli.open_stream("GET", "/gzipped");
  9118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9119. ASSERT_TRUE(handle.is_valid());
  9120. std::string received;
  9121. char buf[256];
  9122. ssize_t n;
  9123. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9124. received.append(buf, static_cast<size_t>(n));
  9125. }
  9126. EXPECT_EQ("Hello World!", received);
  9127. #else
  9128. EXPECT_FALSE(handle.is_valid());
  9129. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9130. #endif
  9131. }
  9132. {
  9133. // A differently-cased coding must not be mistaken for an unknown one, or
  9134. // the body would be handed back still compressed.
  9135. auto res = cli.Get("/gzipped-uppercase");
  9136. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9138. EXPECT_EQ("Hello World!", res->body);
  9139. #else
  9140. ASSERT_FALSE(res);
  9141. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9142. #endif
  9143. }
  9144. }
  9145. // Regression test for DoS vulnerability: a malicious server sending a response
  9146. // without Content-Length header must not cause unbounded memory consumption on
  9147. // the client side. The client should stop reading after a reasonable limit,
  9148. // similar to the server-side set_payload_max_length protection.
  9149. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9150. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9151. #ifndef _WIN32
  9152. signal(SIGPIPE, SIG_IGN);
  9153. #endif
  9154. auto server_thread = std::thread([] {
  9155. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9156. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9157. default_socket_options(srv);
  9158. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9159. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9160. sockaddr_in addr{};
  9161. addr.sin_family = AF_INET;
  9162. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9163. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9164. int opt = 1;
  9165. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9166. #ifdef _WIN32
  9167. reinterpret_cast<const char *>(&opt),
  9168. #else
  9169. &opt,
  9170. #endif
  9171. sizeof(opt));
  9172. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9173. ::listen(srv, 1);
  9174. sockaddr_in cli_addr{};
  9175. socklen_t cli_len = sizeof(cli_addr);
  9176. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9177. if (cli != INVALID_SOCKET) {
  9178. char buf[4096];
  9179. ::recv(cli, buf, sizeof(buf), 0);
  9180. // Malicious response: no Content-Length, no chunked encoding
  9181. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9182. "Connection: close\r\n"
  9183. "\r\n";
  9184. ::send(cli,
  9185. #ifdef _WIN32
  9186. static_cast<const char *>(response_header.c_str()),
  9187. static_cast<int>(response_header.size()),
  9188. #else
  9189. response_header.c_str(), response_header.size(),
  9190. #endif
  9191. 0);
  9192. // Send 10MB of data
  9193. std::string chunk(64 * 1024, 'A');
  9194. size_t total_sent = 0;
  9195. while (total_sent < MALICIOUS_DATA_SIZE) {
  9196. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9197. auto sent = ::send(cli,
  9198. #ifdef _WIN32
  9199. static_cast<const char *>(chunk.c_str()),
  9200. static_cast<int>(to_send),
  9201. #else
  9202. chunk.c_str(), to_send,
  9203. #endif
  9204. 0);
  9205. if (sent <= 0) break;
  9206. total_sent += static_cast<size_t>(sent);
  9207. }
  9208. detail::close_socket(cli);
  9209. }
  9210. detail::close_socket(srv);
  9211. });
  9212. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9213. size_t total_read = 0;
  9214. {
  9215. Client cli("127.0.0.1", PORT + 2);
  9216. cli.set_read_timeout(5, 0);
  9217. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9218. auto stream = cli.open_stream("GET", "/malicious");
  9219. ASSERT_TRUE(stream.is_valid());
  9220. char buffer[64 * 1024];
  9221. ssize_t n;
  9222. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9223. total_read += static_cast<size_t>(n);
  9224. }
  9225. } // StreamHandle and Client destroyed here, closing the socket
  9226. server_thread.join();
  9227. // With set_payload_max_length, the client must stop reading before consuming
  9228. // all 10MB. The read loop should be cut off at or near the configured limit.
  9229. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9230. << "Client read " << total_read << " bytes, exceeding the configured "
  9231. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9232. }
  9233. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9234. // the entire response body without truncation.
  9235. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9236. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9237. #ifndef _WIN32
  9238. signal(SIGPIPE, SIG_IGN);
  9239. #endif
  9240. auto server_thread = std::thread([] {
  9241. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9242. default_socket_options(srv);
  9243. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9245. sockaddr_in addr{};
  9246. addr.sin_family = AF_INET;
  9247. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9248. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9249. int opt = 1;
  9250. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9251. #ifdef _WIN32
  9252. reinterpret_cast<const char *>(&opt),
  9253. #else
  9254. &opt,
  9255. #endif
  9256. sizeof(opt));
  9257. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9258. ::listen(srv, 1);
  9259. sockaddr_in cli_addr{};
  9260. socklen_t cli_len = sizeof(cli_addr);
  9261. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9262. if (cli != INVALID_SOCKET) {
  9263. char buf[4096];
  9264. ::recv(cli, buf, sizeof(buf), 0);
  9265. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9266. "Connection: close\r\n"
  9267. "\r\n";
  9268. ::send(cli,
  9269. #ifdef _WIN32
  9270. static_cast<const char *>(response_header.c_str()),
  9271. static_cast<int>(response_header.size()),
  9272. #else
  9273. response_header.c_str(), response_header.size(),
  9274. #endif
  9275. 0);
  9276. std::string chunk(64 * 1024, 'A');
  9277. size_t total_sent = 0;
  9278. while (total_sent < DATA_SIZE) {
  9279. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9280. auto sent = ::send(cli,
  9281. #ifdef _WIN32
  9282. static_cast<const char *>(chunk.c_str()),
  9283. static_cast<int>(to_send),
  9284. #else
  9285. chunk.c_str(), to_send,
  9286. #endif
  9287. 0);
  9288. if (sent <= 0) break;
  9289. total_sent += static_cast<size_t>(sent);
  9290. }
  9291. #ifdef _WIN32
  9292. ::shutdown(cli, SD_SEND);
  9293. #else
  9294. ::shutdown(cli, SHUT_WR);
  9295. #endif
  9296. // Drain until the client closes its end, ensuring all data is delivered
  9297. char drain[1024];
  9298. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9299. detail::close_socket(cli);
  9300. }
  9301. detail::close_socket(srv);
  9302. });
  9303. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9304. size_t total_read = 0;
  9305. {
  9306. Client cli("127.0.0.1", PORT + 2);
  9307. cli.set_read_timeout(5, 0);
  9308. cli.set_payload_max_length(0); // 0 means no limit
  9309. auto stream = cli.open_stream("GET", "/data");
  9310. ASSERT_TRUE(stream.is_valid());
  9311. char buffer[64 * 1024];
  9312. ssize_t n;
  9313. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9314. total_read += static_cast<size_t>(n);
  9315. }
  9316. }
  9317. server_thread.join();
  9318. EXPECT_EQ(total_read, DATA_SIZE)
  9319. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9320. << " bytes without truncation, but only read " << total_read << " bytes.";
  9321. }
  9322. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9323. // enormous Content-Length must not cause the client to pre-allocate a huge
  9324. // response body buffer. The reservation is capped at payload_max_length_, and
  9325. // the read itself fails when the body exceeds the limit.
  9326. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9327. #ifndef _WIN32
  9328. signal(SIGPIPE, SIG_IGN);
  9329. #endif
  9330. auto server_thread = std::thread([] {
  9331. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9332. default_socket_options(srv);
  9333. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9334. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9335. sockaddr_in addr{};
  9336. addr.sin_family = AF_INET;
  9337. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9338. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9339. int opt = 1;
  9340. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9341. #ifdef _WIN32
  9342. reinterpret_cast<const char *>(&opt),
  9343. #else
  9344. &opt,
  9345. #endif
  9346. sizeof(opt));
  9347. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9348. ::listen(srv, 1);
  9349. sockaddr_in cli_addr{};
  9350. socklen_t cli_len = sizeof(cli_addr);
  9351. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9352. if (cli != INVALID_SOCKET) {
  9353. char buf[4096];
  9354. ::recv(cli, buf, sizeof(buf), 0);
  9355. // Malicious response: claim a 20GB body but send only a tiny payload.
  9356. std::string response = "HTTP/1.1 200 OK\r\n"
  9357. "Content-Length: 20000000000\r\n"
  9358. "\r\n"
  9359. "abc";
  9360. ::send(cli,
  9361. #ifdef _WIN32
  9362. static_cast<const char *>(response.c_str()),
  9363. static_cast<int>(response.size()),
  9364. #else
  9365. response.c_str(), response.size(),
  9366. #endif
  9367. 0);
  9368. detail::close_socket(cli);
  9369. }
  9370. detail::close_socket(srv);
  9371. });
  9372. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9373. {
  9374. Client cli("127.0.0.1", PORT + 2);
  9375. cli.set_read_timeout(5, 0);
  9376. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9377. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9378. // (server claims more bytes than payload_max_length permits), but it must
  9379. // not exhaust memory before getting there.
  9380. auto res = cli.Get("/malicious");
  9381. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9382. }
  9383. server_thread.join();
  9384. }
  9385. // Verify that content_receiver bypasses the default payload_max_length,
  9386. // allowing streaming downloads larger than 100MB without requiring an explicit
  9387. // set_payload_max_length call.
  9388. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9389. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9390. #ifndef _WIN32
  9391. signal(SIGPIPE, SIG_IGN);
  9392. #endif
  9393. auto server_thread = std::thread([] {
  9394. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9395. default_socket_options(srv);
  9396. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9397. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9398. sockaddr_in addr{};
  9399. addr.sin_family = AF_INET;
  9400. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9401. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9402. int opt = 1;
  9403. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9404. #ifdef _WIN32
  9405. reinterpret_cast<const char *>(&opt),
  9406. #else
  9407. &opt,
  9408. #endif
  9409. sizeof(opt));
  9410. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9411. ::listen(srv, 1);
  9412. sockaddr_in cli_addr{};
  9413. socklen_t cli_len = sizeof(cli_addr);
  9414. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9415. if (cli != INVALID_SOCKET) {
  9416. char buf[4096];
  9417. ::recv(cli, buf, sizeof(buf), 0);
  9418. // Response with Content-Length larger than default 100MB limit
  9419. auto content_length = std::to_string(DATA_SIZE);
  9420. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9421. "Content-Length: " +
  9422. content_length +
  9423. "\r\n"
  9424. "Connection: close\r\n"
  9425. "\r\n";
  9426. ::send(cli,
  9427. #ifdef _WIN32
  9428. static_cast<const char *>(response_header.c_str()),
  9429. static_cast<int>(response_header.size()),
  9430. #else
  9431. response_header.c_str(), response_header.size(),
  9432. #endif
  9433. 0);
  9434. std::string chunk(64 * 1024, 'A');
  9435. size_t total_sent = 0;
  9436. while (total_sent < DATA_SIZE) {
  9437. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9438. auto sent = ::send(cli,
  9439. #ifdef _WIN32
  9440. static_cast<const char *>(chunk.c_str()),
  9441. static_cast<int>(to_send),
  9442. #else
  9443. chunk.c_str(), to_send,
  9444. #endif
  9445. 0);
  9446. if (sent <= 0) break;
  9447. total_sent += static_cast<size_t>(sent);
  9448. }
  9449. detail::close_socket(cli);
  9450. }
  9451. detail::close_socket(srv);
  9452. });
  9453. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9454. size_t total_received = 0;
  9455. {
  9456. Client cli("127.0.0.1", PORT + 2);
  9457. cli.set_read_timeout(10, 0);
  9458. // Do NOT call set_payload_max_length — use the default 100MB limit
  9459. auto res =
  9460. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9461. total_received += data_length;
  9462. return true;
  9463. });
  9464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9465. EXPECT_EQ(StatusCode::OK_200, res->status);
  9466. }
  9467. server_thread.join();
  9468. EXPECT_EQ(total_received, DATA_SIZE)
  9469. << "With content_receiver, the client should read all " << DATA_SIZE
  9470. << " bytes despite the default 100MB payload_max_length, but only read "
  9471. << total_received << " bytes.";
  9472. }
  9473. // Verify that an explicit set_payload_max_length smaller than the response is
  9474. // enforced even when a content_receiver is used.
  9475. TEST(ClientVulnerabilityTest,
  9476. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9477. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9478. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9479. #ifndef _WIN32
  9480. signal(SIGPIPE, SIG_IGN);
  9481. #endif
  9482. auto server_thread = std::thread([] {
  9483. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9484. default_socket_options(srv);
  9485. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9487. sockaddr_in addr{};
  9488. addr.sin_family = AF_INET;
  9489. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9491. int opt = 1;
  9492. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9493. #ifdef _WIN32
  9494. reinterpret_cast<const char *>(&opt),
  9495. #else
  9496. &opt,
  9497. #endif
  9498. sizeof(opt));
  9499. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9500. ::listen(srv, 1);
  9501. sockaddr_in cli_addr{};
  9502. socklen_t cli_len = sizeof(cli_addr);
  9503. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9504. if (cli != INVALID_SOCKET) {
  9505. char buf[4096];
  9506. ::recv(cli, buf, sizeof(buf), 0);
  9507. auto content_length = std::to_string(DATA_SIZE);
  9508. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9509. "Content-Length: " +
  9510. content_length +
  9511. "\r\n"
  9512. "Connection: close\r\n"
  9513. "\r\n";
  9514. ::send(cli,
  9515. #ifdef _WIN32
  9516. static_cast<const char *>(response_header.c_str()),
  9517. static_cast<int>(response_header.size()),
  9518. #else
  9519. response_header.c_str(), response_header.size(),
  9520. #endif
  9521. 0);
  9522. std::string chunk(64 * 1024, 'A');
  9523. size_t total_sent = 0;
  9524. while (total_sent < DATA_SIZE) {
  9525. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9526. auto sent = ::send(cli,
  9527. #ifdef _WIN32
  9528. static_cast<const char *>(chunk.c_str()),
  9529. static_cast<int>(to_send),
  9530. #else
  9531. chunk.c_str(), to_send,
  9532. #endif
  9533. 0);
  9534. if (sent <= 0) break;
  9535. total_sent += static_cast<size_t>(sent);
  9536. }
  9537. detail::close_socket(cli);
  9538. }
  9539. detail::close_socket(srv);
  9540. });
  9541. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9542. size_t total_received = 0;
  9543. {
  9544. Client cli("127.0.0.1", PORT + 2);
  9545. cli.set_read_timeout(10, 0);
  9546. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9547. auto res =
  9548. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9549. total_received += data_length;
  9550. return true;
  9551. });
  9552. // Should fail because 200MB exceeds the explicit 150MB limit
  9553. EXPECT_FALSE(res);
  9554. }
  9555. server_thread.join();
  9556. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9557. << "Client with content_receiver should respect the explicit "
  9558. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9559. << total_received << " bytes.";
  9560. }
  9561. // Verify that an explicit set_payload_max_length larger than the response
  9562. // allows the content_receiver to read all data successfully.
  9563. TEST(ClientVulnerabilityTest,
  9564. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9565. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9566. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9567. #ifndef _WIN32
  9568. signal(SIGPIPE, SIG_IGN);
  9569. #endif
  9570. auto server_thread = std::thread([] {
  9571. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9572. default_socket_options(srv);
  9573. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9574. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9575. sockaddr_in addr{};
  9576. addr.sin_family = AF_INET;
  9577. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9578. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9579. int opt = 1;
  9580. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9581. #ifdef _WIN32
  9582. reinterpret_cast<const char *>(&opt),
  9583. #else
  9584. &opt,
  9585. #endif
  9586. sizeof(opt));
  9587. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9588. ::listen(srv, 1);
  9589. sockaddr_in cli_addr{};
  9590. socklen_t cli_len = sizeof(cli_addr);
  9591. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9592. if (cli != INVALID_SOCKET) {
  9593. char buf[4096];
  9594. ::recv(cli, buf, sizeof(buf), 0);
  9595. auto content_length = std::to_string(DATA_SIZE);
  9596. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9597. "Content-Length: " +
  9598. content_length +
  9599. "\r\n"
  9600. "Connection: close\r\n"
  9601. "\r\n";
  9602. ::send(cli,
  9603. #ifdef _WIN32
  9604. static_cast<const char *>(response_header.c_str()),
  9605. static_cast<int>(response_header.size()),
  9606. #else
  9607. response_header.c_str(), response_header.size(),
  9608. #endif
  9609. 0);
  9610. std::string chunk(64 * 1024, 'A');
  9611. size_t total_sent = 0;
  9612. while (total_sent < DATA_SIZE) {
  9613. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9614. auto sent = ::send(cli,
  9615. #ifdef _WIN32
  9616. static_cast<const char *>(chunk.c_str()),
  9617. static_cast<int>(to_send),
  9618. #else
  9619. chunk.c_str(), to_send,
  9620. #endif
  9621. 0);
  9622. if (sent <= 0) break;
  9623. total_sent += static_cast<size_t>(sent);
  9624. }
  9625. #ifdef _WIN32
  9626. ::shutdown(cli, SD_SEND);
  9627. #else
  9628. ::shutdown(cli, SHUT_WR);
  9629. #endif
  9630. char drain[1024];
  9631. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9632. detail::close_socket(cli);
  9633. }
  9634. detail::close_socket(srv);
  9635. });
  9636. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9637. size_t total_received = 0;
  9638. {
  9639. Client cli("127.0.0.1", PORT + 2);
  9640. cli.set_read_timeout(10, 0);
  9641. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9642. auto res =
  9643. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9644. total_received += data_length;
  9645. return true;
  9646. });
  9647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9648. EXPECT_EQ(StatusCode::OK_200, res->status);
  9649. }
  9650. server_thread.join();
  9651. EXPECT_EQ(total_received, DATA_SIZE)
  9652. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9653. << " bytes (larger than " << DATA_SIZE
  9654. << " bytes response), content_receiver should read all data, but only "
  9655. "read "
  9656. << total_received << " bytes.";
  9657. }
  9658. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9659. // Regression test for "zip bomb" attack on the client side: a malicious server
  9660. // sends a small gzip-compressed response that decompresses to a huge payload.
  9661. // The client must enforce payload_max_length on the decompressed size.
  9662. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9663. constexpr size_t DECOMPRESSED_SIZE =
  9664. 10 * 1024 * 1024; // 10MB after decompression
  9665. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9666. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9667. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9668. std::string compressed;
  9669. {
  9670. httplib::detail::gzip_compressor compressor;
  9671. bool ok =
  9672. compressor.compress(uncompressed.data(), uncompressed.size(),
  9673. /*last=*/true, [&](const char *buf, size_t len) {
  9674. compressed.append(buf, len);
  9675. return true;
  9676. });
  9677. ASSERT_TRUE(ok);
  9678. }
  9679. // Sanity: compressed data should be much smaller than the decompressed size
  9680. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9681. #ifndef _WIN32
  9682. signal(SIGPIPE, SIG_IGN);
  9683. #endif
  9684. // Set up the listening socket in the main thread so the server is guaranteed
  9685. // to be ready before the client connects (eliminates race condition).
  9686. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9687. default_socket_options(srv);
  9688. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9689. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9690. sockaddr_in addr{};
  9691. addr.sin_family = AF_INET;
  9692. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9693. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9694. int opt = 1;
  9695. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9696. #ifdef _WIN32
  9697. reinterpret_cast<const char *>(&opt),
  9698. #else
  9699. &opt,
  9700. #endif
  9701. sizeof(opt));
  9702. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9703. ASSERT_EQ(0, ::listen(srv, 1));
  9704. auto server_thread = std::thread([&compressed, srv] {
  9705. sockaddr_in cli_addr{};
  9706. socklen_t cli_len = sizeof(cli_addr);
  9707. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9708. if (cli != INVALID_SOCKET) {
  9709. // Read the full HTTP request (until \r\n\r\n)
  9710. char buf[4096];
  9711. size_t total = 0;
  9712. while (total < sizeof(buf)) {
  9713. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9714. if (n <= 0) break;
  9715. total += static_cast<size_t>(n);
  9716. // Check for end of headers
  9717. if (total >= 4) {
  9718. std::string req(buf, total);
  9719. if (req.find("\r\n\r\n") != std::string::npos) break;
  9720. }
  9721. }
  9722. // Malicious response: gzip-compressed body, no Content-Length
  9723. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9724. "Content-Encoding: gzip\r\n"
  9725. "Connection: close\r\n"
  9726. "\r\n";
  9727. ::send(cli,
  9728. #ifdef _WIN32
  9729. static_cast<const char *>(response_header.c_str()),
  9730. static_cast<int>(response_header.size()),
  9731. #else
  9732. response_header.c_str(), response_header.size(),
  9733. #endif
  9734. 0);
  9735. // Send the compressed payload (small on the wire, huge when decompressed)
  9736. size_t total_sent = 0;
  9737. while (total_sent < compressed.size()) {
  9738. auto to_send = std::min(compressed.size() - total_sent,
  9739. static_cast<size_t>(64 * 1024));
  9740. auto sent =
  9741. ::send(cli,
  9742. #ifdef _WIN32
  9743. static_cast<const char *>(compressed.c_str() + total_sent),
  9744. static_cast<int>(to_send),
  9745. #else
  9746. compressed.c_str() + total_sent, to_send,
  9747. #endif
  9748. 0);
  9749. if (sent <= 0) break;
  9750. total_sent += static_cast<size_t>(sent);
  9751. }
  9752. detail::close_socket(cli);
  9753. }
  9754. });
  9755. auto se = detail::scope_exit([&] {
  9756. detail::close_socket(srv);
  9757. server_thread.join();
  9758. });
  9759. size_t total_decompressed = 0;
  9760. {
  9761. Client cli("127.0.0.1", PORT + 3);
  9762. cli.set_read_timeout(5, 0);
  9763. cli.set_decompress(true);
  9764. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9765. auto stream = cli.open_stream("GET", "/zipbomb");
  9766. ASSERT_TRUE(stream.is_valid());
  9767. char buffer[64 * 1024];
  9768. ssize_t n;
  9769. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9770. total_decompressed += static_cast<size_t>(n);
  9771. }
  9772. }
  9773. // The decompressed size must be capped by payload_max_length. Without
  9774. // protection, the client would decompress the full 10MB from a tiny
  9775. // compressed payload, enabling a zip bomb DoS attack.
  9776. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9777. << "Client decompressed " << total_decompressed
  9778. << " bytes from a gzip response. The decompressed size should be "
  9779. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9780. }
  9781. #endif
  9782. TEST(HostAndPortPropertiesTest, NoSSL) {
  9783. httplib::Client cli("www.google.com", 1234);
  9784. ASSERT_EQ("www.google.com", cli.host());
  9785. ASSERT_EQ(1234, cli.port());
  9786. }
  9787. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9788. httplib::Client cli("www.google.com:1234");
  9789. ASSERT_EQ("www.google.com", cli.host());
  9790. ASSERT_EQ(1234, cli.port());
  9791. }
  9792. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9793. // Port number that overflows int — should not crash, client becomes invalid
  9794. httplib::Client cli("http://www.google.com:99999999999999999999");
  9795. ASSERT_FALSE(cli.is_valid());
  9796. }
  9797. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9798. // Port 99999 exceeds valid range (1-65535) — should not crash
  9799. httplib::Client cli("http://www.google.com:99999");
  9800. ASSERT_FALSE(cli.is_valid());
  9801. }
  9802. #ifdef CPPHTTPLIB_SSL_ENABLED
  9803. TEST(HostAndPortPropertiesTest, SSL) {
  9804. httplib::SSLClient cli("www.google.com");
  9805. ASSERT_EQ("www.google.com", cli.host());
  9806. ASSERT_EQ(443, cli.port());
  9807. }
  9808. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9809. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9810. std::string cert;
  9811. read_file(CA_CERT_FILE, cert);
  9812. httplib::SSLClient httplib_client("www.google.com");
  9813. // Load CA store first time
  9814. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9815. // Load CA store second time (update)
  9816. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9817. // Verify client is still valid and can make connections
  9818. httplib_client.enable_server_certificate_verification(true);
  9819. auto res = httplib_client.Get("/");
  9820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9821. // Google may return 200 or 301 depending on various factors
  9822. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9823. res->status == StatusCode::MovedPermanently_301);
  9824. }
  9825. TEST(SSLClientTest, ServerNameIndication_Online) {
  9826. auto host = "httpbingo.org";
  9827. auto path = std::string{"/get"};
  9828. SSLClient cli(host, 443);
  9829. auto res = cli.Get(path);
  9830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9831. ASSERT_EQ(StatusCode::OK_200, res->status);
  9832. }
  9833. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9834. // Use a site that will cause SSL verification failure due to self-signed cert
  9835. SSLClient cli("self-signed.badssl.com", 443);
  9836. cli.enable_server_certificate_verification(true);
  9837. auto res = cli.Get("/");
  9838. ASSERT_TRUE(!res);
  9839. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9840. // Verify backend error is captured for SSLServerVerification
  9841. // This occurs when certificate verification fails
  9842. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9843. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9844. EXPECT_NE(0UL, res.ssl_backend_error());
  9845. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9846. // For OpenSSL, ssl_error is 0 for verification errors
  9847. EXPECT_EQ(0, res.ssl_error());
  9848. #if !defined(_WIN32) || \
  9849. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9850. // On non-Windows or when Windows Schannel is disabled, the error comes
  9851. // from OpenSSL's verification
  9852. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9853. res.ssl_backend_error());
  9854. #endif
  9855. #endif
  9856. }
  9857. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9858. // Use a site where hostname doesn't match the certificate
  9859. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9860. SSLClient cli("wrong.host.badssl.com", 443);
  9861. cli.enable_server_certificate_verification(true);
  9862. cli.enable_server_hostname_verification(true);
  9863. auto res = cli.Get("/");
  9864. ASSERT_TRUE(!res);
  9865. // The error type depends on when hostname verification occurs:
  9866. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9867. // - Mbed TLS: SSLServerVerification (during handshake)
  9868. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9869. res.error() == Error::SSLServerVerification);
  9870. // Verify backend error is captured for hostname verification failure
  9871. EXPECT_NE(0UL, res.ssl_backend_error());
  9872. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9873. // For OpenSSL, ssl_error is 0 for verification errors
  9874. EXPECT_EQ(0, res.ssl_error());
  9875. #if !defined(_WIN32) || \
  9876. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9877. // On non-Windows or when Windows Schannel is disabled, the error comes
  9878. // from OpenSSL's hostname verification
  9879. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9880. res.ssl_backend_error());
  9881. #endif
  9882. #endif
  9883. }
  9884. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9885. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9886. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9887. SSLClient cli("www.google.com", 443);
  9888. cli.enable_server_certificate_verification(true);
  9889. auto res = cli.Get("/");
  9890. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9891. }
  9892. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9893. SSLClient cli("www.google.com", 443);
  9894. cli.enable_server_certificate_verification(true);
  9895. cli.enable_windows_certificate_verification(false);
  9896. auto res = cli.Get("/");
  9897. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9898. }
  9899. #endif
  9900. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9901. Client cli("https://google.com");
  9902. auto res = cli.Get("/");
  9903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9904. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9905. }
  9906. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9907. SSLClient cli("google.com");
  9908. cli.set_ca_cert_path(CA_CERT_FILE);
  9909. auto res = cli.Get("/");
  9910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9911. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9912. }
  9913. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9914. SSLClient cli("google.com");
  9915. cli.enable_server_certificate_verification(true);
  9916. cli.set_ca_cert_path("hello");
  9917. auto res = cli.Get("/");
  9918. ASSERT_TRUE(!res);
  9919. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9920. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9921. // should be set
  9922. EXPECT_EQ(0, res.ssl_error());
  9923. // Verify backend error is captured for SSLLoadingCerts
  9924. // This error occurs when loading CA certificates fails
  9925. EXPECT_NE(0UL, res.ssl_backend_error());
  9926. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9927. // OpenSSL specific error codes:
  9928. // > openssl errstr 0x80000002
  9929. // error:80000002:system library::No such file or directory
  9930. // > openssl errstr 0xA000126
  9931. // error:0A000126:SSL routines::unexpected eof while reading
  9932. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9933. res.ssl_backend_error() == 0xA000126);
  9934. #endif
  9935. }
  9936. TEST(SSLClientTest, ServerCertificateVerification4) {
  9937. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9938. ASSERT_TRUE(svr.is_valid());
  9939. svr.Get("/test", [&](const Request &, Response &res) {
  9940. res.set_content("test", "text/plain");
  9941. svr.stop();
  9942. ASSERT_TRUE(true);
  9943. });
  9944. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9945. auto se = detail::scope_exit([&] {
  9946. t.join();
  9947. ASSERT_FALSE(svr.is_running());
  9948. });
  9949. svr.wait_until_ready();
  9950. SSLClient cli("127.0.0.1", PORT);
  9951. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9952. cli.enable_server_certificate_verification(true);
  9953. cli.set_connection_timeout(30);
  9954. auto res = cli.Get("/test");
  9955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9956. ASSERT_EQ(StatusCode::OK_200, res->status);
  9957. }
  9958. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9959. std::string cert;
  9960. read_file(CA_CERT_FILE, cert);
  9961. SSLClient cli("google.com");
  9962. cli.load_ca_cert_store(cert.data(), cert.size());
  9963. const auto res = cli.Get("/");
  9964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9965. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9966. }
  9967. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9968. // clang-format off
  9969. static constexpr char cert[] =
  9970. "GlobalSign Root CA\n"
  9971. "==================\n"
  9972. "-----BEGIN CERTIFICATE-----\n"
  9973. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9974. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9975. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9976. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9977. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9978. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9979. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9980. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9981. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9982. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9983. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9984. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9985. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9986. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9987. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9988. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9989. "-----END CERTIFICATE-----\n";
  9990. // clang-format on
  9991. SSLClient cli("google.com");
  9992. cli.load_ca_cert_store(cert, sizeof(cert));
  9993. const auto res = cli.Get("/");
  9994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9995. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9996. }
  9997. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9998. SSLClient cli("www.youtube.com");
  9999. cli.set_ca_cert_path(CA_CERT_FILE);
  10000. cli.enable_server_certificate_verification(true);
  10001. cli.set_follow_location(true);
  10002. auto res = cli.Get("/");
  10003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10004. ASSERT_EQ(StatusCode::OK_200, res->status);
  10005. }
  10006. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10007. SSLClient cli("wWw.YouTube.Com");
  10008. cli.set_ca_cert_path(CA_CERT_FILE);
  10009. cli.enable_server_certificate_verification(true);
  10010. cli.enable_server_hostname_verification(true);
  10011. cli.set_follow_location(true);
  10012. auto res = cli.Get("/");
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. ASSERT_EQ(StatusCode::OK_200, res->status);
  10015. }
  10016. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10017. SSLClient cli("gOoGlE.COm");
  10018. cli.enable_server_certificate_verification(true);
  10019. cli.enable_server_hostname_verification(true);
  10020. cli.set_follow_location(true);
  10021. auto res = cli.Get("/");
  10022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10023. ASSERT_EQ(StatusCode::OK_200, res->status);
  10024. }
  10025. TEST(SSLClientTest, Issue2004_Online) {
  10026. Client client("https://google.com");
  10027. client.set_follow_location(true);
  10028. auto res = client.Get("/");
  10029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10030. ASSERT_EQ(StatusCode::OK_200, res->status);
  10031. auto body = res->body;
  10032. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10033. }
  10034. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10035. // Create SSLClient with invalid cert/key to make is_valid() return false
  10036. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10037. "nonexistent_key.pem");
  10038. // is_valid() should be false due to cert loading failure
  10039. ASSERT_FALSE(cli.is_valid());
  10040. auto res = cli.Get("/");
  10041. ASSERT_FALSE(res);
  10042. EXPECT_EQ(Error::SSLConnection, res.error());
  10043. }
  10044. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10045. // Test for Issue #2251: SSL error not properly reported when client cert
  10046. // and key paths are swapped or mismatched
  10047. // This simulates the scenario where user accidentally swaps the cert and key
  10048. // files
  10049. // Using client cert file as private key and vice versa (completely wrong)
  10050. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10051. // Should fail validation due to cert/key mismatch
  10052. ASSERT_FALSE(cli.is_valid());
  10053. // Attempt to make a request should fail with proper error
  10054. auto res = cli.Get("/");
  10055. ASSERT_FALSE(res);
  10056. EXPECT_EQ(Error::SSLConnection, res.error());
  10057. // SSL error should be recorded in the Result object (this is the key fix for
  10058. // Issue #2251)
  10059. auto backend_error = res.ssl_backend_error();
  10060. EXPECT_NE(0u, backend_error);
  10061. }
  10062. // Tests cert/key mismatch detection at the TLS context level
  10063. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10064. // Test that using mismatched cert/key causes connection failure.
  10065. // We verify this at the SSLClient level rather than through internal
  10066. // TLS API functions.
  10067. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10068. cli.enable_server_certificate_verification(false);
  10069. cli.set_connection_timeout(2);
  10070. // The mismatch should cause a connection or handshake error
  10071. auto res = cli.Get("/test");
  10072. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10073. // Either way, the request should fail
  10074. EXPECT_FALSE(res);
  10075. }
  10076. #endif
  10077. #if 0
  10078. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10079. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10080. ASSERT_TRUE(cli != nullptr);
  10081. cli->set_address_family(AF_INET6);
  10082. cli->set_interface("en0");
  10083. auto res = cli->Get("/get");
  10084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10085. ASSERT_EQ(StatusCode::OK_200, res->status);
  10086. }
  10087. #endif
  10088. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10089. #ifdef CPPHTTPLIB_SSL_ENABLED
  10090. void ClientCertPresent(
  10091. const std::string &client_cert_file,
  10092. const std::string &client_private_key_file,
  10093. const std::string &client_encrypted_private_key_pass = std::string()) {
  10094. using namespace httplib::tls;
  10095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10096. CLIENT_CA_CERT_DIR);
  10097. ASSERT_TRUE(svr.is_valid());
  10098. svr.Get("/test", [&](const Request &req, Response &res) {
  10099. res.set_content("test", "text/plain");
  10100. auto cert = req.peer_cert();
  10101. ASSERT_TRUE(static_cast<bool>(cert));
  10102. std::string common_name = cert.subject_cn();
  10103. EXPECT_EQ("Common Name", common_name);
  10104. });
  10105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10106. auto se = detail::scope_exit([&] {
  10107. svr.stop();
  10108. t.join();
  10109. ASSERT_FALSE(svr.is_running());
  10110. });
  10111. svr.wait_until_ready();
  10112. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10113. client_encrypted_private_key_pass);
  10114. cli.enable_server_certificate_verification(false);
  10115. cli.set_connection_timeout(30);
  10116. auto res = cli.Get("/test");
  10117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10118. ASSERT_EQ(StatusCode::OK_200, res->status);
  10119. }
  10120. TEST(SSLClientServerTest, ClientCertPresent) {
  10121. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10122. }
  10123. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10124. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10125. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10126. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10127. }
  10128. // PEM memory-based constructor tests (works with all TLS backends)
  10129. void PemMemoryClientCertPresent(
  10130. const std::string &client_cert_file,
  10131. const std::string &client_private_key_file,
  10132. const std::string &client_encrypted_private_key_pass = std::string()) {
  10133. // Read PEM files into memory
  10134. std::string server_cert_pem, server_key_pem;
  10135. std::string client_ca_pem;
  10136. std::string client_cert_pem, client_key_pem;
  10137. read_file(SERVER_CERT_FILE, server_cert_pem);
  10138. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10139. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10140. read_file(client_cert_file, client_cert_pem);
  10141. read_file(client_private_key_file, client_key_pem);
  10142. // Create server with PEM memory
  10143. SSLServer::PemMemory server_pem = {
  10144. server_cert_pem.c_str(),
  10145. server_cert_pem.size(),
  10146. server_key_pem.c_str(),
  10147. server_key_pem.size(),
  10148. client_ca_pem.c_str(),
  10149. client_ca_pem.size(),
  10150. nullptr // no password for server key
  10151. };
  10152. SSLServer svr(server_pem);
  10153. ASSERT_TRUE(svr.is_valid());
  10154. svr.Get("/test", [&](const Request &, Response &res) {
  10155. res.set_content("test", "text/plain");
  10156. });
  10157. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10158. auto se = detail::scope_exit([&] {
  10159. svr.stop();
  10160. t.join();
  10161. ASSERT_FALSE(svr.is_running());
  10162. });
  10163. svr.wait_until_ready();
  10164. // Create client with PEM memory
  10165. const char *password = client_encrypted_private_key_pass.empty()
  10166. ? nullptr
  10167. : client_encrypted_private_key_pass.c_str();
  10168. SSLClient::PemMemory client_pem = {
  10169. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10170. client_key_pem.size(), password};
  10171. SSLClient cli(HOST, PORT, client_pem);
  10172. cli.enable_server_certificate_verification(false);
  10173. cli.set_connection_timeout(30);
  10174. auto res = cli.Get("/test");
  10175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10176. ASSERT_EQ(StatusCode::OK_200, res->status);
  10177. }
  10178. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10179. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10180. }
  10181. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10182. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10183. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10184. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10185. }
  10186. TEST(SSLClientServerTest, ClientCertMissing) {
  10187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10188. CLIENT_CA_CERT_DIR);
  10189. ASSERT_TRUE(svr.is_valid());
  10190. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10191. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10192. auto se = detail::scope_exit([&] {
  10193. svr.stop();
  10194. t.join();
  10195. ASSERT_FALSE(svr.is_running());
  10196. });
  10197. svr.wait_until_ready();
  10198. SSLClient cli(HOST, PORT);
  10199. cli.set_connection_timeout(30);
  10200. auto res = cli.Get("/test");
  10201. ASSERT_TRUE(!res);
  10202. // When client cert is missing and server requires it, connection fails
  10203. // Error type depends on backend implementation
  10204. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10205. res.error() == Error::SSLConnection);
  10206. // Verify backend error is captured
  10207. // Note: This test may have different error codes depending on the exact
  10208. // verification failure
  10209. EXPECT_NE(0UL, res.ssl_backend_error());
  10210. }
  10211. TEST(SSLClientServerTest, TrustDirOptional) {
  10212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10213. ASSERT_TRUE(svr.is_valid());
  10214. svr.Get("/test", [&](const Request &, Response &res) {
  10215. res.set_content("test", "text/plain");
  10216. });
  10217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10218. auto se = detail::scope_exit([&] {
  10219. svr.stop();
  10220. t.join();
  10221. ASSERT_FALSE(svr.is_running());
  10222. });
  10223. svr.wait_until_ready();
  10224. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10225. cli.enable_server_certificate_verification(false);
  10226. cli.set_connection_timeout(30);
  10227. auto res = cli.Get("/test");
  10228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10229. ASSERT_EQ(StatusCode::OK_200, res->status);
  10230. }
  10231. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10232. class NoListenSSLServer : public SSLServer {
  10233. public:
  10234. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10235. const char *client_ca_cert_file_path,
  10236. const char *client_ca_cert_dir_path = nullptr)
  10237. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10238. client_ca_cert_dir_path),
  10239. stop_(false) {}
  10240. std::atomic_bool stop_;
  10241. private:
  10242. bool process_and_close_socket(socket_t /*sock*/) override {
  10243. // Don't create SSL context
  10244. while (!stop_.load()) {
  10245. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10246. }
  10247. return true;
  10248. }
  10249. };
  10250. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10251. CLIENT_CA_CERT_FILE);
  10252. ASSERT_TRUE(svr.is_valid());
  10253. svr.Get("/test", [&](const Request &, Response &res) {
  10254. res.set_content("test", "text/plain");
  10255. });
  10256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10257. auto se = detail::scope_exit([&] {
  10258. svr.stop_ = true;
  10259. svr.stop();
  10260. t.join();
  10261. ASSERT_FALSE(svr.is_running());
  10262. });
  10263. svr.wait_until_ready();
  10264. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10265. cli.enable_server_certificate_verification(false);
  10266. cli.set_connection_timeout(1);
  10267. auto res = cli.Get("/test");
  10268. ASSERT_TRUE(!res);
  10269. EXPECT_EQ(Error::SSLConnection, res.error());
  10270. // Timeout results in WantRead error code (maps to backend-specific value)
  10271. EXPECT_NE(0, res.ssl_error());
  10272. }
  10273. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10274. // Test SSLServer with client certificate verification using the standard
  10275. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10277. CLIENT_CA_CERT_DIR);
  10278. ASSERT_TRUE(svr.is_valid());
  10279. svr.Get("/test", [&](const Request &req, Response &res) {
  10280. res.set_content("test", "text/plain");
  10281. auto cert = req.peer_cert();
  10282. ASSERT_TRUE(static_cast<bool>(cert));
  10283. auto common_name = cert.subject_cn();
  10284. EXPECT_EQ("Common Name", common_name);
  10285. });
  10286. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10287. auto se = detail::scope_exit([&] {
  10288. svr.stop();
  10289. t.join();
  10290. ASSERT_FALSE(svr.is_running());
  10291. });
  10292. svr.wait_until_ready();
  10293. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10294. cli.enable_server_certificate_verification(false);
  10295. cli.set_connection_timeout(30);
  10296. auto res = cli.Get("/test");
  10297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10298. ASSERT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10301. // Verifies that wildcard matching and exact matching work consistently
  10302. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10303. using namespace httplib::tls;
  10304. // We need a running server to test against
  10305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10306. ASSERT_TRUE(svr.is_valid());
  10307. svr.Get("/test", [](const Request &, Response &res) {
  10308. res.set_content("ok", "text/plain");
  10309. });
  10310. thread t([&]() { svr.listen(HOST, PORT); });
  10311. auto se = detail::scope_exit([&] {
  10312. svr.stop();
  10313. t.join();
  10314. });
  10315. svr.wait_until_ready();
  10316. bool verify_callback_called = false;
  10317. bool verify_result_wrong = false;
  10318. SSLClient cli(HOST, PORT);
  10319. cli.enable_server_certificate_verification(true);
  10320. cli.set_ca_cert_path(CA_CERT_FILE);
  10321. cli.set_connection_timeout(5);
  10322. // Note: Test certificate has CN="Common Name", not "localhost"
  10323. bool verify_result_cn = false;
  10324. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10325. verify_callback_called = true;
  10326. if (!ctx.cert) return false;
  10327. // Test 1: "Common Name" should match (our test server cert CN)
  10328. verify_result_cn = ctx.check_hostname("Common Name");
  10329. // Test 2: wrong hostname should not match
  10330. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10331. return true; // Accept for the purpose of this test
  10332. });
  10333. auto res = cli.Get("/test");
  10334. // The request may succeed or fail depending on cert configuration
  10335. // but the callback should have been called
  10336. ASSERT_TRUE(verify_callback_called)
  10337. << "Verify callback should have been called";
  10338. // CN="Common Name" should match our test certificate
  10339. //
  10340. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10341. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10342. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10343. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10344. // <openssl/base.h>, which is included transitively when
  10345. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10346. #if defined(OPENSSL_IS_BORINGSSL)
  10347. EXPECT_FALSE(verify_result_cn)
  10348. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10349. #else
  10350. EXPECT_TRUE(verify_result_cn)
  10351. << "verify_hostname should match 'Common Name' (certificate CN)";
  10352. #endif
  10353. // Wrong hostname should not match
  10354. EXPECT_FALSE(verify_result_wrong)
  10355. << "verify_hostname should not match 'wronghost.example.com'";
  10356. }
  10357. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10358. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10359. // X509_check_ip behavior and must hold for every backend.
  10360. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10361. using namespace httplib::tls;
  10362. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10363. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10364. ASSERT_TRUE(svr.is_valid());
  10365. svr.Get("/test", [](const Request &, Response &res) {
  10366. res.set_content("ok", "text/plain");
  10367. });
  10368. thread t([&]() { svr.listen(HOST, PORT); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. t.join();
  10372. });
  10373. svr.wait_until_ready();
  10374. bool verify_callback_called = false;
  10375. bool ip_matched_via_cn = true;
  10376. SSLClient cli(HOST, PORT);
  10377. cli.enable_server_certificate_verification(true);
  10378. cli.set_ca_cert_path(CA_CERT_FILE);
  10379. cli.set_connection_timeout(5);
  10380. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10381. verify_callback_called = true;
  10382. if (!ctx.cert) return false;
  10383. // The IP appears only in the CN, so it must NOT be accepted.
  10384. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10385. return true; // Accept for the purpose of this test
  10386. });
  10387. cli.Get("/test");
  10388. ASSERT_TRUE(verify_callback_called)
  10389. << "Verify callback should have been called";
  10390. EXPECT_FALSE(ip_matched_via_cn)
  10391. << "An IP host must not be authenticated via the certificate CN";
  10392. }
  10393. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10394. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10395. using namespace httplib::tls;
  10396. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10397. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10398. ASSERT_TRUE(svr.is_valid());
  10399. svr.Get("/test", [](const Request &, Response &res) {
  10400. res.set_content("ok", "text/plain");
  10401. });
  10402. thread t([&]() { svr.listen(HOST, PORT); });
  10403. auto se = detail::scope_exit([&] {
  10404. svr.stop();
  10405. t.join();
  10406. });
  10407. svr.wait_until_ready();
  10408. bool verify_callback_called = false;
  10409. bool san_matched = false;
  10410. bool wrong_ipv6_matched = true;
  10411. bool cn_ipv6_matched = true;
  10412. SSLClient cli(HOST, PORT);
  10413. cli.enable_server_certificate_verification(true);
  10414. cli.set_ca_cert_path(CA_CERT_FILE);
  10415. cli.set_connection_timeout(5);
  10416. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10417. verify_callback_called = true;
  10418. if (!ctx.cert) return false;
  10419. // Matches the IPv6 iPAddress SAN.
  10420. san_matched = ctx.check_hostname("2001:db8::1");
  10421. // A different IPv6 address must not match.
  10422. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10423. // "::1" lives only in the CN, so it must not be accepted.
  10424. cn_ipv6_matched = ctx.check_hostname("::1");
  10425. return true; // Accept for the purpose of this test
  10426. });
  10427. cli.Get("/test");
  10428. ASSERT_TRUE(verify_callback_called)
  10429. << "Verify callback should have been called";
  10430. EXPECT_TRUE(san_matched)
  10431. << "verify_hostname should match an IPv6 iPAddress SAN";
  10432. EXPECT_FALSE(wrong_ipv6_matched)
  10433. << "verify_hostname should not match a non-matching IPv6 address";
  10434. EXPECT_FALSE(cn_ipv6_matched)
  10435. << "An IPv6 host must not be authenticated via the certificate CN";
  10436. }
  10437. #endif
  10438. // mbedTLS-specific callback constructor test
  10439. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10440. #ifdef CPPHTTPLIB_SSL_ENABLED
  10441. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10443. ASSERT_TRUE(svr.is_valid());
  10444. // Set up a handler to verify client certificate is present
  10445. bool client_cert_verified = false;
  10446. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10447. // Verify that client certificate was provided
  10448. client_cert_verified = true;
  10449. res.set_content("success", "text/plain");
  10450. });
  10451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10452. auto se = detail::scope_exit([&] {
  10453. svr.stop();
  10454. t.join();
  10455. ASSERT_FALSE(svr.is_running());
  10456. });
  10457. svr.wait_until_ready();
  10458. // Client with certificate
  10459. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10460. cli.enable_server_certificate_verification(false);
  10461. cli.set_connection_timeout(30);
  10462. auto res = cli.Get("/test");
  10463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10464. ASSERT_EQ(StatusCode::OK_200, res->status);
  10465. ASSERT_TRUE(client_cert_verified);
  10466. EXPECT_EQ("success", res->body);
  10467. }
  10468. #endif
  10469. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10470. // backends
  10471. #ifdef CPPHTTPLIB_SSL_ENABLED
  10472. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10473. using namespace httplib::tls;
  10474. // Test that when client CA cert file is provided,
  10475. // the server properly requests and validates client certificates
  10476. // Create a server with client authentication
  10477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10478. ASSERT_TRUE(svr.is_valid());
  10479. bool handler_called = false;
  10480. svr.Get("/test", [&](const Request &req, Response &res) {
  10481. handler_called = true;
  10482. // Verify that a client certificate was provided
  10483. auto cert = req.peer_cert();
  10484. ASSERT_TRUE(static_cast<bool>(cert));
  10485. // Get the issuer name
  10486. std::string issuer_str = cert.issuer_name();
  10487. ASSERT_FALSE(issuer_str.empty());
  10488. // The client certificate should be issued by our test CA
  10489. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10490. res.set_content("authenticated", "text/plain");
  10491. });
  10492. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10493. auto se = detail::scope_exit([&] {
  10494. svr.stop();
  10495. t.join();
  10496. ASSERT_FALSE(svr.is_running());
  10497. });
  10498. svr.wait_until_ready();
  10499. // Connect with a client certificate issued by the CA
  10500. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10501. cli.enable_server_certificate_verification(false);
  10502. cli.set_connection_timeout(30);
  10503. auto res = cli.Get("/test");
  10504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10505. ASSERT_EQ(StatusCode::OK_200, res->status);
  10506. ASSERT_TRUE(handler_called);
  10507. EXPECT_EQ("authenticated", res->body);
  10508. }
  10509. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10510. using namespace httplib::tls;
  10511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10512. ASSERT_TRUE(svr.is_valid());
  10513. svr.Get("/test", [](const Request &, Response &res) {
  10514. res.set_content("ok", "text/plain");
  10515. });
  10516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10517. auto se = detail::scope_exit([&] {
  10518. svr.stop();
  10519. t.join();
  10520. });
  10521. svr.wait_until_ready();
  10522. SSLClient cli(HOST, PORT);
  10523. cli.enable_server_certificate_verification(false);
  10524. cli.set_connection_timeout(30);
  10525. bool cert_checked = false;
  10526. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10527. if (ctx.cert) {
  10528. auto sans = ctx.sans();
  10529. // Test certificate may or may not have SANs - just verify the API
  10530. // works If SANs exist, verify the types are valid
  10531. for (const auto &san : sans) {
  10532. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10533. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10534. san.type == SanType::OTHER);
  10535. EXPECT_FALSE(san.value.empty());
  10536. }
  10537. cert_checked = true;
  10538. }
  10539. return true;
  10540. });
  10541. auto res = cli.Get("/test");
  10542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10543. EXPECT_TRUE(cert_checked);
  10544. }
  10545. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10546. using namespace httplib::tls;
  10547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10548. ASSERT_TRUE(svr.is_valid());
  10549. svr.Get("/test", [](const Request &, Response &res) {
  10550. res.set_content("ok", "text/plain");
  10551. });
  10552. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. t.join();
  10556. });
  10557. svr.wait_until_ready();
  10558. SSLClient cli(HOST, PORT);
  10559. cli.enable_server_certificate_verification(false);
  10560. cli.set_connection_timeout(30);
  10561. bool validity_checked = false;
  10562. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10563. if (ctx.cert) {
  10564. time_t not_before = 0, not_after = 0;
  10565. bool result = ctx.validity(not_before, not_after);
  10566. EXPECT_TRUE(result);
  10567. // Verify that not_before < now < not_after for a valid cert
  10568. time_t now = time(nullptr);
  10569. EXPECT_LT(not_before, now);
  10570. EXPECT_GT(not_after, now);
  10571. validity_checked = true;
  10572. }
  10573. return true;
  10574. });
  10575. auto res = cli.Get("/test");
  10576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10577. EXPECT_TRUE(validity_checked);
  10578. }
  10579. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10580. using namespace httplib::tls;
  10581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10582. ASSERT_TRUE(svr.is_valid());
  10583. svr.Get("/test", [](const Request &, Response &res) {
  10584. res.set_content("ok", "text/plain");
  10585. });
  10586. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. t.join();
  10590. });
  10591. svr.wait_until_ready();
  10592. SSLClient cli(HOST, PORT);
  10593. cli.enable_server_certificate_verification(false);
  10594. cli.set_connection_timeout(30);
  10595. bool serial_checked = false;
  10596. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10597. if (ctx.cert) {
  10598. std::string serial = ctx.serial();
  10599. EXPECT_FALSE(serial.empty());
  10600. // Serial should be a hex string
  10601. for (char c : serial) {
  10602. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10603. (c >= 'a' && c <= 'f'));
  10604. }
  10605. serial_checked = true;
  10606. }
  10607. return true;
  10608. });
  10609. auto res = cli.Get("/test");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_TRUE(serial_checked);
  10612. }
  10613. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10614. // Test 1: Valid CA file - no error should be recorded
  10615. {
  10616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10617. CLIENT_CA_CERT_FILE);
  10618. ASSERT_TRUE(svr.is_valid());
  10619. // With valid setup, last_ssl_error should be 0
  10620. EXPECT_EQ(0, svr.ssl_last_error());
  10621. }
  10622. // Test 2: Invalid CA file content
  10623. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10624. {
  10625. // Create a temporary file with completely invalid content
  10626. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10627. {
  10628. std::ofstream ofs(temp_invalid_ca);
  10629. ofs << "This is not a certificate file at all\n";
  10630. ofs << "Just plain text content\n";
  10631. }
  10632. // Create server with invalid CA file
  10633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10634. // Clean up temporary file
  10635. std::remove(temp_invalid_ca);
  10636. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10637. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10638. // Note: SSL_CTX_load_verify_locations typically fails first,
  10639. // but our error handling code path is still exercised
  10640. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10641. }
  10642. }
  10643. TEST(VerifyCallbackTest, VerifyContextFields) {
  10644. using namespace httplib::tls;
  10645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10646. ASSERT_TRUE(svr.is_valid());
  10647. svr.Get("/test", [](const Request &, Response &res) {
  10648. res.set_content("ok", "text/plain");
  10649. });
  10650. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. });
  10655. svr.wait_until_ready();
  10656. SSLClient cli(HOST, PORT);
  10657. cli.enable_server_certificate_verification(false);
  10658. cli.set_connection_timeout(30);
  10659. int callback_count = 0;
  10660. bool saw_leaf_cert = false;
  10661. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10662. if (ctx.cert) {
  10663. callback_count++;
  10664. // We should see at least one certificate (the leaf)
  10665. std::string cn = ctx.subject_cn();
  10666. if (!cn.empty()) { saw_leaf_cert = true; }
  10667. // Verify context fields are populated
  10668. EXPECT_NE(ctx.session, nullptr);
  10669. EXPECT_GE(ctx.depth, 0);
  10670. }
  10671. return true;
  10672. });
  10673. auto res = cli.Get("/test");
  10674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10675. EXPECT_GT(callback_count, 0);
  10676. EXPECT_TRUE(saw_leaf_cert);
  10677. }
  10678. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10679. using httplib::tls::TlsError;
  10680. // Test that verify_error_to_string returns empty for success
  10681. std::string success_str = TlsError::verify_error_to_string(0);
  10682. EXPECT_TRUE(success_str.empty());
  10683. // Test that verify_error_to_string returns non-empty for error codes
  10684. // Using a common error code (certificate expired)
  10685. std::string error_str =
  10686. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10687. EXPECT_FALSE(error_str.empty());
  10688. }
  10689. TEST(SessionVerifierTest, CertificateAccepted) {
  10690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10691. ASSERT_TRUE(svr.is_valid());
  10692. svr.Get("/test", [](const Request &, Response &res) {
  10693. res.set_content("ok", "text/plain");
  10694. });
  10695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10696. auto se = detail::scope_exit([&] {
  10697. svr.stop();
  10698. t.join();
  10699. });
  10700. svr.wait_until_ready();
  10701. SSLClient cli(HOST, PORT);
  10702. cli.enable_server_certificate_verification(false);
  10703. cli.set_connection_timeout(30);
  10704. bool callback_called = false;
  10705. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10706. EXPECT_NE(session, nullptr);
  10707. callback_called = true;
  10708. return SSLVerifierResponse::CertificateAccepted;
  10709. });
  10710. auto res = cli.Get("/test");
  10711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10712. EXPECT_EQ(200, res->status);
  10713. EXPECT_TRUE(callback_called);
  10714. }
  10715. TEST(SessionVerifierTest, CertificateRejected) {
  10716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10717. ASSERT_TRUE(svr.is_valid());
  10718. svr.Get("/test", [](const Request &, Response &res) {
  10719. res.set_content("ok", "text/plain");
  10720. });
  10721. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10722. auto se = detail::scope_exit([&] {
  10723. svr.stop();
  10724. t.join();
  10725. });
  10726. svr.wait_until_ready();
  10727. SSLClient cli(HOST, PORT);
  10728. cli.enable_server_certificate_verification(false);
  10729. cli.set_connection_timeout(30);
  10730. bool callback_called = false;
  10731. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10732. EXPECT_NE(session, nullptr);
  10733. callback_called = true;
  10734. return SSLVerifierResponse::CertificateRejected;
  10735. });
  10736. auto res = cli.Get("/test");
  10737. EXPECT_FALSE(res);
  10738. EXPECT_TRUE(callback_called);
  10739. }
  10740. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10742. ASSERT_TRUE(svr.is_valid());
  10743. svr.Get("/test", [](const Request &, Response &res) {
  10744. res.set_content("ok", "text/plain");
  10745. });
  10746. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. t.join();
  10750. });
  10751. svr.wait_until_ready();
  10752. // NoDecisionMade with verification disabled should succeed (no default check)
  10753. SSLClient cli(HOST, PORT);
  10754. cli.enable_server_certificate_verification(false);
  10755. cli.set_connection_timeout(30);
  10756. bool callback_called = false;
  10757. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10758. EXPECT_NE(session, nullptr);
  10759. callback_called = true;
  10760. return SSLVerifierResponse::NoDecisionMade;
  10761. });
  10762. auto res = cli.Get("/test");
  10763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10764. EXPECT_EQ(200, res->status);
  10765. EXPECT_TRUE(callback_called);
  10766. }
  10767. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10769. ASSERT_TRUE(svr.is_valid());
  10770. svr.Get("/test", [](const Request &, Response &res) {
  10771. res.set_content("ok", "text/plain");
  10772. });
  10773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10774. auto se = detail::scope_exit([&] {
  10775. svr.stop();
  10776. t.join();
  10777. });
  10778. svr.wait_until_ready();
  10779. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10780. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10781. // so we only check that the request fails, not whether the callback was
  10782. // called.
  10783. SSLClient cli(HOST, PORT);
  10784. cli.enable_server_certificate_verification(true);
  10785. cli.set_connection_timeout(30);
  10786. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10787. EXPECT_NE(session, nullptr);
  10788. return SSLVerifierResponse::NoDecisionMade;
  10789. });
  10790. auto res = cli.Get("/test");
  10791. EXPECT_FALSE(res);
  10792. }
  10793. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10794. // Test SSL server using PemMemory constructor with client CA certificates
  10795. // Read PEM files
  10796. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10797. read_file(SERVER_CERT_FILE, server_cert_pem);
  10798. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10799. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10800. // Create SSLServer with PemMemory constructor including client CA
  10801. SSLServer::PemMemory server_pem = {
  10802. server_cert_pem.c_str(),
  10803. server_cert_pem.size(),
  10804. server_key_pem.c_str(),
  10805. server_key_pem.size(),
  10806. client_ca_pem.c_str(),
  10807. client_ca_pem.size(),
  10808. nullptr // no password for server key
  10809. };
  10810. SSLServer svr(server_pem);
  10811. ASSERT_TRUE(svr.is_valid());
  10812. // No SSL error should be recorded for valid setup
  10813. EXPECT_EQ(0, svr.ssl_last_error());
  10814. // Set up server endpoints
  10815. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10816. res.set_content("ok", "text/plain");
  10817. });
  10818. // Start server in a thread
  10819. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10820. svr.wait_until_ready();
  10821. // Connect with client certificate (using constructor with paths)
  10822. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10823. cli.enable_server_certificate_verification(false);
  10824. auto res = cli.Get("/test-pem-ca");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. EXPECT_EQ(200, res->status);
  10827. EXPECT_EQ("ok", res->body);
  10828. svr.stop();
  10829. server_thread.join();
  10830. }
  10831. #endif
  10832. #ifdef _WIN32
  10833. TEST(CleanupTest, WSACleanup) {
  10834. int ret = WSACleanup();
  10835. ASSERT_EQ(0, ret);
  10836. }
  10837. #endif
  10838. #ifndef CPPHTTPLIB_SSL_ENABLED
  10839. TEST(NoSSLSupport, SimpleInterface) {
  10840. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10841. }
  10842. #endif
  10843. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10844. TEST(InvalidScheme, SimpleInterface) {
  10845. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10846. }
  10847. #endif
  10848. TEST(NoScheme, SimpleInterface) {
  10849. Client cli("yahoo.com:80");
  10850. ASSERT_TRUE(cli.is_valid());
  10851. }
  10852. TEST(SendAPI, SimpleInterface_Online) {
  10853. Client cli("http://yahoo.com");
  10854. Request req;
  10855. req.method = "GET";
  10856. req.path = "/";
  10857. auto res = cli.send(req);
  10858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10859. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10860. }
  10861. TEST(SendAPI, WithParamsInRequest) {
  10862. Server svr;
  10863. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10864. EXPECT_TRUE(req.has_param("test"));
  10865. EXPECT_EQ("test_value", req.get_param_value("test"));
  10866. });
  10867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10868. auto se = detail::scope_exit([&] {
  10869. svr.stop();
  10870. t.join();
  10871. ASSERT_FALSE(svr.is_running());
  10872. });
  10873. svr.wait_until_ready();
  10874. Client cli(HOST, PORT);
  10875. {
  10876. Request req;
  10877. req.method = "GET";
  10878. req.path = "/";
  10879. req.params.emplace("test", "test_value");
  10880. auto res = cli.send(req);
  10881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10882. }
  10883. {
  10884. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10886. }
  10887. }
  10888. TEST(ClientImplMethods, GetSocketTest) {
  10889. httplib::Server svr;
  10890. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10891. res.status = StatusCode::OK_200;
  10892. });
  10893. auto port = svr.bind_to_any_port("127.0.0.1");
  10894. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10895. auto se = detail::scope_exit([&] {
  10896. svr.stop();
  10897. thread.join();
  10898. ASSERT_FALSE(svr.is_running());
  10899. });
  10900. svr.wait_until_ready();
  10901. {
  10902. httplib::Client cli("127.0.0.1", port);
  10903. cli.set_keep_alive(true);
  10904. // Use the behavior of cpp-httplib of opening the connection
  10905. // only when the first request happens. If that changes,
  10906. // this test would be obsolete.
  10907. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10908. // This also implicitly tests the server. But other tests would fail much
  10909. // earlier than this one to be considered.
  10910. auto res = cli.Get("/");
  10911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10912. EXPECT_EQ(StatusCode::OK_200, res->status);
  10913. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10914. }
  10915. }
  10916. #ifdef CPPHTTPLIB_SSL_ENABLED
  10917. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10918. Client cli("http://yahoo.com");
  10919. auto res = cli.Get("/");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10922. cli.set_follow_location(true);
  10923. res = cli.Get("/");
  10924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10925. EXPECT_EQ(StatusCode::OK_200, res->status);
  10926. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10927. }
  10928. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10929. Client cli("https://yahoo.com");
  10930. auto res = cli.Get("/");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10933. cli.set_follow_location(true);
  10934. res = cli.Get("/");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::OK_200, res->status);
  10937. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10938. }
  10939. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10940. Client cli("https://yahoo.com");
  10941. auto res = cli.Get("/");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. ASSERT_FALSE(!res);
  10944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10945. ASSERT_FALSE(res == nullptr);
  10946. ASSERT_TRUE(res != nullptr);
  10947. EXPECT_EQ(Error::Success, res.error());
  10948. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10949. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10950. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10951. cli.set_follow_location(true);
  10952. res = cli.Get("/");
  10953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10954. EXPECT_EQ(Error::Success, res.error());
  10955. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10956. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10957. EXPECT_EQ(StatusCode::OK_200, res->status);
  10958. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10959. }
  10960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10961. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10962. Client cli("https://cdnjs.cloudflare.com");
  10963. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10964. Headers{{"Accept-Encoding", "br"}});
  10965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10966. EXPECT_EQ(StatusCode::OK_200, res->status);
  10967. EXPECT_EQ(287630U, res->body.size());
  10968. EXPECT_EQ("application/javascript; charset=utf-8",
  10969. res->get_header_value("Content-Type"));
  10970. }
  10971. #endif
  10972. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10973. #undef REDIR_HOST // Silence compiler warning
  10974. #define REDIR_HOST "https://httpbingo.org"
  10975. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10976. Client cli(REDIR_HOST);
  10977. cli.set_follow_location(true);
  10978. auto res =
  10979. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ(StatusCode::OK_200, res->status);
  10982. }
  10983. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10984. Client cli(REDIR_HOST);
  10985. cli.set_follow_location(true);
  10986. Params params;
  10987. params.emplace("url", "http://example.com");
  10988. params.emplace("status_code", "302");
  10989. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10991. EXPECT_EQ(StatusCode::OK_200, res->status);
  10992. }
  10993. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10994. Client cli(REDIR_HOST);
  10995. cli.set_follow_location(true);
  10996. Params params;
  10997. params.emplace("url", "http://example.com");
  10998. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. EXPECT_EQ(StatusCode::OK_200, res->status);
  11001. }
  11002. TEST(HttpToHttpsRedirectTest, CertFile) {
  11003. auto ssl_port = PORT + 1;
  11004. Server svr;
  11005. ASSERT_TRUE(svr.is_valid());
  11006. svr.Get("/index", [&](const Request &, Response &res) {
  11007. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11008. "/index");
  11009. svr.stop();
  11010. });
  11011. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11012. ASSERT_TRUE(ssl_svr.is_valid());
  11013. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11014. res.set_content("test", "text/plain");
  11015. ssl_svr.stop();
  11016. });
  11017. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11018. thread t2 =
  11019. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11020. auto se = detail::scope_exit([&] {
  11021. t2.join();
  11022. t.join();
  11023. ASSERT_FALSE(svr.is_running());
  11024. });
  11025. svr.wait_until_ready();
  11026. ssl_svr.wait_until_ready();
  11027. Client cli("127.0.0.1", PORT);
  11028. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11029. cli.enable_server_certificate_verification(true);
  11030. cli.set_follow_location(true);
  11031. cli.set_connection_timeout(30);
  11032. auto res = cli.Get("/index");
  11033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11034. ASSERT_EQ(StatusCode::OK_200, res->status);
  11035. }
  11036. TEST(SSLClientRedirectTest, CertFile) {
  11037. auto ssl_port = PORT + 1;
  11038. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11039. ASSERT_TRUE(ssl_svr1.is_valid());
  11040. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11041. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11042. "/index");
  11043. ssl_svr1.stop();
  11044. });
  11045. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11046. ASSERT_TRUE(ssl_svr2.is_valid());
  11047. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11048. res.set_content("test", "text/plain");
  11049. ssl_svr2.stop();
  11050. });
  11051. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11052. thread t2 =
  11053. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11054. auto se = detail::scope_exit([&] {
  11055. t2.join();
  11056. t.join();
  11057. ASSERT_FALSE(ssl_svr1.is_running());
  11058. });
  11059. ssl_svr1.wait_until_ready();
  11060. ssl_svr2.wait_until_ready();
  11061. SSLClient cli("127.0.0.1", PORT);
  11062. std::string cert;
  11063. read_file(SERVER_CERT2_FILE, cert);
  11064. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11065. cli.enable_server_certificate_verification(true);
  11066. cli.set_follow_location(true);
  11067. cli.set_connection_timeout(30);
  11068. auto res = cli.Get("/index");
  11069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11070. ASSERT_EQ(StatusCode::OK_200, res->status);
  11071. }
  11072. #endif
  11073. #ifdef CPPHTTPLIB_SSL_ENABLED
  11074. // Test that set_ca_cert_store() skips system certs (consistent with
  11075. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11076. // should be trusted - system certs should NOT be loaded.
  11077. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11078. // Load a specific cert that is NOT a system CA cert
  11079. std::string cert;
  11080. read_file(SERVER_CERT2_FILE, cert);
  11081. SSLClient cli("google.com");
  11082. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11083. cli.enable_server_certificate_verification(true);
  11084. // This should FAIL because:
  11085. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11086. // 2. System certs should NOT be loaded when custom store is set
  11087. // If system certs WERE loaded, this would succeed
  11088. auto res = cli.Get("/");
  11089. ASSERT_FALSE(res);
  11090. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11091. }
  11092. // Same as above, but through the native store handle path. Regression test:
  11093. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11094. // merged system certs into the user-provided store.
  11095. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11096. std::string cert;
  11097. read_file(SERVER_CERT2_FILE, cert);
  11098. SSLClient cli("google.com");
  11099. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11100. cli.enable_server_certificate_verification(true);
  11101. auto res = cli.Get("/");
  11102. ASSERT_FALSE(res);
  11103. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11104. }
  11105. // A custom store set via the native handle must still verify a server whose
  11106. // cert it does contain.
  11107. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11108. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11109. ASSERT_TRUE(svr.is_valid());
  11110. svr.Get("/test", [&](const Request &, Response &res) {
  11111. res.set_content("test", "text/plain");
  11112. });
  11113. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11114. auto se = detail::scope_exit([&] {
  11115. svr.stop();
  11116. t.join();
  11117. ASSERT_FALSE(svr.is_running());
  11118. });
  11119. svr.wait_until_ready();
  11120. SSLClient cli("127.0.0.1", PORT);
  11121. std::string cert;
  11122. read_file(SERVER_CERT2_FILE, cert);
  11123. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11124. cli.enable_server_certificate_verification(true);
  11125. cli.set_connection_timeout(30);
  11126. auto res = cli.Get("/test");
  11127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11128. ASSERT_EQ(StatusCode::OK_200, res->status);
  11129. }
  11130. // CA certs loaded through the universal Client must be transferred to the
  11131. // client created internally for following an HTTPS redirect. Regression test:
  11132. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11133. // the CA data for redirect transfer.
  11134. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11135. auto ssl_port = PORT + 1;
  11136. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11137. ASSERT_TRUE(ssl_svr1.is_valid());
  11138. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11139. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11140. "/index");
  11141. });
  11142. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11143. ASSERT_TRUE(ssl_svr2.is_valid());
  11144. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11145. res.set_content("test", "text/plain");
  11146. });
  11147. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11148. thread t2 =
  11149. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11150. auto se = detail::scope_exit([&] {
  11151. ssl_svr2.stop();
  11152. ssl_svr1.stop();
  11153. t2.join();
  11154. t.join();
  11155. ASSERT_FALSE(ssl_svr1.is_running());
  11156. });
  11157. ssl_svr1.wait_until_ready();
  11158. ssl_svr2.wait_until_ready();
  11159. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11160. std::string cert;
  11161. read_file(SERVER_CERT2_FILE, cert);
  11162. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11163. cli.enable_server_certificate_verification(true);
  11164. cli.set_follow_location(true);
  11165. cli.set_connection_timeout(30);
  11166. auto res = cli.Get("/index");
  11167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11168. ASSERT_EQ(StatusCode::OK_200, res->status);
  11169. }
  11170. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11171. // so a host signed by a system CA verifies even though a custom CA is set
  11172. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11173. std::string cert;
  11174. read_file(SERVER_CERT2_FILE, cert);
  11175. SSLClient cli("google.com");
  11176. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11177. cli.enable_system_ca(true);
  11178. cli.enable_server_certificate_verification(true);
  11179. auto res = cli.Get("/");
  11180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11182. }
  11183. // The custom CA remains effective when combined with the system CA
  11184. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11185. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11186. ASSERT_TRUE(svr.is_valid());
  11187. svr.Get("/test", [&](const Request &, Response &res) {
  11188. res.set_content("test", "text/plain");
  11189. });
  11190. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. t.join();
  11194. ASSERT_FALSE(svr.is_running());
  11195. });
  11196. svr.wait_until_ready();
  11197. SSLClient cli("127.0.0.1", PORT);
  11198. std::string cert;
  11199. read_file(SERVER_CERT2_FILE, cert);
  11200. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11201. cli.enable_system_ca(true);
  11202. cli.enable_server_certificate_verification(true);
  11203. cli.set_connection_timeout(30);
  11204. auto res = cli.Get("/test");
  11205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11206. ASSERT_EQ(StatusCode::OK_200, res->status);
  11207. }
  11208. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11209. // skip chain verification entirely (only the certificate identity was
  11210. // checked), so a server presenting an untrusted certificate with a matching
  11211. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11212. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11213. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11214. ASSERT_TRUE(svr.is_valid());
  11215. svr.Get("/test", [&](const Request &, Response &res) {
  11216. res.set_content("test", "text/plain");
  11217. });
  11218. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. t.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. SSLClient cli("127.0.0.1", PORT);
  11226. std::string cert;
  11227. // A trusted CA that did not sign the server certificate. The server cert
  11228. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11229. // this connection.
  11230. read_file(CLIENT_CA_CERT_FILE, cert);
  11231. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11232. cli.enable_server_certificate_verification(true);
  11233. cli.set_connection_timeout(30);
  11234. auto res = cli.Get("/test");
  11235. ASSERT_FALSE(res);
  11236. }
  11237. // enable_system_ca(false) prevents system CA loading entirely
  11238. TEST(SSLClientTest, DisableSystemCa_Online) {
  11239. SSLClient cli("google.com");
  11240. cli.enable_system_ca(false);
  11241. cli.enable_server_certificate_verification(true);
  11242. auto res = cli.Get("/");
  11243. ASSERT_FALSE(res);
  11244. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11245. // itself when the CA chain is empty
  11246. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11247. res.error() == Error::SSLConnection);
  11248. }
  11249. // The universal Client forwards enable_system_ca()
  11250. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11251. std::string cert;
  11252. read_file(SERVER_CERT2_FILE, cert);
  11253. Client cli("https://google.com");
  11254. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11255. cli.enable_system_ca(true);
  11256. cli.enable_server_certificate_verification(true);
  11257. auto res = cli.Get("/");
  11258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11259. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11260. }
  11261. // The system CA policy must carry over to the client created internally for
  11262. // following a cross-host HTTPS redirect
  11263. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11265. ASSERT_TRUE(svr.is_valid());
  11266. svr.Get("/index", [&](const Request &, Response &res) {
  11267. res.set_redirect("https://www.google.com/");
  11268. });
  11269. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11270. auto se = detail::scope_exit([&] {
  11271. svr.stop();
  11272. t.join();
  11273. ASSERT_FALSE(svr.is_running());
  11274. });
  11275. svr.wait_until_ready();
  11276. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11277. std::string cert;
  11278. read_file(SERVER_CERT2_FILE, cert);
  11279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11280. cli.enable_system_ca(true);
  11281. cli.enable_server_certificate_verification(true);
  11282. cli.set_follow_location(true);
  11283. cli.set_connection_timeout(30);
  11284. // Receiving any response proves the redirect client completed the TLS
  11285. // handshake with a system-CA-signed host
  11286. auto res = cli.Get("/index");
  11287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11288. }
  11289. TEST(MultipartFormDataTest, LargeData) {
  11290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11291. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11292. const ContentReader &content_reader) {
  11293. if (req.is_multipart_form_data()) {
  11294. std::vector<FormData> items;
  11295. content_reader(
  11296. [&](const FormData &file) {
  11297. items.push_back(file);
  11298. return true;
  11299. },
  11300. [&](const char *data, size_t data_length) {
  11301. items.back().content.append(data, data_length);
  11302. return true;
  11303. });
  11304. EXPECT_TRUE(std::string(items[0].name) == "document");
  11305. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11306. EXPECT_TRUE(items[0].filename == "2MB_data");
  11307. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11308. EXPECT_TRUE(items[1].name == "hello");
  11309. EXPECT_TRUE(items[1].content == "world");
  11310. EXPECT_TRUE(items[1].filename == "");
  11311. EXPECT_TRUE(items[1].content_type == "");
  11312. } else {
  11313. std::string body;
  11314. content_reader([&](const char *data, size_t data_length) {
  11315. body.append(data, data_length);
  11316. return true;
  11317. });
  11318. }
  11319. });
  11320. auto port = svr.bind_to_any_port(HOST);
  11321. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11322. auto se = detail::scope_exit([&] {
  11323. svr.stop();
  11324. t.join();
  11325. ASSERT_FALSE(svr.is_running());
  11326. });
  11327. svr.wait_until_ready();
  11328. {
  11329. std::string data(1024 * 1024 * 2, '.');
  11330. std::stringstream buffer;
  11331. buffer << data;
  11332. SSLClient cli(HOST, port);
  11333. cli.enable_server_certificate_verification(false);
  11334. UploadFormDataItems items{
  11335. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11336. {"hello", "world", "", ""},
  11337. };
  11338. auto res = cli.Post("/post", items);
  11339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11340. ASSERT_EQ(StatusCode::OK_200, res->status);
  11341. }
  11342. }
  11343. TEST(MultipartFormDataTest, DataProviderItems) {
  11344. std::random_device seed_gen;
  11345. std::mt19937 random(seed_gen());
  11346. std::string rand1;
  11347. rand1.resize(1000);
  11348. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11349. std::string rand2;
  11350. rand2.resize(3000);
  11351. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11353. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11354. const ContentReader &content_reader) {
  11355. ASSERT_FALSE(req.is_multipart_form_data());
  11356. std::string body;
  11357. content_reader([&](const char *data, size_t data_length) {
  11358. body.append(data, data_length);
  11359. return true;
  11360. });
  11361. EXPECT_EQ(body, "");
  11362. });
  11363. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11364. const ContentReader &content_reader) {
  11365. ASSERT_TRUE(req.is_multipart_form_data());
  11366. std::vector<FormData> items;
  11367. content_reader(
  11368. [&](const FormData &file) {
  11369. items.push_back(file);
  11370. return true;
  11371. },
  11372. [&](const char *data, size_t data_length) {
  11373. items.back().content.append(data, data_length);
  11374. return true;
  11375. });
  11376. ASSERT_TRUE(items.size() == 2);
  11377. EXPECT_EQ(std::string(items[0].name), "name1");
  11378. EXPECT_EQ(items[0].content, "Testing123");
  11379. EXPECT_EQ(items[0].filename, "filename1");
  11380. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11381. EXPECT_EQ(items[1].name, "name2");
  11382. EXPECT_EQ(items[1].content, "Testing456");
  11383. EXPECT_EQ(items[1].filename, "");
  11384. EXPECT_EQ(items[1].content_type, "");
  11385. });
  11386. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11387. const ContentReader &content_reader) {
  11388. ASSERT_TRUE(req.is_multipart_form_data());
  11389. std::vector<FormData> items;
  11390. content_reader(
  11391. [&](const FormData &file) {
  11392. items.push_back(file);
  11393. return true;
  11394. },
  11395. [&](const char *data, size_t data_length) {
  11396. items.back().content.append(data, data_length);
  11397. return true;
  11398. });
  11399. ASSERT_TRUE(items.size() == 2);
  11400. EXPECT_EQ(items[0].name, "name3");
  11401. EXPECT_EQ(items[0].content, rand1);
  11402. EXPECT_EQ(items[0].filename, "filename3");
  11403. EXPECT_EQ(items[0].content_type, "");
  11404. EXPECT_EQ(items[1].name, "name4");
  11405. EXPECT_EQ(items[1].content, rand2);
  11406. EXPECT_EQ(items[1].filename, "filename4");
  11407. EXPECT_EQ(items[1].content_type, "");
  11408. });
  11409. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11410. const ContentReader &content_reader) {
  11411. ASSERT_TRUE(req.is_multipart_form_data());
  11412. std::vector<FormData> items;
  11413. content_reader(
  11414. [&](const FormData &file) {
  11415. items.push_back(file);
  11416. return true;
  11417. },
  11418. [&](const char *data, size_t data_length) {
  11419. items.back().content.append(data, data_length);
  11420. return true;
  11421. });
  11422. ASSERT_TRUE(items.size() == 4);
  11423. EXPECT_EQ(std::string(items[0].name), "name1");
  11424. EXPECT_EQ(items[0].content, "Testing123");
  11425. EXPECT_EQ(items[0].filename, "filename1");
  11426. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11427. EXPECT_EQ(items[1].name, "name2");
  11428. EXPECT_EQ(items[1].content, "Testing456");
  11429. EXPECT_EQ(items[1].filename, "");
  11430. EXPECT_EQ(items[1].content_type, "");
  11431. EXPECT_EQ(items[2].name, "name3");
  11432. EXPECT_EQ(items[2].content, rand1);
  11433. EXPECT_EQ(items[2].filename, "filename3");
  11434. EXPECT_EQ(items[2].content_type, "");
  11435. EXPECT_EQ(items[3].name, "name4");
  11436. EXPECT_EQ(items[3].content, rand2);
  11437. EXPECT_EQ(items[3].filename, "filename4");
  11438. EXPECT_EQ(items[3].content_type, "");
  11439. });
  11440. auto port = svr.bind_to_any_port("localhost");
  11441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11442. auto se = detail::scope_exit([&] {
  11443. svr.stop();
  11444. t.join();
  11445. ASSERT_FALSE(svr.is_running());
  11446. });
  11447. svr.wait_until_ready();
  11448. {
  11449. SSLClient cli("localhost", port);
  11450. cli.enable_server_certificate_verification(false);
  11451. UploadFormDataItems items{
  11452. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11453. {"name2", "Testing456", "", ""}, // not a file
  11454. };
  11455. {
  11456. auto res = cli.Post("/post-none", {}, {}, {});
  11457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11458. ASSERT_EQ(StatusCode::OK_200, res->status);
  11459. }
  11460. FormDataProviderItems providers;
  11461. {
  11462. auto res =
  11463. cli.Post("/post-items", {}, items, providers); // empty providers
  11464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11465. ASSERT_EQ(StatusCode::OK_200, res->status);
  11466. }
  11467. providers.push_back({"name3",
  11468. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11469. // test the offset is given correctly at each step
  11470. if (!offset)
  11471. sink.os.write(rand1.data(), 30);
  11472. else if (offset == 30)
  11473. sink.os.write(rand1.data() + 30, 300);
  11474. else if (offset == 330)
  11475. sink.os.write(rand1.data() + 330, 670);
  11476. else if (offset == rand1.size())
  11477. sink.done();
  11478. return true;
  11479. },
  11480. "filename3",
  11481. {}});
  11482. providers.push_back({"name4",
  11483. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11484. // test the offset is given correctly at each step
  11485. if (!offset)
  11486. sink.os.write(rand2.data(), 2000);
  11487. else if (offset == 2000)
  11488. sink.os.write(rand2.data() + 2000, 1);
  11489. else if (offset == 2001)
  11490. sink.os.write(rand2.data() + 2001, 999);
  11491. else if (offset == rand2.size())
  11492. sink.done();
  11493. return true;
  11494. },
  11495. "filename4",
  11496. {}});
  11497. {
  11498. auto res = cli.Post("/post-providers", {}, {}, providers);
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. ASSERT_EQ(StatusCode::OK_200, res->status);
  11501. }
  11502. {
  11503. auto res = cli.Post("/post-both", {}, items, providers);
  11504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11505. ASSERT_EQ(StatusCode::OK_200, res->status);
  11506. }
  11507. }
  11508. }
  11509. TEST(MultipartFormDataTest, BadHeader) {
  11510. Server svr;
  11511. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11512. res.set_content("ok", "text/plain");
  11513. });
  11514. thread t = thread([&] { svr.listen(HOST, PORT); });
  11515. auto se = detail::scope_exit([&] {
  11516. svr.stop();
  11517. t.join();
  11518. ASSERT_FALSE(svr.is_running());
  11519. });
  11520. svr.wait_until_ready();
  11521. const std::string body =
  11522. "This is the preamble. It is to be ignored, though it\r\n"
  11523. "is a handy place for composition agents to include an\r\n"
  11524. "explanatory note to non-MIME conformant readers.\r\n"
  11525. "\r\n"
  11526. "\r\n"
  11527. "--simple boundary\r\n"
  11528. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11529. ": BAD...\r\n"
  11530. "\r\n"
  11531. "value1\r\n"
  11532. "--simple boundary\r\n"
  11533. "Content-Disposition: form-data; name=\"field2\"; "
  11534. "filename=\"example.txt\"\r\n"
  11535. "\r\n"
  11536. "value2\r\n"
  11537. "--simple boundary--\r\n"
  11538. "This is the epilogue. It is also to be ignored.\r\n";
  11539. std::string content_type =
  11540. R"(multipart/form-data; boundary="simple boundary")";
  11541. Client cli(HOST, PORT);
  11542. auto res = cli.Post("/post", body, content_type.c_str());
  11543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11544. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11545. }
  11546. TEST(MultipartFormDataTest, WithPreamble) {
  11547. Server svr;
  11548. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11549. res.set_content("ok", "text/plain");
  11550. });
  11551. thread t = thread([&] { svr.listen(HOST, PORT); });
  11552. auto se = detail::scope_exit([&] {
  11553. svr.stop();
  11554. t.join();
  11555. ASSERT_FALSE(svr.is_running());
  11556. });
  11557. svr.wait_until_ready();
  11558. const std::string body =
  11559. "This is the preamble. It is to be ignored, though it\r\n"
  11560. "is a handy place for composition agents to include an\r\n"
  11561. "explanatory note to non-MIME conformant readers.\r\n"
  11562. "\r\n"
  11563. "\r\n"
  11564. "--simple boundary\r\n"
  11565. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11566. "\r\n"
  11567. "value1\r\n"
  11568. "--simple boundary\r\n"
  11569. "Content-Disposition: form-data; name=\"field2\"; "
  11570. "filename=\"example.txt\"\r\n"
  11571. "\r\n"
  11572. "value2\r\n"
  11573. "--simple boundary--\r\n"
  11574. "This is the epilogue. It is also to be ignored.\r\n";
  11575. std::string content_type =
  11576. R"(multipart/form-data; boundary="simple boundary")";
  11577. Client cli(HOST, PORT);
  11578. auto res = cli.Post("/post", body, content_type.c_str());
  11579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11580. EXPECT_EQ(StatusCode::OK_200, res->status);
  11581. }
  11582. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11584. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11585. const ContentReader &content_reader) {
  11586. if (req.is_multipart_form_data()) {
  11587. std::vector<FormData> items;
  11588. content_reader(
  11589. [&](const FormData &file) {
  11590. items.push_back(file);
  11591. return true;
  11592. },
  11593. [&](const char *data, size_t data_length) {
  11594. items.back().content.append(data, data_length);
  11595. return true;
  11596. });
  11597. EXPECT_TRUE(std::string(items[0].name) == "document");
  11598. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11599. EXPECT_TRUE(items[0].filename == "2MB_data");
  11600. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11601. EXPECT_TRUE(items[1].name == "hello");
  11602. EXPECT_TRUE(items[1].content == "world");
  11603. EXPECT_TRUE(items[1].filename == "");
  11604. EXPECT_TRUE(items[1].content_type == "");
  11605. } else {
  11606. std::string body;
  11607. content_reader([&](const char *data, size_t data_length) {
  11608. body.append(data, data_length);
  11609. return true;
  11610. });
  11611. }
  11612. });
  11613. auto port = svr.bind_to_any_port("localhost");
  11614. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11615. auto se = detail::scope_exit([&] {
  11616. svr.stop();
  11617. t.join();
  11618. ASSERT_FALSE(svr.is_running());
  11619. });
  11620. svr.wait_until_ready();
  11621. {
  11622. std::string data(1024 * 1024 * 2, '.');
  11623. std::stringstream buffer;
  11624. buffer << data;
  11625. SSLClient cli("localhost", port);
  11626. cli.enable_server_certificate_verification(false);
  11627. UploadFormDataItems items{
  11628. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11629. {"hello", "world", "", ""},
  11630. };
  11631. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11633. ASSERT_EQ(StatusCode::OK_200, res->status);
  11634. }
  11635. }
  11636. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11637. std::string data(1024 * 1024 * 2, '&');
  11638. std::stringstream buffer;
  11639. buffer << data;
  11640. Client cli("https://localhost:8080");
  11641. UploadFormDataItems items{
  11642. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11643. {"hello", "world", "", ""},
  11644. };
  11645. for (const char &c : " \t\r\n") {
  11646. auto res =
  11647. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11648. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11649. ASSERT_FALSE(res);
  11650. }
  11651. }
  11652. TEST(MultipartFormDataTest, PutFormData) {
  11653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11654. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11655. const ContentReader &content_reader) {
  11656. if (req.is_multipart_form_data()) {
  11657. std::vector<FormData> items;
  11658. content_reader(
  11659. [&](const FormData &file) {
  11660. items.push_back(file);
  11661. return true;
  11662. },
  11663. [&](const char *data, size_t data_length) {
  11664. items.back().content.append(data, data_length);
  11665. return true;
  11666. });
  11667. EXPECT_TRUE(std::string(items[0].name) == "document");
  11668. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11669. EXPECT_TRUE(items[0].filename == "2MB_data");
  11670. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11671. EXPECT_TRUE(items[1].name == "hello");
  11672. EXPECT_TRUE(items[1].content == "world");
  11673. EXPECT_TRUE(items[1].filename == "");
  11674. EXPECT_TRUE(items[1].content_type == "");
  11675. } else {
  11676. std::string body;
  11677. content_reader([&](const char *data, size_t data_length) {
  11678. body.append(data, data_length);
  11679. return true;
  11680. });
  11681. }
  11682. });
  11683. auto port = svr.bind_to_any_port("localhost");
  11684. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11685. auto se = detail::scope_exit([&] {
  11686. svr.stop();
  11687. t.join();
  11688. ASSERT_FALSE(svr.is_running());
  11689. });
  11690. svr.wait_until_ready();
  11691. {
  11692. std::string data(1024 * 1024 * 2, '&');
  11693. std::stringstream buffer;
  11694. buffer << data;
  11695. SSLClient cli("localhost", port);
  11696. cli.enable_server_certificate_verification(false);
  11697. UploadFormDataItems items{
  11698. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11699. {"hello", "world", "", ""},
  11700. };
  11701. auto res = cli.Put("/put", items);
  11702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11703. ASSERT_EQ(StatusCode::OK_200, res->status);
  11704. }
  11705. }
  11706. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11708. svr.Put("/put_customboundary",
  11709. [&](const Request &req, const Response & /*res*/,
  11710. const ContentReader &content_reader) {
  11711. if (req.is_multipart_form_data()) {
  11712. std::vector<FormData> items;
  11713. content_reader(
  11714. [&](const FormData &file) {
  11715. items.push_back(file);
  11716. return true;
  11717. },
  11718. [&](const char *data, size_t data_length) {
  11719. items.back().content.append(data, data_length);
  11720. return true;
  11721. });
  11722. EXPECT_TRUE(std::string(items[0].name) == "document");
  11723. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11724. EXPECT_TRUE(items[0].filename == "2MB_data");
  11725. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11726. EXPECT_TRUE(items[1].name == "hello");
  11727. EXPECT_TRUE(items[1].content == "world");
  11728. EXPECT_TRUE(items[1].filename == "");
  11729. EXPECT_TRUE(items[1].content_type == "");
  11730. } else {
  11731. std::string body;
  11732. content_reader([&](const char *data, size_t data_length) {
  11733. body.append(data, data_length);
  11734. return true;
  11735. });
  11736. }
  11737. });
  11738. auto port = svr.bind_to_any_port("localhost");
  11739. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11740. auto se = detail::scope_exit([&] {
  11741. svr.stop();
  11742. t.join();
  11743. ASSERT_FALSE(svr.is_running());
  11744. });
  11745. svr.wait_until_ready();
  11746. {
  11747. std::string data(1024 * 1024 * 2, '&');
  11748. std::stringstream buffer;
  11749. buffer << data;
  11750. SSLClient cli("localhost", port);
  11751. cli.enable_server_certificate_verification(false);
  11752. UploadFormDataItems items{
  11753. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11754. {"hello", "world", "", ""},
  11755. };
  11756. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11758. ASSERT_EQ(StatusCode::OK_200, res->status);
  11759. }
  11760. }
  11761. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11762. std::string data(1024 * 1024 * 2, '&');
  11763. std::stringstream buffer;
  11764. buffer << data;
  11765. Client cli("https://localhost:8080");
  11766. cli.enable_server_certificate_verification(false);
  11767. UploadFormDataItems items{
  11768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11769. {"hello", "world", "", ""},
  11770. };
  11771. for (const char &c : " \t\r\n") {
  11772. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11773. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11774. ASSERT_FALSE(res);
  11775. }
  11776. }
  11777. TEST(MultipartFormDataTest, AlternateFilename) {
  11778. auto handled = false;
  11779. Server svr;
  11780. svr.Post("/test", [&](const Request &req, Response &res) {
  11781. ASSERT_EQ(2u, req.form.files.size());
  11782. ASSERT_EQ(1u, req.form.fields.size());
  11783. // Test files
  11784. const auto &file1 = req.form.get_file("file1");
  11785. ASSERT_EQ("file1", file1.name);
  11786. ASSERT_EQ("A.txt", file1.filename);
  11787. ASSERT_EQ("text/plain", file1.content_type);
  11788. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11789. const auto &file2 = req.form.get_file("file2");
  11790. ASSERT_EQ("file2", file2.name);
  11791. ASSERT_EQ("a.html", file2.filename);
  11792. ASSERT_EQ("text/html", file2.content_type);
  11793. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11794. file2.content);
  11795. // Test text field
  11796. const auto &text = req.form.get_field("text");
  11797. ASSERT_EQ("text default", text);
  11798. res.set_content("ok", "text/plain");
  11799. handled = true;
  11800. });
  11801. thread t = thread([&] { svr.listen(HOST, PORT); });
  11802. auto se = detail::scope_exit([&] {
  11803. svr.stop();
  11804. t.join();
  11805. ASSERT_FALSE(svr.is_running());
  11806. ASSERT_TRUE(handled);
  11807. });
  11808. svr.wait_until_ready();
  11809. auto req = "POST /test HTTP/1.1\r\n"
  11810. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11811. "Content-Length: 399\r\n"
  11812. "\r\n"
  11813. "----------\r\n"
  11814. "Content-Disposition: form-data; name=\"text\"\r\n"
  11815. "\r\n"
  11816. "text default\r\n"
  11817. "----------\r\n"
  11818. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11819. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11820. "Content-Type: text/plain\r\n"
  11821. "\r\n"
  11822. "Content of a.txt.\r\n"
  11823. "\r\n"
  11824. "----------\r\n"
  11825. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11826. "\"a.html\"\r\n"
  11827. "Content-Type: text/html\r\n"
  11828. "\r\n"
  11829. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11830. "\r\n"
  11831. "------------\r\n";
  11832. ASSERT_TRUE(send_request(1, req));
  11833. }
  11834. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11835. auto handled = false;
  11836. Server svr;
  11837. svr.Post("/test", [&](const Request &req, Response &res) {
  11838. // Case-insensitive "utf-8''" prefix with a long value
  11839. const auto &file = req.form.get_file("file1");
  11840. ASSERT_EQ("file1", file.name);
  11841. // 8000 chars exercises both the Content-Disposition parser and the
  11842. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11843. // Prior to the fix, std::regex_match on this header would cause O(N)
  11844. // stack recursion in libstdc++, leading to SIGSEGV.
  11845. std::string expected_filename(8000, 'A');
  11846. ASSERT_EQ(expected_filename, file.filename);
  11847. res.set_content("ok", "text/plain");
  11848. handled = true;
  11849. });
  11850. thread t = thread([&] { svr.listen(HOST, PORT); });
  11851. auto se = detail::scope_exit([&] {
  11852. svr.stop();
  11853. t.join();
  11854. ASSERT_FALSE(svr.is_running());
  11855. ASSERT_TRUE(handled);
  11856. });
  11857. svr.wait_until_ready();
  11858. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11859. // Regression test for GHSA-qq6v-r583-3h69
  11860. std::string long_filename(8000, 'A');
  11861. std::string body = "----------\r\n"
  11862. "Content-Disposition: form-data; name=\"file1\"; "
  11863. "filename*=\"Utf-8''" +
  11864. long_filename +
  11865. "\"\r\n"
  11866. "\r\n"
  11867. "hello\r\n"
  11868. "------------\r\n";
  11869. auto req = "POST /test HTTP/1.1\r\n"
  11870. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11871. "Content-Length: " +
  11872. std::to_string(body.size()) + "\r\n\r\n" + body;
  11873. ASSERT_TRUE(send_request(1, req));
  11874. }
  11875. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11876. auto handled = false;
  11877. Server svr;
  11878. svr.Post("/test", [&](const Request &req, Response &) {
  11879. ASSERT_EQ(2u, req.form.fields.size());
  11880. const auto &text1 = req.form.get_field("text1");
  11881. ASSERT_EQ("text1", text1);
  11882. const auto &text2 = req.form.get_field("text2");
  11883. ASSERT_EQ("text2", text2);
  11884. handled = true;
  11885. });
  11886. thread t = thread([&] { svr.listen(HOST, PORT); });
  11887. auto se = detail::scope_exit([&] {
  11888. svr.stop();
  11889. t.join();
  11890. ASSERT_FALSE(svr.is_running());
  11891. ASSERT_TRUE(handled);
  11892. });
  11893. svr.wait_until_ready();
  11894. auto req = "POST /test HTTP/1.1\r\n"
  11895. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11896. "Content-Length: 146\r\n"
  11897. "\r\n----------\r\n"
  11898. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11899. "\r\n"
  11900. "text1"
  11901. "\r\n----------\r\n"
  11902. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11903. "\r\n"
  11904. "text2"
  11905. "\r\n------------";
  11906. std::string response;
  11907. ASSERT_TRUE(send_request(1, req, &response));
  11908. ASSERT_EQ("200", response.substr(9, 3));
  11909. }
  11910. TEST(MultipartFormDataTest, ContentLength) {
  11911. auto handled = false;
  11912. Server svr;
  11913. svr.Post("/test", [&](const Request &req, Response &) {
  11914. ASSERT_EQ(2u, req.form.fields.size());
  11915. const auto &text1 = req.form.get_field("text1");
  11916. ASSERT_EQ("text1", text1);
  11917. const auto &text2 = req.form.get_field("text2");
  11918. ASSERT_EQ("text2", text2);
  11919. handled = true;
  11920. });
  11921. thread t = thread([&] { svr.listen(HOST, PORT); });
  11922. auto se = detail::scope_exit([&] {
  11923. svr.stop();
  11924. t.join();
  11925. ASSERT_FALSE(svr.is_running());
  11926. ASSERT_TRUE(handled);
  11927. });
  11928. svr.wait_until_ready();
  11929. auto req = "POST /test HTTP/1.1\r\n"
  11930. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11931. "Content-Length: 167\r\n"
  11932. "\r\n----------\r\n"
  11933. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11934. "Content-Length: 5\r\n"
  11935. "\r\n"
  11936. "text1"
  11937. "\r\n----------\r\n"
  11938. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11939. "\r\n"
  11940. "text2"
  11941. "\r\n------------\r\n";
  11942. std::string response;
  11943. ASSERT_TRUE(send_request(1, req, &response));
  11944. ASSERT_EQ("200", response.substr(9, 3));
  11945. }
  11946. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11947. auto handled = false;
  11948. Server svr;
  11949. svr.Post("/test", [&](const Request &req, Response &) {
  11950. ASSERT_EQ(2u, req.form.fields.size());
  11951. const auto &text1 = req.form.get_field("text1");
  11952. ASSERT_EQ("text1", text1);
  11953. // TODO: Add header access for text fields if needed
  11954. const auto &text2 = req.form.get_field("text2");
  11955. ASSERT_EQ("text2", text2);
  11956. // TODO: Header access for text fields needs to be implemented
  11957. // auto &headers = it->second.headers;
  11958. // ASSERT_EQ(3U, headers.size());
  11959. // auto custom_header = headers.find("x-whatever");
  11960. // ASSERT_TRUE(custom_header != headers.end());
  11961. // ASSERT_NE("customvalue", custom_header->second);
  11962. // ASSERT_EQ("CustomValue", custom_header->second);
  11963. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11964. handled = true;
  11965. });
  11966. thread t = thread([&] { svr.listen(HOST, PORT); });
  11967. auto se = detail::scope_exit([&] {
  11968. svr.stop();
  11969. t.join();
  11970. ASSERT_FALSE(svr.is_running());
  11971. ASSERT_TRUE(handled);
  11972. });
  11973. svr.wait_until_ready();
  11974. auto req = "POST /test HTTP/1.1\r\n"
  11975. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11976. "Content-Length: 232\r\n"
  11977. "\r\n----------\r\n"
  11978. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11979. "Content-Length: 5\r\n"
  11980. "X-Test: 1\r\n"
  11981. "\r\n"
  11982. "text1"
  11983. "\r\n----------\r\n"
  11984. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11985. "Content-Type: text/plain\r\n"
  11986. "X-Whatever: CustomValue\r\n"
  11987. "\r\n"
  11988. "text2"
  11989. "\r\n------------\r\n"
  11990. "That should be disregarded. Not even read";
  11991. std::string response;
  11992. ASSERT_TRUE(send_request(1, req, &response));
  11993. ASSERT_EQ("200", response.substr(9, 3));
  11994. }
  11995. TEST(MultipartFormDataTest, LargeHeader) {
  11996. auto handled = false;
  11997. Server svr;
  11998. svr.Post("/test", [&](const Request &req, Response &) {
  11999. ASSERT_EQ(1u, req.form.fields.size());
  12000. const auto &text = req.form.get_field("name1");
  12001. ASSERT_EQ("text1", text);
  12002. handled = true;
  12003. });
  12004. thread t = thread([&] { svr.listen(HOST, PORT); });
  12005. auto se = detail::scope_exit([&] {
  12006. svr.stop();
  12007. t.join();
  12008. ASSERT_FALSE(svr.is_running());
  12009. ASSERT_TRUE(handled);
  12010. });
  12011. svr.wait_until_ready();
  12012. auto boundary = std::string("cpp-httplib-multipart-data");
  12013. std::string content = "--" + boundary +
  12014. "\r\n"
  12015. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12016. "\r\n"
  12017. "text1\r\n"
  12018. "--" +
  12019. boundary + "--\r\n";
  12020. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12021. "Content-Type: multipart/form-data;boundary=" +
  12022. boundary +
  12023. "\r\n"
  12024. "Content-Length: " +
  12025. std::to_string(content.size()) +
  12026. "\r\n"
  12027. "Dummy-Header: ";
  12028. std::string header_suffix = "\r\n"
  12029. "\r\n";
  12030. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12031. size_t header_dummy_size =
  12032. read_buff_size -
  12033. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12034. auto header_dummy = std::string(header_dummy_size, '@');
  12035. auto req = header_prefix + header_dummy + header_suffix + content;
  12036. std::string response;
  12037. ASSERT_TRUE(send_request(1, req, &response));
  12038. ASSERT_EQ("200", response.substr(9, 3));
  12039. }
  12040. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12041. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12042. // (not chunked Transfer-Encoding) after the streaming refactor.
  12043. auto handled = false;
  12044. Server svr;
  12045. svr.Post("/upload", [&](const Request &req, Response &res) {
  12046. auto cl_it = req.headers.find("Content-Length");
  12047. EXPECT_TRUE(cl_it != req.headers.end());
  12048. auto te_it = req.headers.find("Transfer-Encoding");
  12049. EXPECT_TRUE(te_it == req.headers.end());
  12050. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12051. res.set_content("ok", "text/plain");
  12052. handled = true;
  12053. });
  12054. auto port = svr.bind_to_any_port(HOST);
  12055. auto t = thread([&] { svr.listen_after_bind(); });
  12056. auto se = detail::scope_exit([&] {
  12057. svr.stop();
  12058. t.join();
  12059. ASSERT_FALSE(svr.is_running());
  12060. ASSERT_TRUE(handled);
  12061. });
  12062. svr.wait_until_ready();
  12063. UploadFormDataItems items = {
  12064. {"field1", "hello", "", "text/plain"},
  12065. {"file1", "world", "test.txt", "application/octet-stream"},
  12066. };
  12067. Client cli(HOST, port);
  12068. auto res = cli.Post("/upload", {}, items);
  12069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12070. EXPECT_EQ(StatusCode::OK_200, res->status);
  12071. }
  12072. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12073. // Verify that make_multipart_content_provider coalesces many small segments
  12074. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12075. constexpr size_t kItemCount = 1000;
  12076. UploadFormDataItems items;
  12077. items.reserve(kItemCount);
  12078. for (size_t i = 0; i < kItemCount; i++) {
  12079. items.push_back(
  12080. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12081. }
  12082. const std::string boundary = "----test-boundary";
  12083. auto content_length = detail::get_multipart_content_length(items, boundary);
  12084. auto provider = detail::make_multipart_content_provider(items, boundary);
  12085. // Drive the provider the same way write_content_with_progress does
  12086. size_t write_count = 0;
  12087. size_t total_bytes = 0;
  12088. DataSink sink;
  12089. size_t offset = 0;
  12090. sink.write = [&](const char *d, size_t l) -> bool {
  12091. (void)d;
  12092. write_count++;
  12093. total_bytes += l;
  12094. offset += l;
  12095. return true;
  12096. };
  12097. sink.is_writable = []() -> bool { return true; };
  12098. while (offset < content_length) {
  12099. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12100. }
  12101. EXPECT_EQ(content_length, total_bytes);
  12102. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12103. // With buffering into 64KB blocks, write_count should be much smaller.
  12104. auto segment_count = 3 * kItemCount + 1;
  12105. EXPECT_LT(write_count, segment_count / 10);
  12106. }
  12107. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12108. // Integration test: send many UploadFormDataItems and verify the server
  12109. // receives all of them correctly (#2410).
  12110. constexpr size_t kItemCount = 500;
  12111. auto handled = false;
  12112. Server svr;
  12113. svr.Post("/upload", [&](const Request &req, Response &res) {
  12114. EXPECT_EQ(kItemCount, req.form.fields.size());
  12115. for (size_t i = 0; i < kItemCount; i++) {
  12116. auto key = "field" + std::to_string(i);
  12117. auto val = "value" + std::to_string(i);
  12118. auto it = req.form.fields.find(key);
  12119. if (it != req.form.fields.end()) {
  12120. EXPECT_EQ(val, it->second.content);
  12121. } else {
  12122. ADD_FAILURE() << "Missing field: " << key;
  12123. }
  12124. }
  12125. res.set_content("ok", "text/plain");
  12126. handled = true;
  12127. });
  12128. auto port = svr.bind_to_any_port(HOST);
  12129. auto t = thread([&] { svr.listen_after_bind(); });
  12130. auto se = detail::scope_exit([&] {
  12131. svr.stop();
  12132. t.join();
  12133. ASSERT_FALSE(svr.is_running());
  12134. ASSERT_TRUE(handled);
  12135. });
  12136. svr.wait_until_ready();
  12137. UploadFormDataItems items;
  12138. items.reserve(kItemCount);
  12139. for (size_t i = 0; i < kItemCount; i++) {
  12140. items.push_back(
  12141. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12142. }
  12143. Client cli(HOST, port);
  12144. auto res = cli.Post("/upload", items);
  12145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12146. EXPECT_EQ(StatusCode::OK_200, res->status);
  12147. }
  12148. TEST(MultipartFormDataTest, MakeFileProvider) {
  12149. // Verify make_file_provider sends a file's contents correctly.
  12150. const std::string file_content(4096, 'Z');
  12151. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12152. {
  12153. std::ofstream ofs(tmp_path, std::ios::binary);
  12154. ofs.write(file_content.data(),
  12155. static_cast<std::streamsize>(file_content.size()));
  12156. }
  12157. auto handled = false;
  12158. Server svr;
  12159. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12160. const ContentReader &content_reader) {
  12161. ASSERT_TRUE(req.is_multipart_form_data());
  12162. std::vector<FormData> items;
  12163. content_reader(
  12164. [&](const FormData &file) {
  12165. items.push_back(file);
  12166. return true;
  12167. },
  12168. [&](const char *data, size_t data_length) {
  12169. items.back().content.append(data, data_length);
  12170. return true;
  12171. });
  12172. ASSERT_EQ(1u, items.size());
  12173. EXPECT_EQ("myfile", items[0].name);
  12174. EXPECT_EQ("data.bin", items[0].filename);
  12175. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12176. EXPECT_EQ(file_content, items[0].content);
  12177. handled = true;
  12178. });
  12179. auto port = svr.bind_to_any_port(HOST);
  12180. auto t = thread([&] { svr.listen_after_bind(); });
  12181. auto se = detail::scope_exit([&] {
  12182. svr.stop();
  12183. t.join();
  12184. ASSERT_FALSE(svr.is_running());
  12185. ASSERT_TRUE(handled);
  12186. std::remove(tmp_path.c_str());
  12187. });
  12188. svr.wait_until_ready();
  12189. FormDataProviderItems providers;
  12190. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12191. "application/octet-stream"));
  12192. Client cli(HOST, port);
  12193. auto res = cli.Post("/upload", {}, {}, providers);
  12194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12195. EXPECT_EQ(StatusCode::OK_200, res->status);
  12196. }
  12197. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12198. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12199. // (100) headers is rejected with a 400 Bad Request response.
  12200. Server svr;
  12201. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12202. res.set_content("ok", "text/plain");
  12203. });
  12204. thread t = thread([&] { svr.listen(HOST, PORT); });
  12205. auto se = detail::scope_exit([&] {
  12206. svr.stop();
  12207. t.join();
  12208. ASSERT_FALSE(svr.is_running());
  12209. });
  12210. svr.wait_until_ready();
  12211. // Build a multipart part with 101 custom headers (exceeding
  12212. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12213. std::stringstream body;
  12214. body << "--simpleboundary\r\n"
  12215. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12216. for (int i = 0; i < 101; i++) {
  12217. body << "X-Custom-Header-" << i << ": value\r\n";
  12218. }
  12219. body << "\r\n"
  12220. << "value1\r\n"
  12221. << "--simpleboundary--\r\n";
  12222. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12223. Client cli(HOST, PORT);
  12224. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12227. }
  12228. TEST(MakeFileBodyTest, Basic) {
  12229. const std::string file_content(4096, 'Z');
  12230. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12231. {
  12232. std::ofstream ofs(tmp_path, std::ios::binary);
  12233. ofs.write(file_content.data(),
  12234. static_cast<std::streamsize>(file_content.size()));
  12235. }
  12236. auto handled = false;
  12237. Server svr;
  12238. svr.Post("/upload", [&](const Request &req, Response &res) {
  12239. EXPECT_EQ(file_content, req.body);
  12240. handled = true;
  12241. res.status = StatusCode::OK_200;
  12242. });
  12243. auto port = svr.bind_to_any_port(HOST);
  12244. auto t = thread([&] { svr.listen_after_bind(); });
  12245. auto se = detail::scope_exit([&] {
  12246. svr.stop();
  12247. t.join();
  12248. ASSERT_FALSE(svr.is_running());
  12249. ASSERT_TRUE(handled);
  12250. std::remove(tmp_path.c_str());
  12251. });
  12252. svr.wait_until_ready();
  12253. auto fb = make_file_body(tmp_path);
  12254. ASSERT_GT(fb.first, 0u);
  12255. Client cli(HOST, port);
  12256. auto res =
  12257. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12259. EXPECT_EQ(StatusCode::OK_200, res->status);
  12260. }
  12261. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12262. static constexpr unsigned int number_of_tasks{1000000};
  12263. std::atomic_uint count{0};
  12264. std::unique_ptr<TaskQueue> task_queue{
  12265. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12266. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12267. auto queued = task_queue->enqueue(
  12268. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12269. EXPECT_TRUE(queued);
  12270. }
  12271. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12272. task_queue->shutdown();
  12273. #else
  12274. EXPECT_NO_THROW(task_queue->shutdown());
  12275. #endif
  12276. EXPECT_EQ(number_of_tasks, count.load());
  12277. }
  12278. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12279. static constexpr unsigned int number_of_tasks{1000000};
  12280. static constexpr unsigned int qlimit{2};
  12281. unsigned int queued_count{0};
  12282. std::atomic_uint count{0};
  12283. std::unique_ptr<TaskQueue> task_queue{
  12284. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12285. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12286. if (task_queue->enqueue(
  12287. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12288. queued_count++;
  12289. }
  12290. }
  12291. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12292. task_queue->shutdown();
  12293. #else
  12294. EXPECT_NO_THROW(task_queue->shutdown());
  12295. #endif
  12296. EXPECT_EQ(queued_count, count.load());
  12297. EXPECT_TRUE(queued_count <= number_of_tasks);
  12298. EXPECT_TRUE(queued_count >= qlimit);
  12299. }
  12300. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12301. // Use a short idle timeout so a dynamic thread spawns, times out and
  12302. // exits during the test, and the pool keeps working afterwards.
  12303. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12304. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12305. /*idle_timeout_sec=*/1}};
  12306. std::atomic_uint count{0};
  12307. std::condition_variable cv;
  12308. std::mutex mtx;
  12309. bool release = false;
  12310. // Block the base thread so the second task spawns a dynamic thread.
  12311. EXPECT_TRUE(task_queue->enqueue([&] {
  12312. std::unique_lock<std::mutex> lock(mtx);
  12313. while (!release) {
  12314. cv.wait(lock);
  12315. }
  12316. count++;
  12317. }));
  12318. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12319. // Let the dynamic thread finish its task and exceed the idle timeout.
  12320. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12321. {
  12322. std::unique_lock<std::mutex> lock(mtx);
  12323. release = true;
  12324. }
  12325. cv.notify_all();
  12326. // The pool must still accept and run tasks after the dynamic thread exited.
  12327. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12328. task_queue->shutdown();
  12329. EXPECT_EQ(3u, count.load());
  12330. }
  12331. TEST(TaskQueueTest, MaxQueuedRequests) {
  12332. static constexpr unsigned int qlimit{3};
  12333. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12334. std::condition_variable sem_cv;
  12335. std::mutex sem_mtx;
  12336. int credits = 0;
  12337. bool queued;
  12338. /* Fill up the queue with tasks that will block until we give them credits to
  12339. * complete. */
  12340. for (unsigned int n = 0; n <= qlimit;) {
  12341. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12342. std::unique_lock<std::mutex> lock(sem_mtx);
  12343. while (credits <= 0) {
  12344. sem_cv.wait(lock);
  12345. }
  12346. /* Consume the credit and signal the test code if they are all gone. */
  12347. if (--credits == 0) { sem_cv.notify_one(); }
  12348. });
  12349. if (n < qlimit) {
  12350. /* The first qlimit enqueues must succeed. */
  12351. EXPECT_TRUE(queued);
  12352. } else {
  12353. /* The last one will succeed only when the worker thread
  12354. * starts and dequeues the first blocking task. Although
  12355. * not necessary for the correctness of this test, we sleep for
  12356. * a short while to avoid busy waiting. */
  12357. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12358. }
  12359. if (queued) { n++; }
  12360. }
  12361. /* Further enqueues must fail since the queue is full. */
  12362. for (auto i = 0; i < 4; i++) {
  12363. queued = task_queue->enqueue([] {});
  12364. EXPECT_FALSE(queued);
  12365. }
  12366. /* Give the credits to allow the previous tasks to complete. */
  12367. {
  12368. std::unique_lock<std::mutex> lock(sem_mtx);
  12369. credits += qlimit + 1;
  12370. }
  12371. sem_cv.notify_all();
  12372. /* Wait for all the credits to be consumed. */
  12373. {
  12374. std::unique_lock<std::mutex> lock(sem_mtx);
  12375. while (credits > 0) {
  12376. sem_cv.wait(lock);
  12377. }
  12378. }
  12379. /* Check that we are able again to enqueue at least qlimit tasks. */
  12380. for (unsigned int i = 0; i < qlimit; i++) {
  12381. queued = task_queue->enqueue([] {});
  12382. EXPECT_TRUE(queued);
  12383. }
  12384. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12385. task_queue->shutdown();
  12386. #else
  12387. EXPECT_NO_THROW(task_queue->shutdown());
  12388. #endif
  12389. }
  12390. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12391. Server svr;
  12392. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12393. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12394. });
  12395. svr.Get("/hello", [](const Request &req, Response &res) {
  12396. res.set_content(req.get_param_value("key"), "text/plain");
  12397. });
  12398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12399. auto se = detail::scope_exit([&] {
  12400. svr.stop();
  12401. thread.join();
  12402. ASSERT_FALSE(svr.is_running());
  12403. });
  12404. svr.wait_until_ready();
  12405. {
  12406. Client cli(HOST, PORT);
  12407. cli.set_follow_location(true);
  12408. auto res = cli.Get("/");
  12409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12410. EXPECT_EQ(StatusCode::OK_200, res->status);
  12411. EXPECT_EQ("val&key2=val2", res->body);
  12412. }
  12413. }
  12414. #endif
  12415. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12416. Server svr;
  12417. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12418. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12419. });
  12420. svr.Get("/hello", [](const Request &req, Response &res) {
  12421. res.set_content(req.get_param_value("key"), "text/plain");
  12422. });
  12423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12424. auto se = detail::scope_exit([&] {
  12425. svr.stop();
  12426. thread.join();
  12427. ASSERT_FALSE(svr.is_running());
  12428. });
  12429. svr.wait_until_ready();
  12430. {
  12431. Client cli(HOST, PORT);
  12432. cli.set_follow_location(true);
  12433. auto res = cli.Get("/");
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12435. EXPECT_EQ(StatusCode::OK_200, res->status);
  12436. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12437. }
  12438. }
  12439. TEST(RedirectTest, RedirectWithPlusInPath) {
  12440. Server svr;
  12441. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12442. res.set_redirect("/a+b");
  12443. });
  12444. // Route pattern uses regex; escape + as \\+
  12445. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12446. res.set_content(req.path, "text/plain");
  12447. });
  12448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12449. auto se = detail::scope_exit([&] {
  12450. svr.stop();
  12451. thread.join();
  12452. ASSERT_FALSE(svr.is_running());
  12453. });
  12454. svr.wait_until_ready();
  12455. {
  12456. Client cli(HOST, PORT);
  12457. cli.set_follow_location(true);
  12458. auto res = cli.Get("/");
  12459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12460. EXPECT_EQ(StatusCode::OK_200, res->status);
  12461. EXPECT_EQ("/a+b", res->body);
  12462. }
  12463. }
  12464. #ifdef CPPHTTPLIB_SSL_ENABLED
  12465. TEST(RedirectTest, Issue2185_Online) {
  12466. SSLClient client("github.com");
  12467. client.set_follow_location(true);
  12468. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12469. "Coollab-Windows.zip");
  12470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12471. EXPECT_EQ(StatusCode::OK_200, res->status);
  12472. EXPECT_EQ(9920427U, res->body.size());
  12473. }
  12474. #endif
  12475. TEST(VulnerabilityTest, CRLFInjection) {
  12476. Server svr;
  12477. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12478. res.set_content("Hello 1", "text/plain");
  12479. });
  12480. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12481. res.set_content("Hello 2", "text/plain");
  12482. });
  12483. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12484. res.set_content("Hello 3", "text/plain");
  12485. });
  12486. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12487. res.set_content("Hello 4", "text/plain");
  12488. });
  12489. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12490. for (const auto &x : req.headers) {
  12491. auto key = x.first;
  12492. EXPECT_STRNE("evil", key.c_str());
  12493. }
  12494. });
  12495. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12496. auto se = detail::scope_exit([&] {
  12497. svr.stop();
  12498. thread.join();
  12499. ASSERT_FALSE(svr.is_running());
  12500. });
  12501. svr.wait_until_ready();
  12502. {
  12503. Client cli(HOST, PORT);
  12504. cli.Post("/test1", "A=B",
  12505. "application/x-www-form-urlencoded\r\nevil: hello1");
  12506. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12507. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12508. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12509. }
  12510. }
  12511. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12512. auto server_thread = std::thread([] {
  12513. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12514. default_socket_options(srv);
  12515. sockaddr_in addr{};
  12516. addr.sin_family = AF_INET;
  12517. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12518. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12519. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12520. ::listen(srv, 1);
  12521. sockaddr_in cli_addr{};
  12522. socklen_t cli_len = sizeof(cli_addr);
  12523. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12524. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12525. std::string buf_all;
  12526. char buf[2048];
  12527. ssize_t n;
  12528. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12529. buf_all.append(buf, static_cast<size_t>(n));
  12530. size_t pos;
  12531. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12532. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12533. auto e = request_block.find("\r\n");
  12534. if (e != std::string::npos) {
  12535. auto request_line = request_block.substr(0, e);
  12536. std::string msg =
  12537. "CRLF injection detected in request line: '" + request_line + "'";
  12538. EXPECT_FALSE(true) << msg;
  12539. }
  12540. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12541. ::send(cli,
  12542. #ifdef _WIN32
  12543. static_cast<const char *>(resp.c_str()),
  12544. static_cast<int>(resp.size()),
  12545. #else
  12546. resp.c_str(), resp.size(),
  12547. #endif
  12548. 0);
  12549. buf_all.erase(0, pos + 4);
  12550. }
  12551. }
  12552. detail::close_socket(cli);
  12553. detail::close_socket(srv);
  12554. });
  12555. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12556. auto cli = Client("127.0.0.1", PORT + 1);
  12557. auto headers = Headers{
  12558. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12559. {"Connection", "keep-alive"}};
  12560. auto res = cli.Get("/hi", headers);
  12561. EXPECT_FALSE(res);
  12562. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12563. server_thread.join();
  12564. }
  12565. TEST(PathParamsTest, StaticMatch) {
  12566. const auto pattern = "/users/all";
  12567. detail::PathParamsMatcher matcher(pattern);
  12568. Request request;
  12569. request.path = "/users/all";
  12570. ASSERT_TRUE(matcher.match(request));
  12571. std::unordered_map<std::string, std::string> expected_params = {};
  12572. EXPECT_EQ(request.path_params, expected_params);
  12573. }
  12574. TEST(PathParamsTest, StaticMismatch) {
  12575. const auto pattern = "/users/all";
  12576. detail::PathParamsMatcher matcher(pattern);
  12577. Request request;
  12578. request.path = "/users/1";
  12579. ASSERT_FALSE(matcher.match(request));
  12580. }
  12581. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12582. const auto pattern = "/users/:id/subscriptions";
  12583. detail::PathParamsMatcher matcher(pattern);
  12584. Request request;
  12585. request.path = "/users/42/subscriptions";
  12586. ASSERT_TRUE(matcher.match(request));
  12587. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12588. EXPECT_EQ(request.path_params, expected_params);
  12589. }
  12590. TEST(PathParamsTest, SingleParamInTheEnd) {
  12591. const auto pattern = "/users/:id";
  12592. detail::PathParamsMatcher matcher(pattern);
  12593. Request request;
  12594. request.path = "/users/24";
  12595. ASSERT_TRUE(matcher.match(request));
  12596. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12597. EXPECT_EQ(request.path_params, expected_params);
  12598. }
  12599. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12600. const auto pattern = "/users/:id/";
  12601. detail::PathParamsMatcher matcher(pattern);
  12602. Request request;
  12603. request.path = "/users/42/";
  12604. ASSERT_TRUE(matcher.match(request));
  12605. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12606. EXPECT_EQ(request.path_params, expected_params);
  12607. }
  12608. TEST(PathParamsTest, EmptyParam) {
  12609. const auto pattern = "/users/:id/";
  12610. detail::PathParamsMatcher matcher(pattern);
  12611. Request request;
  12612. request.path = "/users//";
  12613. ASSERT_TRUE(matcher.match(request));
  12614. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12615. EXPECT_EQ(request.path_params, expected_params);
  12616. }
  12617. TEST(PathParamsTest, FragmentMismatch) {
  12618. const auto pattern = "/users/:id/";
  12619. detail::PathParamsMatcher matcher(pattern);
  12620. Request request;
  12621. request.path = "/admins/24/";
  12622. ASSERT_FALSE(matcher.match(request));
  12623. }
  12624. TEST(PathParamsTest, ExtraFragments) {
  12625. const auto pattern = "/users/:id";
  12626. detail::PathParamsMatcher matcher(pattern);
  12627. Request request;
  12628. request.path = "/users/42/subscriptions";
  12629. ASSERT_FALSE(matcher.match(request));
  12630. }
  12631. TEST(PathParamsTest, MissingTrailingParam) {
  12632. const auto pattern = "/users/:id";
  12633. detail::PathParamsMatcher matcher(pattern);
  12634. Request request;
  12635. request.path = "/users";
  12636. ASSERT_FALSE(matcher.match(request));
  12637. }
  12638. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12639. const auto pattern = "/users/:id/subscriptions";
  12640. detail::PathParamsMatcher matcher(pattern);
  12641. Request request;
  12642. request.path = "/users/subscriptions";
  12643. ASSERT_FALSE(matcher.match(request));
  12644. }
  12645. TEST(PathParamsTest, MultipleParams) {
  12646. const auto pattern = "/users/:userid/subscriptions/:subid";
  12647. detail::PathParamsMatcher matcher(pattern);
  12648. Request request;
  12649. request.path = "/users/42/subscriptions/2";
  12650. ASSERT_TRUE(matcher.match(request));
  12651. std::unordered_map<std::string, std::string> expected_params = {
  12652. {"userid", "42"}, {"subid", "2"}};
  12653. EXPECT_EQ(request.path_params, expected_params);
  12654. }
  12655. TEST(PathParamsTest, SequenceOfParams) {
  12656. const auto pattern = "/values/:x/:y/:z";
  12657. detail::PathParamsMatcher matcher(pattern);
  12658. Request request;
  12659. request.path = "/values/1/2/3";
  12660. ASSERT_TRUE(matcher.match(request));
  12661. std::unordered_map<std::string, std::string> expected_params = {
  12662. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12663. EXPECT_EQ(request.path_params, expected_params);
  12664. }
  12665. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12666. const auto pattern = "/prefix:suffix";
  12667. detail::PathParamsMatcher matcher(pattern);
  12668. Request request;
  12669. request.path = "/prefix:suffix";
  12670. ASSERT_TRUE(matcher.match(request));
  12671. const std::unordered_map<std::string, std::string> expected_params = {};
  12672. EXPECT_EQ(request.path_params, expected_params);
  12673. }
  12674. TEST(ParseUrlTest, VariousPatterns) {
  12675. {
  12676. detail::UrlComponents uc;
  12677. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12678. EXPECT_EQ("http", uc.scheme);
  12679. EXPECT_EQ("example.com", uc.host);
  12680. EXPECT_EQ("8080", uc.port);
  12681. EXPECT_EQ("/path", uc.path);
  12682. EXPECT_EQ("?q=1", uc.query);
  12683. }
  12684. {
  12685. detail::UrlComponents uc;
  12686. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12687. EXPECT_EQ("https", uc.scheme);
  12688. EXPECT_EQ("example.com", uc.host);
  12689. EXPECT_TRUE(uc.port.empty());
  12690. EXPECT_EQ("/path", uc.path);
  12691. }
  12692. {
  12693. detail::UrlComponents uc;
  12694. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12695. EXPECT_EQ("::1", uc.host);
  12696. EXPECT_EQ("8080", uc.port);
  12697. EXPECT_EQ("/path", uc.path);
  12698. }
  12699. {
  12700. detail::UrlComponents uc;
  12701. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12702. }
  12703. {
  12704. detail::UrlComponents uc;
  12705. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12706. EXPECT_TRUE(uc.scheme.empty());
  12707. EXPECT_EQ("example.com", uc.host);
  12708. EXPECT_EQ("/path", uc.path);
  12709. EXPECT_EQ("?q=1", uc.query);
  12710. }
  12711. {
  12712. detail::UrlComponents uc;
  12713. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12714. EXPECT_TRUE(uc.host.empty());
  12715. EXPECT_EQ("/path", uc.path);
  12716. EXPECT_EQ("?q=1", uc.query);
  12717. }
  12718. {
  12719. detail::UrlComponents uc;
  12720. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12721. EXPECT_EQ("example.com", uc.host);
  12722. EXPECT_EQ("8080", uc.port);
  12723. }
  12724. {
  12725. // Unix socket path — must not be parsed as host
  12726. detail::UrlComponents uc;
  12727. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12728. EXPECT_TRUE(uc.host.empty());
  12729. }
  12730. {
  12731. detail::UrlComponents uc;
  12732. ASSERT_TRUE(detail::parse_url("", uc));
  12733. EXPECT_TRUE(uc.host.empty());
  12734. EXPECT_TRUE(uc.path.empty());
  12735. }
  12736. {
  12737. detail::UrlComponents uc;
  12738. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12739. }
  12740. {
  12741. detail::UrlComponents uc;
  12742. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12743. }
  12744. {
  12745. // Accepted by parse_url; callers restrict to http/https
  12746. detail::UrlComponents uc;
  12747. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12748. EXPECT_EQ("ftp", uc.scheme);
  12749. }
  12750. {
  12751. detail::UrlComponents uc;
  12752. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12753. }
  12754. {
  12755. detail::UrlComponents uc;
  12756. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12757. }
  12758. }
  12759. TEST(ParseUrlTest, FragmentHandling) {
  12760. {
  12761. detail::UrlComponents uc;
  12762. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12763. EXPECT_EQ("/path", uc.path);
  12764. EXPECT_TRUE(uc.query.empty());
  12765. }
  12766. {
  12767. detail::UrlComponents uc;
  12768. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12769. EXPECT_TRUE(uc.path.empty());
  12770. EXPECT_TRUE(uc.query.empty());
  12771. }
  12772. }
  12773. TEST(ParseUrlTest, UserinfoHandling) {
  12774. // Userinfo with @ but no colon — host includes @
  12775. detail::UrlComponents uc;
  12776. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12777. EXPECT_EQ("user@host.com", uc.host);
  12778. EXPECT_EQ("/path", uc.path);
  12779. }
  12780. TEST(ParseUrlTest, IPv6EdgeCases) {
  12781. {
  12782. detail::UrlComponents uc;
  12783. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12784. EXPECT_TRUE(uc.scheme.empty());
  12785. EXPECT_EQ("::1", uc.host);
  12786. EXPECT_EQ("8080", uc.port);
  12787. }
  12788. {
  12789. // Zone ID '%25' is not in [a-fA-F0-9:]
  12790. detail::UrlComponents uc;
  12791. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12792. }
  12793. }
  12794. TEST(ParseUrlTest, SchemeEdgeCases) {
  12795. {
  12796. detail::UrlComponents uc;
  12797. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12798. }
  12799. {
  12800. detail::UrlComponents uc;
  12801. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12802. }
  12803. {
  12804. detail::UrlComponents uc;
  12805. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12806. }
  12807. }
  12808. TEST(ParseUrlTest, PortEdgeCases) {
  12809. {
  12810. detail::UrlComponents uc;
  12811. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12812. EXPECT_TRUE(uc.port.empty());
  12813. EXPECT_EQ("/path", uc.path);
  12814. }
  12815. {
  12816. // parse_url accepts any port string; validation is done by parse_port
  12817. detail::UrlComponents uc;
  12818. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12819. EXPECT_EQ("abc", uc.port);
  12820. }
  12821. }
  12822. TEST(ParseUrlTest, WebSocketPatterns) {
  12823. {
  12824. detail::UrlComponents uc;
  12825. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12826. EXPECT_EQ("ws", uc.scheme);
  12827. EXPECT_EQ("echo.example.com", uc.host);
  12828. EXPECT_EQ("8080", uc.port);
  12829. EXPECT_EQ("/ws", uc.path);
  12830. }
  12831. {
  12832. detail::UrlComponents uc;
  12833. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12834. EXPECT_EQ("wss", uc.scheme);
  12835. EXPECT_EQ("echo.example.com", uc.host);
  12836. EXPECT_TRUE(uc.port.empty());
  12837. EXPECT_EQ("/ws", uc.path);
  12838. }
  12839. }
  12840. TEST(ParseUrlTest, QueryOnly) {
  12841. detail::UrlComponents uc;
  12842. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12843. EXPECT_TRUE(uc.host.empty());
  12844. EXPECT_TRUE(uc.path.empty());
  12845. EXPECT_EQ("?q=1&r=2", uc.query);
  12846. }
  12847. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12848. detail::UrlComponents uc;
  12849. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12850. EXPECT_TRUE(uc.scheme.empty());
  12851. EXPECT_EQ("example.com", uc.host);
  12852. EXPECT_EQ("443", uc.port);
  12853. EXPECT_EQ("/path", uc.path);
  12854. }
  12855. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12856. // If ipv6 regex working, regex match codepath is taken.
  12857. // else port will default to 80 in Client impl
  12858. int clientImplMagicPort = 80;
  12859. int port = 4321;
  12860. // above ports must be different to avoid false negative
  12861. EXPECT_NE(clientImplMagicPort, port);
  12862. std::string ipV6TestURL = "http://[ff06::c3]";
  12863. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12864. CLIENT_PRIVATE_KEY_FILE);
  12865. EXPECT_EQ(cli.port(), port);
  12866. }
  12867. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12868. auto file_path = "./www/dir/index.html";
  12869. auto dir_path = "./www/dir";
  12870. detail::FileStat stat_file(file_path);
  12871. EXPECT_TRUE(stat_file.is_file());
  12872. EXPECT_FALSE(stat_file.is_dir());
  12873. detail::FileStat stat_dir(dir_path);
  12874. EXPECT_FALSE(stat_dir.is_file());
  12875. EXPECT_TRUE(stat_dir.is_dir());
  12876. }
  12877. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12878. // IPv4 with default HTTP port (80)
  12879. EXPECT_EQ("example.com",
  12880. detail::make_host_and_port_string("example.com", 80, false));
  12881. // IPv4 with default HTTPS port (443)
  12882. EXPECT_EQ("example.com",
  12883. detail::make_host_and_port_string("example.com", 443, true));
  12884. // IPv4 with non-default HTTP port
  12885. EXPECT_EQ("example.com:8080",
  12886. detail::make_host_and_port_string("example.com", 8080, false));
  12887. // IPv4 with non-default HTTPS port
  12888. EXPECT_EQ("example.com:8443",
  12889. detail::make_host_and_port_string("example.com", 8443, true));
  12890. // IPv6 with default HTTP port (80)
  12891. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12892. // IPv6 with default HTTPS port (443)
  12893. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12894. // IPv6 with non-default HTTP port
  12895. EXPECT_EQ("[::1]:8080",
  12896. detail::make_host_and_port_string("::1", 8080, false));
  12897. // IPv6 with non-default HTTPS port
  12898. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12899. // IPv6 full address with default port
  12900. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12901. detail::make_host_and_port_string(
  12902. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12903. // IPv6 full address with non-default port
  12904. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12905. detail::make_host_and_port_string(
  12906. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12907. // IPv6 localhost with non-default port
  12908. EXPECT_EQ("[::1]:3000",
  12909. detail::make_host_and_port_string("::1", 3000, false));
  12910. // IPv6 with zone ID (link-local address) with default port
  12911. EXPECT_EQ("[fe80::1%eth0]",
  12912. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12913. // IPv6 with zone ID (link-local address) with non-default port
  12914. EXPECT_EQ("[fe80::1%eth0]:8080",
  12915. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12916. // Edge case: Port 443 with is_ssl=false (should add port)
  12917. EXPECT_EQ("example.com:443",
  12918. detail::make_host_and_port_string("example.com", 443, false));
  12919. // Edge case: Port 80 with is_ssl=true (should add port)
  12920. EXPECT_EQ("example.com:80",
  12921. detail::make_host_and_port_string("example.com", 80, true));
  12922. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12923. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12924. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12925. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12926. // Security fix: Already bracketed IPv6 should not get double brackets
  12927. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12928. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12929. EXPECT_EQ("[::1]:8080",
  12930. detail::make_host_and_port_string("[::1]", 8080, false));
  12931. EXPECT_EQ("[2001:db8::1]:8080",
  12932. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12933. EXPECT_EQ("[fe80::1%eth0]",
  12934. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12935. EXPECT_EQ("[fe80::1%eth0]:8080",
  12936. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12937. // Edge case: Empty host (should return as-is)
  12938. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12939. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12940. // This is a known limitation but shouldn't crash
  12941. EXPECT_EQ("[host:name]",
  12942. detail::make_host_and_port_string("host:name", 80, false));
  12943. // Port number edge cases (no validation, but should not crash)
  12944. EXPECT_EQ("example.com:0",
  12945. detail::make_host_and_port_string("example.com", 0, false));
  12946. EXPECT_EQ("example.com:-1",
  12947. detail::make_host_and_port_string("example.com", -1, false));
  12948. EXPECT_EQ("example.com:65535",
  12949. detail::make_host_and_port_string("example.com", 65535, false));
  12950. EXPECT_EQ("example.com:65536",
  12951. detail::make_host_and_port_string("example.com", 65536, false));
  12952. }
  12953. #ifdef CPPHTTPLIB_SSL_ENABLED
  12954. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12955. httplib::SSLClient cli("roblox.com", 443);
  12956. cli.set_follow_location(true);
  12957. auto res = cli.Get("/");
  12958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12959. EXPECT_EQ(StatusCode::OK_200, res->status);
  12960. }
  12961. #endif
  12962. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12963. Server svr;
  12964. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12965. EXPECT_EQ(res.status, 400);
  12966. });
  12967. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12968. auto se = detail::scope_exit([&] {
  12969. svr.stop();
  12970. thread.join();
  12971. ASSERT_FALSE(svr.is_running());
  12972. });
  12973. svr.wait_until_ready();
  12974. Client cli(HOST, PORT);
  12975. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12976. }
  12977. TEST(InvalidHeaderCharsTest, is_field_name) {
  12978. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12979. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12980. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12981. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12982. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12983. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12984. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12985. EXPECT_FALSE(detail::fields::is_field_name(""));
  12986. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12987. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12988. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12989. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12990. }
  12991. TEST(InvalidHeaderCharsTest, is_field_value) {
  12992. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12993. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12994. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12995. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12996. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12997. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12998. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12999. EXPECT_TRUE(detail::fields::is_field_value(""));
  13000. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13001. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13002. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13003. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13004. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13005. }
  13006. TEST(InvalidHeaderCharsTest, OnServer) {
  13007. Server svr;
  13008. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13009. std::string header = "Not Set";
  13010. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13011. res.set_header(header, "value");
  13012. res.set_content("Page Content Page Content", "text/plain");
  13013. });
  13014. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13015. std::string header = "Not Set";
  13016. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13017. res.set_header("X-Test", header);
  13018. res.set_content("Page Content Page Content", "text/plain");
  13019. });
  13020. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13021. auto se = detail::scope_exit([&] {
  13022. svr.stop();
  13023. thread.join();
  13024. ASSERT_FALSE(svr.is_running());
  13025. });
  13026. svr.wait_until_ready();
  13027. Client cli(HOST, PORT);
  13028. {
  13029. auto res = cli.Get(
  13030. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13032. EXPECT_EQ("Page Content Page Content", res->body);
  13033. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13034. }
  13035. {
  13036. auto res = cli.Get(
  13037. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13039. EXPECT_EQ("Page Content Page Content", res->body);
  13040. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13041. }
  13042. }
  13043. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13044. auto handled = false;
  13045. Server svr;
  13046. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13047. thread t = thread([&] { svr.listen(HOST, PORT); });
  13048. auto se = detail::scope_exit([&] {
  13049. svr.stop();
  13050. t.join();
  13051. ASSERT_FALSE(svr.is_running());
  13052. ASSERT_FALSE(handled);
  13053. });
  13054. svr.wait_until_ready();
  13055. auto req = "POST /test HTTP/1.1\r\n"
  13056. "Content-Length: x\r\n"
  13057. "\r\n";
  13058. std::string response;
  13059. ASSERT_TRUE(send_request(1, req, &response));
  13060. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13061. response.substr(0, response.find("\r\n")));
  13062. }
  13063. #ifndef _WIN32
  13064. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13065. static constexpr char reject[] = "Unauthorized";
  13066. static constexpr char accept[] = "Upload accepted";
  13067. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13068. Server svr;
  13069. svr.set_expect_100_continue_handler(
  13070. [](const Request & /*req*/, Response &res) {
  13071. res.status = StatusCode::Unauthorized_401;
  13072. res.set_content(reject, "text/plain");
  13073. return res.status;
  13074. });
  13075. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13076. res.set_content(accept, "text/plain");
  13077. });
  13078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13079. auto se = detail::scope_exit([&] {
  13080. svr.stop();
  13081. thread.join();
  13082. ASSERT_FALSE(svr.is_running());
  13083. });
  13084. svr.wait_until_ready();
  13085. {
  13086. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13087. curl_easy_init(), &curl_easy_cleanup};
  13088. ASSERT_NE(curl, nullptr);
  13089. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13090. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13091. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13092. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13093. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13094. &curl_slist_free_all};
  13095. ASSERT_NE(list, nullptr);
  13096. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13097. struct read_data {
  13098. size_t read_size;
  13099. size_t total_size;
  13100. } data = {0, total_size};
  13101. using read_callback_t =
  13102. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13103. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13104. void *userdata) -> size_t {
  13105. read_data *d = (read_data *)userdata;
  13106. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13107. std::fill_n(ptr, size * nmemb, 'A');
  13108. d->read_size += size * nmemb;
  13109. return size * nmemb;
  13110. };
  13111. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13112. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13113. std::vector<char> buffer;
  13114. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13115. using write_callback_t =
  13116. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13117. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13118. void *userdata) -> size_t {
  13119. std::vector<char> *buf = (std::vector<char> *)userdata;
  13120. buf->reserve(buf->size() + size * nmemb + 1);
  13121. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13122. return size * nmemb;
  13123. };
  13124. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13125. {
  13126. const auto res = curl_easy_perform(curl.get());
  13127. ASSERT_EQ(res, CURLE_OK);
  13128. }
  13129. {
  13130. auto response_code = long{};
  13131. const auto res =
  13132. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13133. ASSERT_EQ(res, CURLE_OK);
  13134. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13135. }
  13136. {
  13137. auto dl = curl_off_t{};
  13138. const auto res =
  13139. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13140. ASSERT_EQ(res, CURLE_OK);
  13141. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13142. }
  13143. {
  13144. buffer.push_back('\0');
  13145. ASSERT_STRCASEEQ(buffer.data(), reject);
  13146. }
  13147. }
  13148. }
  13149. #endif
  13150. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13151. // Regression test for #2458.
  13152. //
  13153. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13154. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13155. // ticket can make the client socket spuriously readable during the
  13156. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13157. // the client withholds the body and then blocks reading a response that never
  13158. // comes, failing with `Failed to read connection`.
  13159. //
  13160. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13161. // within the timeout. This raw OpenSSL server deliberately never sends
  13162. // `100 Continue`; the client must still deliver the body and receive 200.
  13163. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13164. signal(SIGPIPE, SIG_IGN);
  13165. const auto port = PORT + 4;
  13166. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13167. ASSERT_NE(srv, INVALID_SOCKET);
  13168. int opt = 1;
  13169. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13170. sockaddr_in addr{};
  13171. addr.sin_family = AF_INET;
  13172. addr.sin_port = htons(static_cast<uint16_t>(port));
  13173. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13174. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13175. ASSERT_EQ(0, ::listen(srv, 1));
  13176. std::atomic<size_t> server_body_bytes{0};
  13177. auto server_thread = std::thread([&] {
  13178. sockaddr_in cli_addr{};
  13179. socklen_t cli_len = sizeof(cli_addr);
  13180. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13181. if (cli == INVALID_SOCKET) { return; }
  13182. // Bound the lifetime of the server side so a buggy client (which never
  13183. // sends the body) cannot make this thread block forever on join.
  13184. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13185. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13186. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13187. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13188. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13189. SSL *ssl = SSL_new(ctx);
  13190. SSL_set_fd(ssl, static_cast<int>(cli));
  13191. if (SSL_accept(ssl) > 0) {
  13192. // Read the request headers. Reading here also flushes the TLS 1.3
  13193. // session tickets to the client. Deliberately do NOT send
  13194. // `100 Continue`.
  13195. std::string buf;
  13196. char tmp[1024];
  13197. while (buf.find("\r\n\r\n") == std::string::npos) {
  13198. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13199. if (n <= 0) { break; }
  13200. buf.append(tmp, static_cast<size_t>(n));
  13201. }
  13202. // A correct client sends the body now; count what arrives.
  13203. auto pos = buf.find("\r\n\r\n");
  13204. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13205. while (body < 4096) {
  13206. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13207. if (n <= 0) { break; }
  13208. body += static_cast<size_t>(n);
  13209. }
  13210. server_body_bytes = body;
  13211. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13212. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13213. SSL_shutdown(ssl);
  13214. }
  13215. SSL_free(ssl);
  13216. detail::close_socket(cli);
  13217. SSL_CTX_free(ctx);
  13218. });
  13219. auto se = detail::scope_exit([&] {
  13220. server_thread.join();
  13221. detail::close_socket(srv);
  13222. });
  13223. SSLClient cli("127.0.0.1", port);
  13224. cli.enable_server_certificate_verification(false);
  13225. cli.set_connection_timeout(5, 0);
  13226. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13227. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13228. std::string body(4096, 'A');
  13229. auto res = cli.Put("/api/test", body, "application/json");
  13230. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13231. EXPECT_EQ(StatusCode::OK_200, res->status);
  13232. EXPECT_EQ(body.size(), server_body_bytes.load());
  13233. }
  13234. #endif
  13235. template <typename S, typename C>
  13236. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13237. svr.Get("/stream", [&](const Request &, Response &res) {
  13238. auto data = new std::string("01234567890123456789");
  13239. res.set_content_provider(
  13240. data->size(), "text/plain",
  13241. [&, data](size_t offset, size_t length, DataSink &sink) {
  13242. const size_t DATA_CHUNK_SIZE = 4;
  13243. const auto &d = *data;
  13244. std::this_thread::sleep_for(std::chrono::seconds(1));
  13245. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13246. return true;
  13247. },
  13248. [data](bool success) {
  13249. EXPECT_FALSE(success);
  13250. delete data;
  13251. });
  13252. });
  13253. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13254. auto i = new size_t(0);
  13255. res.set_content_provider(
  13256. "text/plain",
  13257. [i](size_t, DataSink &sink) {
  13258. if (*i < 5) {
  13259. std::this_thread::sleep_for(std::chrono::seconds(1));
  13260. sink.write("abcd", 4);
  13261. (*i)++;
  13262. } else {
  13263. sink.done();
  13264. }
  13265. return true;
  13266. },
  13267. [i](bool success) {
  13268. EXPECT_FALSE(success);
  13269. delete i;
  13270. });
  13271. });
  13272. svr.Get("/chunked", [&](const Request &, Response &res) {
  13273. auto i = new size_t(0);
  13274. res.set_chunked_content_provider(
  13275. "text/plain",
  13276. [i](size_t, DataSink &sink) {
  13277. if (*i < 5) {
  13278. std::this_thread::sleep_for(std::chrono::seconds(1));
  13279. sink.os << "abcd";
  13280. (*i)++;
  13281. } else {
  13282. sink.done();
  13283. }
  13284. return true;
  13285. },
  13286. [i](bool success) {
  13287. EXPECT_FALSE(success);
  13288. delete i;
  13289. });
  13290. });
  13291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13292. auto se = detail::scope_exit([&] {
  13293. svr.stop();
  13294. listen_thread.join();
  13295. ASSERT_FALSE(svr.is_running());
  13296. });
  13297. svr.wait_until_ready();
  13298. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13299. {
  13300. auto start = std::chrono::steady_clock::now();
  13301. auto res = cli.Get("/stream");
  13302. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13303. std::chrono::steady_clock::now() - start)
  13304. .count();
  13305. ASSERT_FALSE(res);
  13306. EXPECT_EQ(Error::Read, res.error());
  13307. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13308. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13309. }
  13310. {
  13311. auto start = std::chrono::steady_clock::now();
  13312. auto res = cli.Get("/stream_without_length");
  13313. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13314. std::chrono::steady_clock::now() - start)
  13315. .count();
  13316. ASSERT_FALSE(res);
  13317. EXPECT_EQ(Error::Read, res.error());
  13318. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13319. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13320. }
  13321. {
  13322. auto start = std::chrono::steady_clock::now();
  13323. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13324. EXPECT_EQ("abcd", string(data, data_length));
  13325. return true;
  13326. });
  13327. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13328. std::chrono::steady_clock::now() - start)
  13329. .count();
  13330. ASSERT_FALSE(res);
  13331. EXPECT_EQ(Error::Read, res.error());
  13332. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13333. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13334. }
  13335. }
  13336. TEST(MaxTimeoutTest, ContentStream) {
  13337. time_t timeout = 2000;
  13338. time_t threshold = 200;
  13339. Server svr;
  13340. Client cli("localhost", PORT);
  13341. max_timeout_test(svr, cli, timeout, threshold);
  13342. }
  13343. #ifdef CPPHTTPLIB_SSL_ENABLED
  13344. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13345. time_t timeout = 2000;
  13346. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13348. SSLClient cli("localhost", PORT);
  13349. cli.enable_server_certificate_verification(false);
  13350. max_timeout_test(svr, cli, timeout, threshold);
  13351. }
  13352. #endif
  13353. class EventDispatcher {
  13354. public:
  13355. EventDispatcher() {}
  13356. bool wait_event(DataSink *sink) {
  13357. unique_lock<mutex> lk(m_);
  13358. int id = id_;
  13359. // Wait with timeout to prevent hanging if client disconnects
  13360. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13361. [&] { return cid_ == id; })) {
  13362. return false; // Timeout occurred
  13363. }
  13364. sink->write(message_.data(), message_.size());
  13365. return true;
  13366. }
  13367. void send_event(const string &message) {
  13368. lock_guard<mutex> lk(m_);
  13369. cid_ = id_++;
  13370. message_ = message;
  13371. cv_.notify_all();
  13372. }
  13373. private:
  13374. mutex m_;
  13375. condition_variable cv_;
  13376. atomic_int id_{0};
  13377. atomic_int cid_{-1};
  13378. string message_;
  13379. };
  13380. TEST(ClientInThreadTest, Issue2068) {
  13381. EventDispatcher ed;
  13382. Server svr;
  13383. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13384. res.set_chunked_content_provider("text/event-stream",
  13385. [&](size_t /*offset*/, DataSink &sink) {
  13386. return ed.wait_event(&sink);
  13387. });
  13388. });
  13389. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13390. svr.wait_until_ready();
  13391. thread event_thread([&] {
  13392. int id = 0;
  13393. while (svr.is_running()) {
  13394. this_thread::sleep_for(chrono::milliseconds(500));
  13395. std::stringstream ss;
  13396. ss << "data: " << id << "\n\n";
  13397. ed.send_event(ss.str());
  13398. id++;
  13399. }
  13400. });
  13401. auto se = detail::scope_exit([&] {
  13402. svr.stop();
  13403. listen_thread.join();
  13404. event_thread.join();
  13405. ASSERT_FALSE(svr.is_running());
  13406. });
  13407. {
  13408. auto client = detail::make_unique<Client>(HOST, PORT);
  13409. client->set_read_timeout(std::chrono::minutes(10));
  13410. std::atomic<bool> stop{false};
  13411. std::thread t([&] {
  13412. client->Get("/event1",
  13413. [&](const char *, size_t) -> bool { return !stop; });
  13414. });
  13415. std::this_thread::sleep_for(std::chrono::seconds(2));
  13416. stop = true;
  13417. client->stop();
  13418. t.join();
  13419. // Reset client after thread has finished
  13420. client.reset();
  13421. }
  13422. }
  13423. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13424. auto handled = false;
  13425. Server svr;
  13426. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13427. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13428. auto se = detail::scope_exit([&] {
  13429. svr.stop();
  13430. t.join();
  13431. ASSERT_FALSE(svr.is_running());
  13432. ASSERT_FALSE(handled);
  13433. });
  13434. svr.wait_until_ready();
  13435. // Two Content-Length headers with different values — must be rejected
  13436. auto req = "POST /test HTTP/1.1\r\n"
  13437. "Content-Length: 5\r\n"
  13438. "Content-Length: 10\r\n"
  13439. "\r\n"
  13440. "hello";
  13441. std::string response;
  13442. ASSERT_TRUE(send_request(1, req, &response));
  13443. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13444. response.substr(0, response.find("\r\n")));
  13445. }
  13446. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13447. auto handled = false;
  13448. Server svr;
  13449. svr.Post("/test", [&](const Request &, Response &res) {
  13450. handled = true;
  13451. res.set_content("ok", "text/plain");
  13452. });
  13453. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13454. auto se = detail::scope_exit([&] {
  13455. svr.stop();
  13456. t.join();
  13457. ASSERT_FALSE(svr.is_running());
  13458. ASSERT_TRUE(handled);
  13459. });
  13460. svr.wait_until_ready();
  13461. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13462. auto req = "POST /test HTTP/1.1\r\n"
  13463. "Content-Length: 5\r\n"
  13464. "Content-Length: 5\r\n"
  13465. "\r\n"
  13466. "hello";
  13467. std::string response;
  13468. ASSERT_TRUE(send_request(1, req, &response));
  13469. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13470. }
  13471. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13472. Server svr;
  13473. svr.Get("/", [](const Request &req, Response &res) {
  13474. EXPECT_EQ(2U, req.trailers.size());
  13475. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13476. // Denied
  13477. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13478. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13479. // Accepted
  13480. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13481. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13482. EXPECT_TRUE(req.has_trailer("X-World"));
  13483. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13484. res.set_content("ok", "text/plain");
  13485. });
  13486. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13487. auto se = detail::scope_exit([&] {
  13488. svr.stop();
  13489. t.join();
  13490. ASSERT_FALSE(svr.is_running());
  13491. });
  13492. svr.wait_until_ready();
  13493. const std::string req = "GET / HTTP/1.1\r\n"
  13494. "Transfer-Encoding: chunked\r\n"
  13495. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13496. "\r\n"
  13497. "0\r\n"
  13498. "Content-Length: 10\r\n"
  13499. "Host: internal.local\r\n"
  13500. "Content-Type: malicious/content\r\n"
  13501. "Cookie: any\r\n"
  13502. "Set-Cookie: any\r\n"
  13503. "X-Forwarded-For: attacker.com\r\n"
  13504. "X-Real-Ip: 1.1.1.1\r\n"
  13505. "X-Hello: hello\r\n"
  13506. "X-World: world\r\n"
  13507. "\r\n";
  13508. std::string res;
  13509. ASSERT_TRUE(send_request(1, req, &res));
  13510. }
  13511. // A direct client that is not listed in trusted_proxies must not be able to
  13512. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13513. // the peer address on the actual TCP connection determines whether the
  13514. // header is honored.
  13515. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13516. Server svr;
  13517. // Deliberately does NOT include the loopback address the test client
  13518. // actually connects from, so the direct connection is not a trusted proxy.
  13519. svr.set_trusted_proxies({"203.0.113.66"});
  13520. std::string observed_remote_addr;
  13521. svr.Get("/ip", [&](const Request &req, Response &res) {
  13522. observed_remote_addr = req.remote_addr;
  13523. res.set_content("ok", "text/plain");
  13524. });
  13525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. Client cli(HOST, PORT);
  13533. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. EXPECT_EQ(StatusCode::OK_200, res->status);
  13536. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13537. // ignored entirely and the real connection-level address retained.
  13538. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13539. observed_remote_addr == "127.0.0.1");
  13540. }
  13541. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13542. Server svr;
  13543. std::string observed_remote_addr;
  13544. std::string observed_xff;
  13545. svr.Get("/ip", [&](const Request &req, Response &res) {
  13546. observed_remote_addr = req.remote_addr;
  13547. observed_xff = req.get_header_value("X-Forwarded-For");
  13548. res.set_content("ok", "text/plain");
  13549. });
  13550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13551. auto se = detail::scope_exit([&] {
  13552. svr.stop();
  13553. t.join();
  13554. ASSERT_FALSE(svr.is_running());
  13555. });
  13556. svr.wait_until_ready();
  13557. Client cli(HOST, PORT);
  13558. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13560. EXPECT_EQ(StatusCode::OK_200, res->status);
  13561. EXPECT_EQ(observed_xff, "203.0.113.66");
  13562. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13563. observed_remote_addr == "127.0.0.1");
  13564. }
  13565. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13566. Server svr;
  13567. svr.set_trusted_proxies({"203.0.113.66"});
  13568. std::string observed_remote_addr;
  13569. std::string observed_xff;
  13570. svr.Get("/ip", [&](const Request &req, Response &res) {
  13571. observed_remote_addr = req.remote_addr;
  13572. observed_xff = req.get_header_value("X-Forwarded-For");
  13573. res.set_content("ok", "text/plain");
  13574. });
  13575. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13576. auto se = detail::scope_exit([&] {
  13577. svr.stop();
  13578. t.join();
  13579. ASSERT_FALSE(svr.is_running());
  13580. });
  13581. svr.wait_until_ready();
  13582. Client cli(HOST, PORT);
  13583. auto res = cli.Get("/ip");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. EXPECT_EQ(StatusCode::OK_200, res->status);
  13586. EXPECT_EQ(observed_xff, "");
  13587. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13588. observed_remote_addr == "127.0.0.1");
  13589. }
  13590. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13591. Server svr;
  13592. // Include the loopback address the test client actually connects from, so
  13593. // the direct connection itself is recognized as the trusted proxy hop.
  13594. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13595. std::string observed_remote_addr;
  13596. std::string observed_xff;
  13597. svr.Get("/ip", [&](const Request &req, Response &res) {
  13598. observed_remote_addr = req.remote_addr;
  13599. observed_xff = req.get_header_value("X-Forwarded-For");
  13600. res.set_content("ok", "text/plain");
  13601. });
  13602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13603. auto se = detail::scope_exit([&] {
  13604. svr.stop();
  13605. t.join();
  13606. ASSERT_FALSE(svr.is_running());
  13607. });
  13608. svr.wait_until_ready();
  13609. Client cli(HOST, PORT);
  13610. auto res = cli.Get(
  13611. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13613. EXPECT_EQ(StatusCode::OK_200, res->status);
  13614. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13615. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13616. }
  13617. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13618. Server svr;
  13619. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13620. std::string observed_remote_addr;
  13621. std::string observed_xff;
  13622. svr.Get("/ip", [&](const Request &req, Response &res) {
  13623. observed_remote_addr = req.remote_addr;
  13624. observed_xff = req.get_header_value("X-Forwarded-For");
  13625. res.set_content("ok", "text/plain");
  13626. });
  13627. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13628. auto se = detail::scope_exit([&] {
  13629. svr.stop();
  13630. t.join();
  13631. ASSERT_FALSE(svr.is_running());
  13632. });
  13633. svr.wait_until_ready();
  13634. Client cli(HOST, PORT);
  13635. auto res = cli.Get(
  13636. "/ip",
  13637. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13639. EXPECT_EQ(StatusCode::OK_200, res->status);
  13640. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13641. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13642. }
  13643. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13644. Server svr;
  13645. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13646. std::string observed_remote_addr;
  13647. std::string observed_xff;
  13648. svr.Get("/ip", [&](const Request &req, Response &res) {
  13649. observed_remote_addr = req.remote_addr;
  13650. observed_xff = req.get_header_value("X-Forwarded-For");
  13651. res.set_content("ok", "text/plain");
  13652. });
  13653. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13654. auto se = detail::scope_exit([&] {
  13655. svr.stop();
  13656. t.join();
  13657. ASSERT_FALSE(svr.is_running());
  13658. });
  13659. svr.wait_until_ready();
  13660. Client cli(HOST, PORT);
  13661. auto res = cli.Get(
  13662. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13664. EXPECT_EQ(StatusCode::OK_200, res->status);
  13665. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13666. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13667. // and must not be selected.
  13668. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13669. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13670. }
  13671. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13672. Server svr;
  13673. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13674. std::string observed_remote_addr;
  13675. svr.Get("/ip", [&](const Request &req, Response &res) {
  13676. observed_remote_addr = req.remote_addr;
  13677. res.set_content("ok", "text/plain");
  13678. });
  13679. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13680. auto se = detail::scope_exit([&] {
  13681. svr.stop();
  13682. t.join();
  13683. ASSERT_FALSE(svr.is_running());
  13684. });
  13685. svr.wait_until_ready();
  13686. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13687. // a forged address and the trusted proxy's own address; the forged value must
  13688. // not win over the address the trusted proxy actually recorded.
  13689. Client cli(HOST, PORT);
  13690. auto res = cli.Get(
  13691. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13693. EXPECT_EQ(StatusCode::OK_200, res->status);
  13694. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13695. }
  13696. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13697. Server svr;
  13698. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13699. std::string observed_remote_addr;
  13700. std::string observed_xff;
  13701. svr.Get("/ip", [&](const Request &req, Response &res) {
  13702. observed_remote_addr = req.remote_addr;
  13703. observed_xff = req.get_header_value("X-Forwarded-For");
  13704. res.set_content("ok", "text/plain");
  13705. });
  13706. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13707. auto se = detail::scope_exit([&] {
  13708. svr.stop();
  13709. t.join();
  13710. ASSERT_FALSE(svr.is_running());
  13711. });
  13712. svr.wait_until_ready();
  13713. Client cli(HOST, PORT);
  13714. auto res = cli.Get(
  13715. "/ip",
  13716. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. EXPECT_EQ(StatusCode::OK_200, res->status);
  13719. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13720. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13721. }
  13722. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13723. Server svr;
  13724. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13725. std::string observed_remote_addr;
  13726. std::string observed_xff;
  13727. svr.Get("/ip", [&](const Request &req, Response &res) {
  13728. observed_remote_addr = req.remote_addr;
  13729. observed_xff = req.get_header_value("X-Forwarded-For");
  13730. res.set_content("ok", "text/plain");
  13731. });
  13732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. ASSERT_FALSE(svr.is_running());
  13737. });
  13738. svr.wait_until_ready();
  13739. std::string raw_req =
  13740. "GET /ip HTTP/1.1\r\n"
  13741. "Host: localhost\r\n"
  13742. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13743. "Connection: close\r\n"
  13744. "\r\n";
  13745. std::string out;
  13746. ASSERT_TRUE(send_request(5, raw_req, &out));
  13747. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13748. // Header parser trims surrounding whitespace of the header value
  13749. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13750. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13751. }
  13752. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13753. // crash the server (it used to call front() on an empty vector inside
  13754. // get_client_ip). The connection-level remote address must be retained instead.
  13755. static void run_malformed_xff_test(const std::string &xff_value) {
  13756. Server svr;
  13757. svr.set_trusted_proxies({"192.0.2.45"});
  13758. std::string observed_remote_addr;
  13759. svr.Get("/ip", [&](const Request &req, Response &res) {
  13760. observed_remote_addr = req.remote_addr;
  13761. res.set_content("ok", "text/plain");
  13762. });
  13763. int port = 0;
  13764. thread t = thread([&]() {
  13765. port = svr.bind_to_any_port(HOST);
  13766. svr.listen_after_bind();
  13767. });
  13768. auto se = detail::scope_exit([&] {
  13769. svr.stop();
  13770. t.join();
  13771. ASSERT_FALSE(svr.is_running());
  13772. });
  13773. svr.wait_until_ready();
  13774. Client cli(HOST, port);
  13775. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13777. EXPECT_EQ(StatusCode::OK_200, res->status);
  13778. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13779. observed_remote_addr == "127.0.0.1");
  13780. }
  13781. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13782. run_malformed_xff_test("");
  13783. }
  13784. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13785. run_malformed_xff_test(",");
  13786. }
  13787. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13788. run_malformed_xff_test(", , ,");
  13789. }
  13790. #ifndef _WIN32
  13791. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13792. Server svr;
  13793. svr.Post("/post", [&](const Request &req, Response &res) {
  13794. res.set_content(req.body, "text/plain");
  13795. });
  13796. svr.Put("/put", [&](const Request &req, Response &res) {
  13797. res.set_content(req.body, "text/plain");
  13798. });
  13799. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13800. res.set_content(req.body, "text/plain");
  13801. });
  13802. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13803. res.set_content(req.body, "text/plain");
  13804. });
  13805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13806. auto se = detail::scope_exit([&] {
  13807. svr.stop();
  13808. t.join();
  13809. ASSERT_FALSE(svr.is_running());
  13810. });
  13811. svr.wait_until_ready();
  13812. std::string resp;
  13813. // POST without Content-Length
  13814. ASSERT_TRUE(send_request(5,
  13815. "POST /post HTTP/1.1\r\n"
  13816. "Host: localhost\r\n"
  13817. "Connection: close\r\n"
  13818. "\r\n",
  13819. &resp));
  13820. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13821. // PUT without Content-Length
  13822. resp.clear();
  13823. ASSERT_TRUE(send_request(5,
  13824. "PUT /put HTTP/1.1\r\n"
  13825. "Host: localhost\r\n"
  13826. "Connection: close\r\n"
  13827. "\r\n",
  13828. &resp));
  13829. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13830. // PATCH without Content-Length
  13831. resp.clear();
  13832. ASSERT_TRUE(send_request(5,
  13833. "PATCH /patch HTTP/1.1\r\n"
  13834. "Host: localhost\r\n"
  13835. "Connection: close\r\n"
  13836. "\r\n",
  13837. &resp));
  13838. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13839. // DELETE without Content-Length
  13840. resp.clear();
  13841. ASSERT_TRUE(send_request(5,
  13842. "DELETE /delete HTTP/1.1\r\n"
  13843. "Host: localhost\r\n"
  13844. "Connection: close\r\n"
  13845. "\r\n",
  13846. &resp));
  13847. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13848. }
  13849. #endif
  13850. //==============================================================================
  13851. // open_stream() Tests
  13852. //==============================================================================
  13853. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13854. std::string result;
  13855. char buf[8192];
  13856. ssize_t n;
  13857. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13858. result.append(buf, static_cast<size_t>(n));
  13859. }
  13860. return result;
  13861. }
  13862. // Mock stream for unit tests
  13863. class MockStream : public Stream {
  13864. public:
  13865. std::string data;
  13866. size_t pos = 0;
  13867. ssize_t error_after = -1; // -1 = no error
  13868. explicit MockStream(const std::string &d, ssize_t err = -1)
  13869. : data(d), error_after(err) {}
  13870. bool is_readable() const override { return true; }
  13871. bool wait_readable() const override { return true; }
  13872. bool wait_writable() const override { return true; }
  13873. ssize_t read(char *ptr, size_t size) override {
  13874. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13875. if (pos >= data.size()) return 0;
  13876. size_t limit =
  13877. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13878. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13879. std::memcpy(ptr, data.data() + pos, to_read);
  13880. pos += to_read;
  13881. return static_cast<ssize_t>(to_read);
  13882. }
  13883. ssize_t write(const char *, size_t) override { return -1; }
  13884. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13885. ip = "127.0.0.1";
  13886. port = 0;
  13887. }
  13888. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13889. ip = "127.0.0.1";
  13890. port = 0;
  13891. }
  13892. socket_t socket() const override { return INVALID_SOCKET; }
  13893. time_t duration() const override { return 0; }
  13894. };
  13895. TEST(StreamHandleTest, Basic) {
  13896. ClientImpl::StreamHandle handle;
  13897. EXPECT_FALSE(handle.is_valid());
  13898. handle.response = detail::make_unique<Response>();
  13899. handle.error = Error::Connection;
  13900. EXPECT_FALSE(handle.is_valid());
  13901. handle.error = Error::Success;
  13902. EXPECT_TRUE(handle.is_valid());
  13903. }
  13904. TEST(BodyReaderTest, Basic) {
  13905. MockStream stream("Hello, World!");
  13906. detail::BodyReader reader;
  13907. reader.stream = &stream;
  13908. reader.content_length = 13;
  13909. char buf[32];
  13910. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13911. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13912. EXPECT_TRUE(reader.eof);
  13913. }
  13914. TEST(BodyReaderTest, NoStream) {
  13915. detail::BodyReader reader;
  13916. char buf[32];
  13917. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13918. EXPECT_EQ(Error::Connection, reader.last_error);
  13919. }
  13920. TEST(BodyReaderTest, Error) {
  13921. MockStream stream("Hello, World!", 5);
  13922. detail::BodyReader reader;
  13923. reader.stream = &stream;
  13924. reader.content_length = 13;
  13925. char buf[32];
  13926. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13927. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13928. EXPECT_EQ(Error::Read, reader.last_error);
  13929. }
  13930. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13931. // Mock-based StreamHandle tests relying on private internals are removed.
  13932. class OpenStreamTest : public ::testing::Test {
  13933. protected:
  13934. void SetUp() override {
  13935. svr_.Get("/hello", [](const Request &, Response &res) {
  13936. res.set_content("Hello World!", "text/plain");
  13937. });
  13938. svr_.Get("/large", [](const Request &, Response &res) {
  13939. res.set_content(std::string(10000, 'X'), "text/plain");
  13940. });
  13941. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  13942. res.set_content("Hello World!", "image/jpeg");
  13943. res.set_header("Content-Encoding", "UTF-8");
  13944. });
  13945. svr_.Get("/chunked", [](const Request &, Response &res) {
  13946. res.set_chunked_content_provider("text/plain",
  13947. [](size_t offset, DataSink &sink) {
  13948. if (offset < 15) {
  13949. sink.write("chunk", 5);
  13950. return true;
  13951. }
  13952. sink.done();
  13953. return true;
  13954. });
  13955. });
  13956. svr_.Get("/compressible", [](const Request &, Response &res) {
  13957. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13958. DataSink &sink) {
  13959. if (offset < 100 * 1024) {
  13960. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13961. sink.write(chunk.data(), chunk.size());
  13962. return true;
  13963. }
  13964. sink.done();
  13965. return true;
  13966. });
  13967. });
  13968. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13969. [](const Request & /*req*/, Response &res) {
  13970. auto i = new int(0);
  13971. res.set_header("Trailer", "Content-Length, X-Allowed");
  13972. res.set_chunked_content_provider(
  13973. "text/plain",
  13974. [i](size_t /*offset*/, DataSink &sink) {
  13975. switch (*i) {
  13976. case 0: sink.os << "123"; break;
  13977. case 1: sink.os << "456"; break;
  13978. case 2: sink.os << "789"; break;
  13979. case 3: {
  13980. sink.done_with_trailer(
  13981. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13982. } break;
  13983. }
  13984. (*i)++;
  13985. return true;
  13986. },
  13987. [i](bool success) {
  13988. EXPECT_TRUE(success);
  13989. delete i;
  13990. });
  13991. });
  13992. // Echo headers endpoint for header-related tests
  13993. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13994. std::string body;
  13995. for (const auto &h : req.headers) {
  13996. body.append(h.first);
  13997. body.push_back(':');
  13998. body.append(h.second);
  13999. body.push_back('\n');
  14000. }
  14001. res.set_content(body, "text/plain");
  14002. });
  14003. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14004. std::string body;
  14005. for (const auto &h : req.headers) {
  14006. body.append(h.first);
  14007. body.push_back(':');
  14008. body.append(h.second);
  14009. body.push_back('\n');
  14010. }
  14011. res.set_content(body, "text/plain");
  14012. });
  14013. port_ = svr_.bind_to_any_port("127.0.0.1");
  14014. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14015. svr_.wait_until_ready();
  14016. }
  14017. void TearDown() override {
  14018. svr_.stop();
  14019. if (thread_.joinable()) thread_.join();
  14020. }
  14021. Server svr_;
  14022. std::thread thread_;
  14023. int port_ = 0;
  14024. };
  14025. TEST_F(OpenStreamTest, Basic) {
  14026. Client cli("127.0.0.1", port_);
  14027. auto handle = cli.open_stream("GET", "/hello");
  14028. EXPECT_TRUE(handle.is_valid());
  14029. EXPECT_EQ("Hello World!", read_all(handle));
  14030. }
  14031. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14032. Client cli("127.0.0.1", port_);
  14033. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14034. ASSERT_TRUE(handle.is_valid());
  14035. EXPECT_EQ("Hello World!", read_all(handle));
  14036. }
  14037. TEST_F(OpenStreamTest, SmallBuffer) {
  14038. Client cli("127.0.0.1", port_);
  14039. auto handle = cli.open_stream("GET", "/hello");
  14040. std::string result;
  14041. char buf[4];
  14042. ssize_t n;
  14043. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14044. result.append(buf, static_cast<size_t>(n));
  14045. EXPECT_EQ("Hello World!", result);
  14046. }
  14047. TEST_F(OpenStreamTest, DefaultHeaders) {
  14048. Client cli("127.0.0.1", port_);
  14049. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14050. {
  14051. auto handle = cli.open_stream("GET", "/echo-headers");
  14052. ASSERT_TRUE(handle.is_valid());
  14053. auto body = read_all(handle);
  14054. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14055. std::string::npos);
  14056. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14057. std::string::npos);
  14058. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14059. }
  14060. // open_stream POST with body and no explicit content_type should NOT add
  14061. // text/plain Content-Type (behavior differs from non-streaming path), but
  14062. // should include Content-Length
  14063. {
  14064. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14065. ASSERT_TRUE(handle.is_valid());
  14066. auto body = read_all(handle);
  14067. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14068. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14069. }
  14070. // open_stream POST with explicit Content-Type should preserve it
  14071. {
  14072. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14073. {{"Content-Type", "application/custom"}},
  14074. "{}", "application/custom");
  14075. ASSERT_TRUE(handle.is_valid());
  14076. auto body = read_all(handle);
  14077. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14078. }
  14079. // User-specified User-Agent must not be overwritten for stream API
  14080. {
  14081. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14082. {{"User-Agent", "MyAgent/1.2"}});
  14083. ASSERT_TRUE(handle.is_valid());
  14084. auto body = read_all(handle);
  14085. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14086. }
  14087. }
  14088. TEST_F(OpenStreamTest, Large) {
  14089. Client cli("127.0.0.1", port_);
  14090. auto handle = cli.open_stream("GET", "/large");
  14091. EXPECT_EQ(10000u, read_all(handle).size());
  14092. }
  14093. TEST_F(OpenStreamTest, ConnectionError) {
  14094. Client cli("127.0.0.1", 9999);
  14095. auto handle = cli.open_stream("GET", "/hello");
  14096. EXPECT_FALSE(handle.is_valid());
  14097. }
  14098. TEST_F(OpenStreamTest, Chunked) {
  14099. Client cli("127.0.0.1", port_);
  14100. auto handle = cli.open_stream("GET", "/chunked");
  14101. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14102. "Transfer-Encoding") == "chunked");
  14103. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14104. }
  14105. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14106. Client cli("127.0.0.1", port_);
  14107. auto handle =
  14108. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14109. ASSERT_TRUE(handle.is_valid());
  14110. // Consume body to allow trailers to be received/parsed
  14111. auto body = read_all(handle);
  14112. // Explicitly parse trailers (ensure trailers are available for assertion)
  14113. handle.parse_trailers_if_needed();
  14114. EXPECT_EQ(std::string("123456789"), body);
  14115. // The response should include a Trailer header declaring both names
  14116. ASSERT_TRUE(handle.response);
  14117. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14118. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14119. handle.response->get_header_value("Trailer"));
  14120. // Prohibited trailer must not be present
  14121. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14122. // Allowed trailer should be present
  14123. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14124. EXPECT_EQ(std::string("yes"),
  14125. handle.response->get_trailer_value("X-Allowed"));
  14126. // Verify trailers are NOT present as regular headers
  14127. EXPECT_EQ(std::string(""),
  14128. handle.response->get_header_value("Content-Length"));
  14129. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14130. }
  14131. static std::thread serve_single_response(std::promise<int> &port_promise,
  14132. const std::string &response) {
  14133. return std::thread([&port_promise, response] {
  14134. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14135. default_socket_options(srv);
  14136. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14137. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14138. sockaddr_in addr{};
  14139. addr.sin_family = AF_INET;
  14140. addr.sin_port = htons(0); // Let OS assign a free port
  14141. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14142. int opt = 1;
  14143. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14144. #ifdef _WIN32
  14145. reinterpret_cast<const char *>(&opt),
  14146. #else
  14147. &opt,
  14148. #endif
  14149. sizeof(opt));
  14150. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14151. ::listen(srv, 1) != 0) {
  14152. port_promise.set_value(-1);
  14153. detail::close_socket(srv);
  14154. return;
  14155. }
  14156. socklen_t addr_len = sizeof(addr);
  14157. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14158. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14159. sockaddr_in cli_addr{};
  14160. socklen_t cli_len = sizeof(cli_addr);
  14161. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14162. if (cli != INVALID_SOCKET) {
  14163. // Read the complete HTTP request (until the blank line that terminates
  14164. // headers) before sending the response. If the server closes the socket
  14165. // while the client's request data is still unread in the kernel receive
  14166. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14167. // connection on both sides: it discards the client's receive buffer
  14168. // (which already holds our response) and causes any in-progress write on
  14169. // the client to fail with ECONNRESET. Reading all request data first
  14170. // ensures close() emits a graceful FIN.
  14171. {
  14172. char rbuf[256];
  14173. std::string req;
  14174. while (req.find("\r\n\r\n") == std::string::npos) {
  14175. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14176. if (n <= 0) { break; }
  14177. req.append(rbuf, static_cast<size_t>(n));
  14178. }
  14179. }
  14180. ::send(cli,
  14181. #ifdef _WIN32
  14182. static_cast<const char *>(response.c_str()),
  14183. static_cast<int>(response.size()),
  14184. #else
  14185. response.c_str(), response.size(),
  14186. #endif
  14187. 0);
  14188. detail::close_socket(cli);
  14189. }
  14190. detail::close_socket(srv);
  14191. });
  14192. }
  14193. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14194. #ifndef _WIN32
  14195. signal(SIGPIPE, SIG_IGN);
  14196. #endif
  14197. std::promise<int> port_promise;
  14198. auto port_future = port_promise.get_future();
  14199. auto server_thread =
  14200. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14201. "Content-Type: text/plain\r\n"
  14202. "Content-Length: not-a-number\r\n"
  14203. "Connection: close\r\n"
  14204. "\r\n"
  14205. "hello");
  14206. auto port = port_future.get();
  14207. ASSERT_GT(port, 0);
  14208. Client cli("127.0.0.1", port);
  14209. auto handle = cli.open_stream("GET", "/");
  14210. EXPECT_FALSE(handle.is_valid());
  14211. server_thread.join();
  14212. }
  14213. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14214. #ifndef _WIN32
  14215. signal(SIGPIPE, SIG_IGN);
  14216. #endif
  14217. std::promise<int> port_promise;
  14218. auto port_future = port_promise.get_future();
  14219. auto server_thread = serve_single_response(
  14220. port_promise, "HTTP/1.1 200 OK\r\n"
  14221. "Content-Type: text/plain\r\n"
  14222. "Content-Length: 99999999999999999999999999\r\n"
  14223. "Connection: close\r\n"
  14224. "\r\n"
  14225. "hello");
  14226. auto port = port_future.get();
  14227. ASSERT_GT(port, 0);
  14228. // Historically std::stoull would throw std::out_of_range here and crash
  14229. // the process, then parsing silently clamped to a bogus framing length and
  14230. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14231. // so the stream fails to open, matching the not-a-number case above. The
  14232. // process still must NOT terminate.
  14233. Client cli("127.0.0.1", port);
  14234. auto handle = cli.open_stream("GET", "/");
  14235. EXPECT_FALSE(handle.is_valid());
  14236. server_thread.join();
  14237. }
  14238. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14239. TEST_F(OpenStreamTest, Gzip) {
  14240. Client cli("127.0.0.1", port_);
  14241. auto handle = cli.open_stream("GET", "/compressible", {},
  14242. {{"Accept-Encoding", "gzip"}});
  14243. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14244. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14245. }
  14246. #endif
  14247. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14248. TEST_F(OpenStreamTest, Brotli) {
  14249. Client cli("127.0.0.1", port_);
  14250. auto handle =
  14251. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14252. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14253. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14254. }
  14255. #endif
  14256. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14257. TEST_F(OpenStreamTest, Zstd) {
  14258. Client cli("127.0.0.1", port_);
  14259. auto handle = cli.open_stream("GET", "/compressible", {},
  14260. {{"Accept-Encoding", "zstd"}});
  14261. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14262. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14263. }
  14264. #endif
  14265. #ifdef CPPHTTPLIB_SSL_ENABLED
  14266. class SSLOpenStreamTest : public ::testing::Test {
  14267. protected:
  14268. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14269. void SetUp() override {
  14270. svr_.Get("/hello", [](const Request &, Response &res) {
  14271. res.set_content("Hello SSL World!", "text/plain");
  14272. });
  14273. svr_.Get("/chunked", [](const Request &, Response &res) {
  14274. res.set_chunked_content_provider("text/plain",
  14275. [](size_t offset, DataSink &sink) {
  14276. if (offset < 15) {
  14277. sink.write("chunk", 5);
  14278. return true;
  14279. }
  14280. sink.done();
  14281. return true;
  14282. });
  14283. });
  14284. svr_.Post("/echo", [](const Request &req, Response &res) {
  14285. res.set_content(req.body, req.get_header_value("Content-Type"));
  14286. });
  14287. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14288. std::string body = req.body;
  14289. res.set_chunked_content_provider(
  14290. "text/plain", [body](size_t offset, DataSink &sink) {
  14291. if (offset < body.size()) {
  14292. sink.write(body.data() + offset, body.size() - offset);
  14293. }
  14294. sink.done();
  14295. return true;
  14296. });
  14297. });
  14298. port_ = svr_.bind_to_any_port("127.0.0.1");
  14299. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14300. svr_.wait_until_ready();
  14301. }
  14302. void TearDown() override {
  14303. svr_.stop();
  14304. if (thread_.joinable()) thread_.join();
  14305. }
  14306. SSLServer svr_;
  14307. std::thread thread_;
  14308. int port_ = 0;
  14309. };
  14310. TEST_F(SSLOpenStreamTest, Basic) {
  14311. SSLClient cli("127.0.0.1", port_);
  14312. cli.enable_server_certificate_verification(false);
  14313. auto handle = cli.open_stream("GET", "/hello");
  14314. ASSERT_TRUE(handle.is_valid());
  14315. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14316. }
  14317. TEST_F(SSLOpenStreamTest, Chunked) {
  14318. SSLClient cli("127.0.0.1", port_);
  14319. cli.enable_server_certificate_verification(false);
  14320. auto handle = cli.open_stream("GET", "/chunked");
  14321. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14322. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14323. "Transfer-Encoding") == "chunked");
  14324. auto body = read_all(handle);
  14325. EXPECT_EQ("chunkchunkchunk", body);
  14326. }
  14327. TEST_F(SSLOpenStreamTest, Post) {
  14328. SSLClient cli("127.0.0.1", port_);
  14329. cli.enable_server_certificate_verification(false);
  14330. auto handle =
  14331. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14332. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14333. EXPECT_EQ(200, handle.response->status);
  14334. auto body = read_all(handle);
  14335. EXPECT_EQ("Hello SSL POST", body);
  14336. }
  14337. TEST_F(SSLOpenStreamTest, PostChunked) {
  14338. SSLClient cli("127.0.0.1", port_);
  14339. cli.enable_server_certificate_verification(false);
  14340. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14341. "Chunked SSL Data", "text/plain");
  14342. ASSERT_TRUE(handle.is_valid());
  14343. EXPECT_EQ(200, handle.response->status);
  14344. auto body = read_all(handle);
  14345. EXPECT_EQ("Chunked SSL Data", body);
  14346. }
  14347. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14348. // Content-Length is terminated by the server closing the connection. When the
  14349. // SSL peer sends a close_notify after the body, the client must treat it as a
  14350. // clean EOF and return a successful response rather than an error.
  14351. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14353. ASSERT_TRUE(svr.is_valid());
  14354. svr.set_keep_alive_max_count(1);
  14355. const std::string expected_body = "Hello from connection-close response!";
  14356. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14357. res.set_content_provider("text/plain",
  14358. [&](size_t offset, DataSink &sink) -> bool {
  14359. if (offset < expected_body.size()) {
  14360. sink.write(expected_body.data() + offset,
  14361. expected_body.size() - offset);
  14362. }
  14363. sink.done();
  14364. return true;
  14365. });
  14366. });
  14367. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14368. auto se = detail::scope_exit([&] {
  14369. svr.stop();
  14370. listen_thread.join();
  14371. ASSERT_FALSE(svr.is_running());
  14372. });
  14373. svr.wait_until_ready();
  14374. SSLClient cli(HOST, PORT);
  14375. cli.enable_server_certificate_verification(false);
  14376. auto res = cli.Get("/no-content-length");
  14377. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::OK_200, res->status);
  14379. EXPECT_EQ(expected_body, res->body);
  14380. }
  14381. #endif // CPPHTTPLIB_SSL_ENABLED
  14382. //==============================================================================
  14383. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14384. // results for various scenarios.
  14385. //==============================================================================
  14386. TEST(ParityTest, GetVsOpenStream) {
  14387. Server svr;
  14388. const std::string path = "/parity";
  14389. const std::string content = "Parity test content: hello world";
  14390. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14391. res.set_content(content, "text/plain");
  14392. });
  14393. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14394. auto se = detail::scope_exit([&] {
  14395. svr.stop();
  14396. t.join();
  14397. ASSERT_FALSE(svr.is_running());
  14398. });
  14399. svr.wait_until_ready();
  14400. Client cli(HOST, PORT);
  14401. // Non-stream path
  14402. auto r1 = cli.Get(path);
  14403. ASSERT_TRUE(r1);
  14404. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14405. // Stream path
  14406. auto h = cli.open_stream("GET", path);
  14407. ASSERT_TRUE(h.is_valid());
  14408. EXPECT_EQ(r1->body, read_all(h));
  14409. }
  14410. // Helper to compress data with provided compressor type T
  14411. template <typename Compressor>
  14412. static std::string compress_payload_for_parity(const std::string &in) {
  14413. std::string out;
  14414. Compressor compressor;
  14415. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14416. [&](const char *data, size_t n) {
  14417. out.append(data, n);
  14418. return true;
  14419. });
  14420. EXPECT_TRUE(ok);
  14421. return out;
  14422. }
  14423. // Helper function for compression parity tests
  14424. template <typename Compressor>
  14425. static void test_compression_parity(const std::string &original,
  14426. const std::string &path,
  14427. const std::string &encoding) {
  14428. const std::string compressed =
  14429. compress_payload_for_parity<Compressor>(original);
  14430. Server svr;
  14431. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14432. res.set_content(compressed, "application/octet-stream");
  14433. res.set_header("Content-Encoding", encoding);
  14434. });
  14435. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. ASSERT_FALSE(svr.is_running());
  14440. });
  14441. svr.wait_until_ready();
  14442. Client cli(HOST, PORT);
  14443. // Non-streaming
  14444. {
  14445. auto res = cli.Get(path);
  14446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14447. EXPECT_EQ(StatusCode::OK_200, res->status);
  14448. EXPECT_EQ(original, res->body);
  14449. }
  14450. // Streaming
  14451. {
  14452. auto h = cli.open_stream("GET", path);
  14453. ASSERT_TRUE(h.is_valid());
  14454. EXPECT_EQ(original, read_all(h));
  14455. }
  14456. }
  14457. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14458. TEST(ParityTest, Gzip) {
  14459. test_compression_parity<detail::gzip_compressor>(
  14460. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14461. }
  14462. #endif
  14463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14464. TEST(ParityTest, Brotli) {
  14465. test_compression_parity<detail::brotli_compressor>(
  14466. "Hello, brotli parity test payload", "/parity-br", "br");
  14467. }
  14468. #endif
  14469. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14470. TEST(ParityTest, Zstd) {
  14471. test_compression_parity<detail::zstd_compressor>(
  14472. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14473. }
  14474. #endif
  14475. //==============================================================================
  14476. // New Stream API Tests
  14477. //==============================================================================
  14478. inline std::string read_body(httplib::stream::Result &result) {
  14479. std::string body;
  14480. while (result.next()) {
  14481. body.append(result.data(), result.size());
  14482. }
  14483. return body;
  14484. }
  14485. TEST(ClientConnectionTest, Basic) {
  14486. httplib::ClientConnection conn;
  14487. EXPECT_FALSE(conn.is_open());
  14488. conn.sock = 1;
  14489. EXPECT_TRUE(conn.is_open());
  14490. httplib::ClientConnection conn2(std::move(conn));
  14491. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14492. conn2.sock = INVALID_SOCKET;
  14493. }
  14494. // Unified test server for all stream::* tests
  14495. class StreamApiTest : public ::testing::Test {
  14496. protected:
  14497. void SetUp() override {
  14498. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14499. res.set_content("Hello World!", "text/plain");
  14500. });
  14501. svr_.Get("/echo-params",
  14502. [](const httplib::Request &req, httplib::Response &res) {
  14503. std::string r;
  14504. for (const auto &p : req.params) {
  14505. if (!r.empty()) r += "&";
  14506. r += p.first + "=" + p.second;
  14507. }
  14508. res.set_content(r, "text/plain");
  14509. });
  14510. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14511. res.set_content(req.body, req.get_header_value("Content-Type"));
  14512. });
  14513. svr_.Post("/echo-headers",
  14514. [](const httplib::Request &req, httplib::Response &res) {
  14515. std::string r;
  14516. for (const auto &h : req.headers)
  14517. r += h.first + ": " + h.second + "\n";
  14518. res.set_content(r, "text/plain");
  14519. });
  14520. svr_.Post("/echo-params",
  14521. [](const httplib::Request &req, httplib::Response &res) {
  14522. std::string r = "params:";
  14523. for (const auto &p : req.params)
  14524. r += p.first + "=" + p.second + ";";
  14525. res.set_content(r + " body:" + req.body, "text/plain");
  14526. });
  14527. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14528. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14529. });
  14530. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14531. res.set_content("PUT:" + req.body, "text/plain");
  14532. });
  14533. svr_.Patch("/echo",
  14534. [](const httplib::Request &req, httplib::Response &res) {
  14535. res.set_content("PATCH:" + req.body, "text/plain");
  14536. });
  14537. svr_.Delete(
  14538. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14539. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14540. "text/plain");
  14541. });
  14542. svr_.Get("/head-test",
  14543. [](const httplib::Request &, httplib::Response &res) {
  14544. res.set_content("body for HEAD", "text/plain");
  14545. });
  14546. svr_.Options("/options",
  14547. [](const httplib::Request &, httplib::Response &res) {
  14548. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14549. });
  14550. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14551. svr_.wait_until_ready();
  14552. }
  14553. void TearDown() override {
  14554. svr_.stop();
  14555. if (thread_.joinable()) thread_.join();
  14556. }
  14557. httplib::Server svr_;
  14558. std::thread thread_;
  14559. };
  14560. // stream::Get tests
  14561. TEST_F(StreamApiTest, GetBasic) {
  14562. httplib::Client cli(HOST, PORT);
  14563. auto result = httplib::stream::Get(cli, "/hello");
  14564. ASSERT_TRUE(result.is_valid());
  14565. EXPECT_EQ(200, result.status());
  14566. EXPECT_EQ("Hello World!", read_body(result));
  14567. }
  14568. TEST_F(StreamApiTest, GetWithParams) {
  14569. httplib::Client cli(HOST, PORT);
  14570. httplib::Params params{{"foo", "bar"}};
  14571. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14572. ASSERT_TRUE(result.is_valid());
  14573. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14574. }
  14575. TEST_F(StreamApiTest, GetConnectionError) {
  14576. httplib::Client cli(HOST, 9999);
  14577. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14578. }
  14579. TEST_F(StreamApiTest, Get404) {
  14580. httplib::Client cli(HOST, PORT);
  14581. auto result = httplib::stream::Get(cli, "/nonexistent");
  14582. EXPECT_TRUE(result.is_valid());
  14583. EXPECT_EQ(404, result.status());
  14584. }
  14585. // stream::Post tests
  14586. TEST_F(StreamApiTest, PostBasic) {
  14587. httplib::Client cli(HOST, PORT);
  14588. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14589. "application/json");
  14590. ASSERT_TRUE(result.is_valid());
  14591. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14592. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14593. }
  14594. TEST_F(StreamApiTest, PostWithHeaders) {
  14595. httplib::Client cli(HOST, PORT);
  14596. httplib::Headers headers{{"X-Custom", "value"}};
  14597. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14598. "text/plain");
  14599. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14600. }
  14601. TEST_F(StreamApiTest, PostWithParams) {
  14602. httplib::Client cli(HOST, PORT);
  14603. httplib::Params params{{"k", "v"}};
  14604. auto result =
  14605. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14606. auto body = read_body(result);
  14607. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14608. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14609. }
  14610. TEST_F(StreamApiTest, PostLarge) {
  14611. httplib::Client cli(HOST, PORT);
  14612. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14613. size_t total = 0;
  14614. while (result.next()) {
  14615. total += result.size();
  14616. }
  14617. EXPECT_EQ(100u * 1024u, total);
  14618. }
  14619. // stream::Put/Patch tests
  14620. TEST_F(StreamApiTest, PutAndPatch) {
  14621. httplib::Client cli(HOST, PORT);
  14622. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14623. EXPECT_EQ("PUT:test", read_body(put));
  14624. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14625. EXPECT_EQ("PATCH:test", read_body(patch));
  14626. }
  14627. // stream::Delete tests
  14628. TEST_F(StreamApiTest, Delete) {
  14629. httplib::Client cli(HOST, PORT);
  14630. auto del1 = httplib::stream::Delete(cli, "/resource");
  14631. EXPECT_EQ("Deleted", read_body(del1));
  14632. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14633. EXPECT_EQ("Deleted:data", read_body(del2));
  14634. }
  14635. // stream::Head/Options tests
  14636. TEST_F(StreamApiTest, HeadAndOptions) {
  14637. httplib::Client cli(HOST, PORT);
  14638. auto head = httplib::stream::Head(cli, "/head-test");
  14639. EXPECT_TRUE(head.is_valid());
  14640. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14641. auto opts = httplib::stream::Options(cli, "/options");
  14642. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14643. }
  14644. // SSL stream::* tests
  14645. #ifdef CPPHTTPLIB_SSL_ENABLED
  14646. class SSLStreamApiTest : public ::testing::Test {
  14647. protected:
  14648. void SetUp() override {
  14649. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14650. res.set_content("Hello SSL!", "text/plain");
  14651. });
  14652. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14653. res.set_content(req.body, "text/plain");
  14654. });
  14655. port_ = svr_.bind_to_any_port("127.0.0.1");
  14656. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14657. svr_.wait_until_ready();
  14658. }
  14659. void TearDown() override {
  14660. svr_.stop();
  14661. if (thread_.joinable()) thread_.join();
  14662. }
  14663. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14664. std::thread thread_;
  14665. int port_ = 0;
  14666. };
  14667. TEST_F(SSLStreamApiTest, GetAndPost) {
  14668. httplib::SSLClient cli("127.0.0.1", port_);
  14669. cli.enable_server_certificate_verification(false);
  14670. auto get = httplib::stream::Get(cli, "/hello");
  14671. EXPECT_EQ("Hello SSL!", read_body(get));
  14672. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14673. EXPECT_EQ("test", read_body(post));
  14674. }
  14675. #endif
  14676. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14677. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14678. // BodyReader
  14679. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14680. // Test that read timeout during streaming is detected
  14681. // Use a large content-length response where server delays mid-stream
  14682. Server svr;
  14683. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14684. // Send a large response with delay in the middle
  14685. res.set_content_provider(
  14686. 1000, // content_length
  14687. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14688. if (offset < 100) {
  14689. // Send first 100 bytes immediately
  14690. std::string data(100, 'A');
  14691. sink.write(data.c_str(), data.size());
  14692. return true;
  14693. }
  14694. // Then delay longer than client timeout
  14695. std::this_thread::sleep_for(std::chrono::seconds(3));
  14696. std::string data(900, 'B');
  14697. sink.write(data.c_str(), data.size());
  14698. return true;
  14699. });
  14700. });
  14701. auto port = 8091;
  14702. std::thread t([&]() { svr.listen("localhost", port); });
  14703. svr.wait_until_ready();
  14704. Client cli("localhost", port);
  14705. cli.set_read_timeout(1, 0); // 1 second timeout
  14706. auto handle = cli.open_stream("GET", "/slow-stream");
  14707. ASSERT_TRUE(handle.is_valid());
  14708. char buf[256];
  14709. ssize_t total = 0;
  14710. ssize_t n;
  14711. bool got_error = false;
  14712. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14713. total += n;
  14714. }
  14715. if (n < 0) {
  14716. got_error = true;
  14717. // Should be timeout or read error
  14718. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14719. handle.get_read_error() == Error::Read)
  14720. << "Actual error: " << to_string(handle.get_read_error());
  14721. }
  14722. // Either we got an error, or we got less data than expected
  14723. EXPECT_TRUE(got_error || total < 1000)
  14724. << "Expected timeout but got all " << total << " bytes";
  14725. svr.stop();
  14726. t.join();
  14727. }
  14728. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14729. // Test connection closed detection via BodyReader
  14730. Server svr;
  14731. std::atomic<bool> close_now{false};
  14732. svr.Get("/will-close", [&](const Request &, Response &res) {
  14733. res.set_content_provider(
  14734. 10000, // Large content_length that we won't fully send
  14735. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14736. if (offset < 100) {
  14737. std::string data(100, 'X');
  14738. sink.write(data.c_str(), data.size());
  14739. return true;
  14740. }
  14741. // Wait for signal then abort
  14742. while (!close_now) {
  14743. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14744. }
  14745. return false; // Abort - server will close connection
  14746. });
  14747. });
  14748. auto port = 8092;
  14749. std::thread t([&]() { svr.listen("localhost", port); });
  14750. svr.wait_until_ready();
  14751. Client cli("localhost", port);
  14752. auto handle = cli.open_stream("GET", "/will-close");
  14753. ASSERT_TRUE(handle.is_valid());
  14754. char buf[256];
  14755. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14756. EXPECT_GT(n, 0) << "First read should succeed";
  14757. // Signal server to close
  14758. close_now = true;
  14759. // Keep reading until error or EOF
  14760. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14761. // Keep reading
  14762. }
  14763. // Should get an error since content_length wasn't satisfied
  14764. if (n < 0) {
  14765. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14766. handle.get_read_error() == Error::Read)
  14767. << "Actual error: " << to_string(handle.get_read_error());
  14768. }
  14769. svr.stop();
  14770. t.join();
  14771. }
  14772. #ifdef CPPHTTPLIB_SSL_ENABLED
  14773. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14774. // Test that read timeout during SSL streaming is detected
  14775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14776. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14777. res.set_content_provider(
  14778. 1000, "text/plain",
  14779. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14780. if (offset < 100) {
  14781. std::string data(100, 'A');
  14782. sink.write(data.c_str(), data.size());
  14783. return true;
  14784. }
  14785. std::this_thread::sleep_for(std::chrono::seconds(3));
  14786. std::string data(900, 'B');
  14787. sink.write(data.c_str(), data.size());
  14788. return true;
  14789. });
  14790. });
  14791. auto port = 8093;
  14792. std::thread t([&]() { svr.listen("localhost", port); });
  14793. svr.wait_until_ready();
  14794. SSLClient cli("localhost", port);
  14795. cli.enable_server_certificate_verification(false);
  14796. cli.set_read_timeout(1, 0); // 1 second timeout
  14797. auto handle = cli.open_stream("GET", "/slow-stream");
  14798. ASSERT_TRUE(handle.is_valid());
  14799. char buf[256];
  14800. ssize_t total = 0;
  14801. ssize_t n;
  14802. bool got_error = false;
  14803. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14804. total += n;
  14805. }
  14806. if (n < 0) {
  14807. got_error = true;
  14808. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14809. handle.get_read_error() == Error::Read)
  14810. << "Actual error: " << to_string(handle.get_read_error());
  14811. }
  14812. EXPECT_TRUE(got_error || total < 1000)
  14813. << "Expected timeout but got all " << total << " bytes";
  14814. svr.stop();
  14815. t.join();
  14816. }
  14817. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14818. // Test SSL connection closed detection
  14819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14820. std::atomic<bool> close_now{false};
  14821. svr.Get("/will-close", [&](const Request &, Response &res) {
  14822. res.set_content_provider(
  14823. 10000, "text/plain",
  14824. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14825. if (offset < 100) {
  14826. std::string data(100, 'X');
  14827. sink.write(data.c_str(), data.size());
  14828. return true;
  14829. }
  14830. while (!close_now) {
  14831. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14832. }
  14833. return false;
  14834. });
  14835. });
  14836. auto port = 8094;
  14837. std::thread t([&]() { svr.listen("localhost", port); });
  14838. svr.wait_until_ready();
  14839. SSLClient cli("localhost", port);
  14840. cli.enable_server_certificate_verification(false);
  14841. auto handle = cli.open_stream("GET", "/will-close");
  14842. ASSERT_TRUE(handle.is_valid());
  14843. char buf[256];
  14844. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14845. EXPECT_GT(n, 0);
  14846. // Signal server to close
  14847. close_now = true;
  14848. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14849. // Keep reading
  14850. }
  14851. if (n < 0) {
  14852. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14853. handle.get_read_error() == Error::Read)
  14854. << "Actual error: " << to_string(handle.get_read_error());
  14855. }
  14856. svr.stop();
  14857. t.join();
  14858. }
  14859. #endif
  14860. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14861. using namespace httplib;
  14862. // Create a test file
  14863. const char *fname = "etag_testfile.txt";
  14864. const char *content = "etag-content";
  14865. {
  14866. std::ofstream ofs(fname);
  14867. ofs << content;
  14868. ASSERT_TRUE(ofs.good());
  14869. }
  14870. Server svr;
  14871. svr.set_mount_point("/static", ".");
  14872. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14873. svr.wait_until_ready();
  14874. Client cli(HOST, PORT);
  14875. // First request: should get 200 with ETag header
  14876. auto res1 = cli.Get("/static/etag_testfile.txt");
  14877. ASSERT_TRUE(res1);
  14878. ASSERT_EQ(200, res1->status);
  14879. ASSERT_TRUE(res1->has_header("ETag"));
  14880. std::string etag = res1->get_header_value("ETag");
  14881. EXPECT_FALSE(etag.empty());
  14882. // Verify ETag format: W/"hex-hex"
  14883. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14884. EXPECT_EQ('W', etag[0]);
  14885. EXPECT_EQ('/', etag[1]);
  14886. EXPECT_EQ('"', etag[2]);
  14887. EXPECT_EQ('"', etag.back());
  14888. // Exact match: expect 304 Not Modified
  14889. Headers h2 = {{"If-None-Match", etag}};
  14890. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14891. ASSERT_TRUE(res2);
  14892. EXPECT_EQ(304, res2->status);
  14893. // Wildcard match: expect 304 Not Modified
  14894. Headers h3 = {{"If-None-Match", "*"}};
  14895. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14896. ASSERT_TRUE(res3);
  14897. EXPECT_EQ(304, res3->status);
  14898. // Non-matching ETag: expect 200
  14899. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14900. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14901. ASSERT_TRUE(res4);
  14902. EXPECT_EQ(200, res4->status);
  14903. // Multiple ETags with one matching: expect 304
  14904. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14905. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14906. ASSERT_TRUE(res5);
  14907. EXPECT_EQ(304, res5->status);
  14908. svr.stop();
  14909. t.join();
  14910. std::remove(fname);
  14911. }
  14912. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14913. using namespace httplib;
  14914. Server svr;
  14915. svr.set_mount_point("/static", ".");
  14916. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14917. svr.wait_until_ready();
  14918. Client cli(HOST, PORT);
  14919. // Send If-None-Match: * to a non-existent file
  14920. Headers h = {{"If-None-Match", "*"}};
  14921. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14923. EXPECT_EQ(404, res->status);
  14924. svr.stop();
  14925. t.join();
  14926. }
  14927. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14928. using namespace httplib;
  14929. // Create a test file
  14930. const char *fname = "etag_boundary_testfile.txt";
  14931. const char *content = "boundary-test";
  14932. {
  14933. std::ofstream ofs(fname);
  14934. ofs << content;
  14935. ASSERT_TRUE(ofs.good());
  14936. }
  14937. Server svr;
  14938. svr.set_mount_point("/static", ".");
  14939. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14940. svr.wait_until_ready();
  14941. Client cli(HOST, PORT);
  14942. // Get the actual ETag
  14943. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14944. ASSERT_TRUE(res1);
  14945. ASSERT_EQ(200, res1->status);
  14946. ASSERT_TRUE(res1->has_header("ETag"));
  14947. std::string etag = res1->get_header_value("ETag");
  14948. // Test 1: Very long ETag value (longer than actual ETag)
  14949. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14950. Headers h1 = {{"If-None-Match", "W/"
  14951. "\"very-long-etag-value-that-is-much-longer-"
  14952. "than-the-actual-etag-value\""}};
  14953. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14954. ASSERT_TRUE(res2);
  14955. EXPECT_EQ(200, res2->status); // Should not match
  14956. // Test 2: Long string followed by wildcard
  14957. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14958. // string)
  14959. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14960. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14961. ASSERT_TRUE(res3);
  14962. EXPECT_EQ(304, res3->status); // Should match on "*"
  14963. // Test 3: Wildcard followed by long string
  14964. // Should match on "*" immediately and return 304
  14965. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14966. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14967. ASSERT_TRUE(res4);
  14968. EXPECT_EQ(304, res4->status); // Should match on "*"
  14969. // Test 4: Multiple long non-matching values
  14970. // Should NOT match and return 200 (test that all comparisons are safe)
  14971. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14972. "W/\"second-long-non-matching-value\", "
  14973. "W/\"third-long-non-matching-value\""}};
  14974. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14975. ASSERT_TRUE(res5);
  14976. EXPECT_EQ(200, res5->status); // Should not match
  14977. // Test 5: Single character that is not "*" (edge case)
  14978. Headers h5 = {{"If-None-Match", "X"}};
  14979. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14980. ASSERT_TRUE(res6);
  14981. EXPECT_EQ(200, res6->status); // Should not match
  14982. svr.stop();
  14983. t.join();
  14984. std::remove(fname);
  14985. }
  14986. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14987. using namespace httplib;
  14988. // Create a test file
  14989. const char *fname = "ims_testfile.txt";
  14990. const char *content = "if-modified-since-test";
  14991. {
  14992. std::ofstream ofs(fname);
  14993. ofs << content;
  14994. ASSERT_TRUE(ofs.good());
  14995. }
  14996. Server svr;
  14997. svr.set_mount_point("/static", ".");
  14998. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14999. svr.wait_until_ready();
  15000. Client cli(HOST, PORT);
  15001. // First request: should get 200 with Last-Modified header
  15002. auto res1 = cli.Get("/static/ims_testfile.txt");
  15003. ASSERT_TRUE(res1);
  15004. ASSERT_EQ(200, res1->status);
  15005. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15006. std::string last_modified = res1->get_header_value("Last-Modified");
  15007. EXPECT_FALSE(last_modified.empty());
  15008. // If-Modified-Since with same time: expect 304
  15009. Headers h2 = {{"If-Modified-Since", last_modified}};
  15010. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15011. ASSERT_TRUE(res2);
  15012. EXPECT_EQ(304, res2->status);
  15013. // If-Modified-Since with future time: expect 304
  15014. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15015. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15016. ASSERT_TRUE(res3);
  15017. EXPECT_EQ(304, res3->status);
  15018. // If-Modified-Since with past time: expect 200
  15019. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15020. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15021. ASSERT_TRUE(res4);
  15022. EXPECT_EQ(200, res4->status);
  15023. // If-None-Match takes precedence over If-Modified-Since
  15024. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15025. ASSERT_TRUE(res1->has_header("ETag"));
  15026. std::string etag = res1->get_header_value("ETag");
  15027. Headers h5 = {{"If-None-Match", etag},
  15028. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15029. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15030. ASSERT_TRUE(res5);
  15031. EXPECT_EQ(304, res5->status);
  15032. svr.stop();
  15033. t.join();
  15034. std::remove(fname);
  15035. }
  15036. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15037. using namespace httplib;
  15038. Server svr;
  15039. // Endpoint that returns compressible content
  15040. svr.Get("/compressible", [](const Request &, Response &res) {
  15041. // Return a large enough body to trigger compression
  15042. std::string body(1000, 'a');
  15043. res.set_content(body, "text/plain");
  15044. });
  15045. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15046. svr.wait_until_ready();
  15047. Client cli(HOST, PORT);
  15048. // Request with gzip support: should get Vary header when compressed
  15049. cli.set_compress(true);
  15050. auto res1 = cli.Get("/compressible");
  15051. ASSERT_TRUE(res1);
  15052. EXPECT_EQ(200, res1->status);
  15053. // If Content-Encoding is set, Vary should also be set
  15054. if (res1->has_header("Content-Encoding")) {
  15055. EXPECT_TRUE(res1->has_header("Vary"));
  15056. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15057. }
  15058. // Request without Accept-Encoding header: should not have compression
  15059. Headers h_no_compress;
  15060. auto res2 = cli.Get("/compressible", h_no_compress);
  15061. ASSERT_TRUE(res2);
  15062. EXPECT_EQ(200, res2->status);
  15063. // Verify Vary header is present when compression is applied
  15064. // (the exact behavior depends on server configuration)
  15065. svr.stop();
  15066. t.join();
  15067. }
  15068. TEST(ETagTest, IfRangeWithETag) {
  15069. using namespace httplib;
  15070. // Create a test file with known content
  15071. const char *fname = "if_range_testfile.txt";
  15072. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15073. {
  15074. std::ofstream ofs(fname);
  15075. ofs << content;
  15076. ASSERT_TRUE(ofs.good());
  15077. }
  15078. Server svr;
  15079. svr.set_mount_point("/static", ".");
  15080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15081. svr.wait_until_ready();
  15082. Client cli(HOST, PORT);
  15083. // First request: get ETag
  15084. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15085. ASSERT_TRUE(res1);
  15086. ASSERT_EQ(200, res1->status);
  15087. ASSERT_TRUE(res1->has_header("ETag"));
  15088. std::string etag = res1->get_header_value("ETag");
  15089. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15090. // Since our server generates weak ETags (W/"..."), If-Range with our
  15091. // ETag should NOT result in partial content - it should return full content.
  15092. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15093. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15094. ASSERT_TRUE(res2);
  15095. // Weak ETag in If-Range -> full content (200), not partial (206)
  15096. EXPECT_EQ(200, res2->status);
  15097. EXPECT_EQ(content, res2->body);
  15098. EXPECT_FALSE(res2->has_header("Content-Range"));
  15099. // Range request with non-matching If-Range (ETag): should get 200 (full
  15100. // content)
  15101. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15102. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15103. ASSERT_TRUE(res3);
  15104. EXPECT_EQ(200, res3->status);
  15105. EXPECT_EQ(content, res3->body);
  15106. EXPECT_FALSE(res3->has_header("Content-Range"));
  15107. // Range request with strong ETag (hypothetical - our server doesn't generate
  15108. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15109. // should return full content)
  15110. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15111. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15112. ASSERT_TRUE(res4);
  15113. EXPECT_EQ(200, res4->status);
  15114. EXPECT_EQ(content, res4->body);
  15115. EXPECT_FALSE(res4->has_header("Content-Range"));
  15116. svr.stop();
  15117. t.join();
  15118. std::remove(fname);
  15119. }
  15120. TEST(ETagTest, IfRangeWithDate) {
  15121. using namespace httplib;
  15122. // Create a test file
  15123. const char *fname = "if_range_date_testfile.txt";
  15124. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15125. {
  15126. std::ofstream ofs(fname);
  15127. ofs << content;
  15128. ASSERT_TRUE(ofs.good());
  15129. }
  15130. Server svr;
  15131. svr.set_mount_point("/static", ".");
  15132. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15133. svr.wait_until_ready();
  15134. Client cli(HOST, PORT);
  15135. // First request: get Last-Modified
  15136. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15137. ASSERT_TRUE(res1);
  15138. ASSERT_EQ(200, res1->status);
  15139. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15140. std::string last_modified = res1->get_header_value("Last-Modified");
  15141. // Range request with matching If-Range (date): should get 206
  15142. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15143. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15144. ASSERT_TRUE(res2);
  15145. EXPECT_EQ(206, res2->status);
  15146. EXPECT_EQ("FGHIJ", res2->body);
  15147. // Range request with old If-Range date: should get 200 (full content)
  15148. Headers h3 = {{"Range", "bytes=5-9"},
  15149. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15150. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15151. ASSERT_TRUE(res3);
  15152. EXPECT_EQ(200, res3->status);
  15153. EXPECT_EQ(content, res3->body);
  15154. // Range request with future If-Range date: should get 206
  15155. Headers h4 = {{"Range", "bytes=0-4"},
  15156. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15157. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15158. ASSERT_TRUE(res4);
  15159. EXPECT_EQ(206, res4->status);
  15160. EXPECT_EQ("ABCDE", res4->body);
  15161. svr.stop();
  15162. t.join();
  15163. std::remove(fname);
  15164. }
  15165. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15166. using namespace httplib;
  15167. const char *fname = "etag_malformed.txt";
  15168. const char *content = "malformed-etag";
  15169. {
  15170. std::ofstream ofs(fname);
  15171. ofs << content;
  15172. ASSERT_TRUE(ofs.good());
  15173. }
  15174. Server svr;
  15175. svr.set_mount_point("/static", ".");
  15176. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15177. svr.wait_until_ready();
  15178. Client cli(HOST, PORT);
  15179. // baseline: should get 200 and an ETag
  15180. auto res1 = cli.Get("/static/etag_malformed.txt");
  15181. ASSERT_TRUE(res1);
  15182. ASSERT_EQ(200, res1->status);
  15183. ASSERT_TRUE(res1->has_header("ETag"));
  15184. // Malformed ETag value (missing quotes) should be treated as non-matching
  15185. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15186. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15187. ASSERT_TRUE(res_bad);
  15188. EXPECT_EQ(200, res_bad->status);
  15189. // Whitespace-only header value should be considered invalid / non-matching
  15190. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15191. "Host: localhost\r\n"
  15192. "If-None-Match: \r\n"
  15193. "Connection: close\r\n"
  15194. "\r\n";
  15195. std::string out;
  15196. ASSERT_TRUE(send_request(5, raw_req, &out));
  15197. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15198. svr.stop();
  15199. t.join();
  15200. std::remove(fname);
  15201. }
  15202. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15203. using namespace httplib;
  15204. const char *fname = "ims_invalid_format.txt";
  15205. const char *content = "ims-bad-format";
  15206. {
  15207. std::ofstream ofs(fname);
  15208. ofs << content;
  15209. ASSERT_TRUE(ofs.good());
  15210. }
  15211. Server svr;
  15212. svr.set_mount_point("/static", ".");
  15213. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15214. svr.wait_until_ready();
  15215. Client cli(HOST, PORT);
  15216. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15217. ASSERT_TRUE(res1);
  15218. ASSERT_EQ(200, res1->status);
  15219. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15220. // If-Modified-Since with invalid format should not result in 304
  15221. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15222. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15223. ASSERT_TRUE(res_bad);
  15224. EXPECT_EQ(200, res_bad->status);
  15225. // If-Range with invalid date format should be treated as mismatch -> full
  15226. // content (200)
  15227. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15228. {"If-Range", "invalid-date"}};
  15229. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15230. ASSERT_TRUE(res_ifrange);
  15231. EXPECT_EQ(200, res_ifrange->status);
  15232. svr.stop();
  15233. t.join();
  15234. std::remove(fname);
  15235. }
  15236. TEST(ETagTest, IfRangeWithMalformedETag) {
  15237. using namespace httplib;
  15238. const char *fname = "ifrange_malformed.txt";
  15239. const std::string content = "0123456789";
  15240. {
  15241. std::ofstream ofs(fname);
  15242. ofs << content;
  15243. ASSERT_TRUE(ofs.good());
  15244. }
  15245. Server svr;
  15246. svr.set_mount_point("/static", ".");
  15247. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15248. svr.wait_until_ready();
  15249. Client cli(HOST, PORT);
  15250. // First request: get ETag
  15251. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15252. ASSERT_TRUE(res1);
  15253. ASSERT_EQ(200, res1->status);
  15254. ASSERT_TRUE(res1->has_header("ETag"));
  15255. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15256. // full content (200)
  15257. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15258. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15259. ASSERT_TRUE(res2);
  15260. EXPECT_EQ(200, res2->status);
  15261. EXPECT_EQ(content, res2->body);
  15262. svr.stop();
  15263. t.join();
  15264. std::remove(fname);
  15265. }
  15266. TEST(ETagTest, ExtremeLargeDateValues) {
  15267. using namespace httplib;
  15268. const char *fname = "ims_extreme_date.txt";
  15269. const char *content = "ims-extreme-date";
  15270. {
  15271. std::ofstream ofs(fname);
  15272. ofs << content;
  15273. ASSERT_TRUE(ofs.good());
  15274. }
  15275. Server svr;
  15276. svr.set_mount_point("/static", ".");
  15277. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15278. svr.wait_until_ready();
  15279. Client cli(HOST, PORT);
  15280. auto res1 = cli.Get(std::string("/static/") + fname);
  15281. ASSERT_TRUE(res1);
  15282. ASSERT_EQ(200, res1->status);
  15283. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15284. // Extremely large year that may overflow date parsing routines.
  15285. Headers h_large_date = {
  15286. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15287. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15288. ASSERT_TRUE(res_bad);
  15289. // Expect server to treat this as invalid/mismatch and return full content
  15290. EXPECT_EQ(200, res_bad->status);
  15291. // If-Range with extremely large date should be treated as mismatch -> full
  15292. // content (200)
  15293. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15294. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15295. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15296. ASSERT_TRUE(res_ifrange);
  15297. EXPECT_EQ(200, res_ifrange->status);
  15298. svr.stop();
  15299. t.join();
  15300. std::remove(fname);
  15301. }
  15302. TEST(ETagTest, NegativeFileModificationTime) {
  15303. using namespace httplib;
  15304. const char *fname = "ims_negative_mtime.txt";
  15305. const std::string content = "negative-mtime";
  15306. {
  15307. std::ofstream ofs(fname);
  15308. ofs << content;
  15309. ASSERT_TRUE(ofs.good());
  15310. }
  15311. // Try to set file mtime to a negative value. This may fail on some
  15312. // platforms/filesystems; if it fails, the test will still verify server
  15313. // behaves safely by performing a regular conditional request.
  15314. #if defined(__APPLE__) || defined(__linux__)
  15315. bool set_negative = false;
  15316. do {
  15317. struct timeval times[2];
  15318. // access time: now
  15319. times[0].tv_sec = time(nullptr);
  15320. times[0].tv_usec = 0;
  15321. // modification time: negative (e.g., -1)
  15322. times[1].tv_sec = -1;
  15323. times[1].tv_usec = 0;
  15324. if (utimes(fname, times) == 0) { set_negative = true; }
  15325. } while (0);
  15326. #else
  15327. bool set_negative = false;
  15328. #endif
  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. auto res1 = cli.Get(std::string("/static/") + fname);
  15335. ASSERT_TRUE(res1);
  15336. ASSERT_EQ(200, res1->status);
  15337. bool has_last_modified = res1->has_header("Last-Modified");
  15338. std::string last_modified;
  15339. if (has_last_modified) {
  15340. last_modified = res1->get_header_value("Last-Modified");
  15341. }
  15342. if (set_negative) {
  15343. // If we successfully set a negative mtime, ensure server returns a
  15344. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15345. // with an old date and ensure server handles it without crash.
  15346. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15347. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15348. ASSERT_TRUE(res2);
  15349. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15350. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15351. } else {
  15352. // Could not set negative mtime on this platform; fall back to verifying
  15353. // that normal invalid/malformed dates are treated safely (non-304).
  15354. Headers h_bad_date = {
  15355. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15356. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15357. ASSERT_TRUE(res_bad);
  15358. EXPECT_EQ(200, res_bad->status);
  15359. }
  15360. svr.stop();
  15361. t.join();
  15362. std::remove(fname);
  15363. }
  15364. //==============================================================================
  15365. // SSE Parsing Tests
  15366. //==============================================================================
  15367. class SSEParsingTest : public ::testing::Test {
  15368. protected:
  15369. // Test helper that mimics SSE parsing behavior
  15370. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15371. int &retry_ms) {
  15372. // Blank line signals end of event
  15373. if (line.empty() || line == "\r") { return true; }
  15374. // Lines starting with ':' are comments (ignored)
  15375. if (!line.empty() && line[0] == ':') { return false; }
  15376. // Find the colon separator
  15377. auto colon_pos = line.find(':');
  15378. if (colon_pos == std::string::npos) {
  15379. // Line with no colon is treated as field name with empty value
  15380. return false;
  15381. }
  15382. std::string field = line.substr(0, colon_pos);
  15383. std::string value;
  15384. // Value starts after colon, skip optional single space
  15385. if (colon_pos + 1 < line.size()) {
  15386. size_t value_start = colon_pos + 1;
  15387. if (line[value_start] == ' ') { value_start++; }
  15388. value = line.substr(value_start);
  15389. // Remove trailing \r if present
  15390. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15391. }
  15392. // Handle known fields
  15393. if (field == "event") {
  15394. msg.event = value;
  15395. } else if (field == "data") {
  15396. // Multiple data lines are concatenated with newlines
  15397. if (!msg.data.empty()) { msg.data += "\n"; }
  15398. msg.data += value;
  15399. } else if (field == "id") {
  15400. // Empty id is valid (clears the last event ID)
  15401. msg.id = value;
  15402. } else if (field == "retry") {
  15403. // Parse retry interval in milliseconds
  15404. {
  15405. int v = 0;
  15406. auto res =
  15407. detail::from_chars(value.data(), value.data() + value.size(), v);
  15408. if (res.ec == std::errc{}) { retry_ms = v; }
  15409. }
  15410. }
  15411. // Unknown fields are ignored per SSE spec
  15412. return false;
  15413. }
  15414. };
  15415. // Test: Single-line data
  15416. TEST_F(SSEParsingTest, SingleLineData) {
  15417. sse::SSEMessage msg;
  15418. int retry_ms = 3000;
  15419. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15420. EXPECT_EQ(msg.data, "hello");
  15421. EXPECT_EQ(msg.event, "message");
  15422. // Blank line ends event
  15423. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15424. }
  15425. // Test: Multi-line data
  15426. TEST_F(SSEParsingTest, MultiLineData) {
  15427. sse::SSEMessage msg;
  15428. int retry_ms = 3000;
  15429. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15430. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15431. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15432. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15433. }
  15434. // Test: Custom event types
  15435. TEST_F(SSEParsingTest, CustomEventType) {
  15436. sse::SSEMessage msg;
  15437. int retry_ms = 3000;
  15438. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15439. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15440. EXPECT_EQ(msg.event, "update");
  15441. EXPECT_EQ(msg.data, "payload");
  15442. }
  15443. // Test: Event ID handling
  15444. TEST_F(SSEParsingTest, EventIdHandling) {
  15445. sse::SSEMessage msg;
  15446. int retry_ms = 3000;
  15447. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15448. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15449. EXPECT_EQ(msg.id, "12345");
  15450. }
  15451. // Test: Empty event ID (clears last event ID)
  15452. TEST_F(SSEParsingTest, EmptyEventId) {
  15453. sse::SSEMessage msg;
  15454. msg.id = "previous";
  15455. int retry_ms = 3000;
  15456. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15457. EXPECT_EQ(msg.id, "");
  15458. }
  15459. // Test: Retry field parsing
  15460. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15461. sse::SSEMessage msg;
  15462. int retry_ms = 3000;
  15463. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15464. EXPECT_EQ(retry_ms, 5000);
  15465. }
  15466. // Test: Invalid retry value
  15467. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15468. sse::SSEMessage msg;
  15469. int retry_ms = 3000;
  15470. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15471. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15472. }
  15473. // Test: Comments (lines starting with :)
  15474. TEST_F(SSEParsingTest, CommentsIgnored) {
  15475. sse::SSEMessage msg;
  15476. int retry_ms = 3000;
  15477. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15478. EXPECT_EQ(msg.data, "");
  15479. EXPECT_EQ(msg.event, "message");
  15480. }
  15481. // Test: Colon in value
  15482. TEST_F(SSEParsingTest, ColonInValue) {
  15483. sse::SSEMessage msg;
  15484. int retry_ms = 3000;
  15485. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15486. EXPECT_EQ(msg.data, "hello:world:test");
  15487. }
  15488. // Test: Line with no colon (field name only)
  15489. TEST_F(SSEParsingTest, FieldNameOnly) {
  15490. sse::SSEMessage msg;
  15491. int retry_ms = 3000;
  15492. // According to SSE spec, this is treated as field name with empty value
  15493. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15494. // Since we don't recognize "data" without colon, data should be empty
  15495. EXPECT_EQ(msg.data, "");
  15496. }
  15497. // Test: Trailing \r handling
  15498. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15499. sse::SSEMessage msg;
  15500. int retry_ms = 3000;
  15501. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15502. EXPECT_EQ(msg.data, "hello");
  15503. }
  15504. // Test: Unknown fields ignored
  15505. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15506. sse::SSEMessage msg;
  15507. int retry_ms = 3000;
  15508. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15509. EXPECT_EQ(msg.data, "");
  15510. EXPECT_EQ(msg.event, "message");
  15511. }
  15512. // Test: Space after colon is optional
  15513. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15514. sse::SSEMessage msg1, msg2;
  15515. int retry_ms = 3000;
  15516. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15517. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15518. EXPECT_EQ(msg1.data, "hello");
  15519. EXPECT_EQ(msg2.data, "hello");
  15520. }
  15521. // Test: SSEMessage clear
  15522. TEST_F(SSEParsingTest, MessageClear) {
  15523. sse::SSEMessage msg;
  15524. msg.event = "custom";
  15525. msg.data = "some data";
  15526. msg.id = "123";
  15527. msg.clear();
  15528. EXPECT_EQ(msg.event, "message");
  15529. EXPECT_EQ(msg.data, "");
  15530. EXPECT_EQ(msg.id, "");
  15531. }
  15532. // Test: Complete event parsing
  15533. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15534. sse::SSEMessage msg;
  15535. int retry_ms = 3000;
  15536. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15537. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15538. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15539. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15540. // Blank line ends event
  15541. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15542. EXPECT_EQ(msg.event, "notification");
  15543. EXPECT_EQ(msg.id, "evt-42");
  15544. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15545. EXPECT_EQ(retry_ms, 1000);
  15546. }
  15547. //==============================================================================
  15548. // Integration Tests with Server
  15549. //==============================================================================
  15550. class SSEIntegrationTest : public ::testing::Test {
  15551. protected:
  15552. void SetUp() override {
  15553. stop_server_.store(false);
  15554. events_.clear();
  15555. server_ = httplib::detail::make_unique<Server>();
  15556. setup_server();
  15557. start_server();
  15558. }
  15559. void TearDown() override {
  15560. stop_server_.store(true);
  15561. event_cv_.notify_all();
  15562. server_->stop();
  15563. if (server_thread_.joinable()) { server_thread_.join(); }
  15564. }
  15565. void setup_server() {
  15566. // Simple SSE endpoint
  15567. server_->Get("/events", [this](const Request &req, Response &res) {
  15568. auto last_id = req.get_header_value("Last-Event-ID");
  15569. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15570. res.set_chunked_content_provider(
  15571. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15572. std::unique_lock<std::mutex> lock(event_mutex_);
  15573. if (event_cv_.wait_for(
  15574. lock, std::chrono::milliseconds(200), [this] {
  15575. return !events_.empty() || stop_server_.load();
  15576. })) {
  15577. if (stop_server_.load()) { return false; }
  15578. if (!events_.empty()) {
  15579. std::string event = events_.front();
  15580. events_.erase(events_.begin());
  15581. sink.write(event.data(), event.size());
  15582. return true;
  15583. }
  15584. }
  15585. return !stop_server_.load();
  15586. });
  15587. });
  15588. // Endpoint that returns error
  15589. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15590. res.status = 500;
  15591. res.set_content("Internal Server Error", "text/plain");
  15592. });
  15593. // Endpoint for custom event types
  15594. server_->Get("/custom-events", [](const Request &, Response &res) {
  15595. res.set_chunked_content_provider(
  15596. "text/event-stream", [](size_t offset, DataSink &sink) {
  15597. if (offset == 0) {
  15598. std::string event = "event: update\ndata: updated\n\n"
  15599. "event: delete\ndata: deleted\n\n";
  15600. sink.write(event.data(), event.size());
  15601. }
  15602. return false; // End stream after sending
  15603. });
  15604. });
  15605. }
  15606. void start_server() {
  15607. port_ = server_->bind_to_any_port(HOST);
  15608. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15609. // Wait for server to start
  15610. while (!server_->is_running()) {
  15611. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15612. }
  15613. }
  15614. int get_port() const { return port_; }
  15615. void send_event(const std::string &event) {
  15616. std::lock_guard<std::mutex> lock(event_mutex_);
  15617. events_.push_back(event);
  15618. event_cv_.notify_all();
  15619. }
  15620. std::unique_ptr<Server> server_;
  15621. std::thread server_thread_;
  15622. std::mutex event_mutex_;
  15623. std::condition_variable event_cv_;
  15624. std::vector<std::string> events_;
  15625. std::atomic<bool> stop_server_{false};
  15626. std::string last_received_event_id_;
  15627. int port_ = 0;
  15628. };
  15629. // Test: Successful connection and on_open callback
  15630. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15631. // Add a simple endpoint that sends one event and closes
  15632. server_->Get("/simple-event", [](const Request &, Response &res) {
  15633. res.set_chunked_content_provider(
  15634. "text/event-stream", [](size_t offset, DataSink &sink) {
  15635. if (offset == 0) {
  15636. std::string event = "data: hello\n\n";
  15637. sink.write(event.data(), event.size());
  15638. }
  15639. return false; // Close stream after sending
  15640. });
  15641. });
  15642. Client client("localhost", get_port());
  15643. sse::SSEClient sse(client, "/simple-event");
  15644. std::atomic<bool> open_called{false};
  15645. std::atomic<bool> message_received{false};
  15646. sse.on_open([&open_called]() { open_called.store(true); });
  15647. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15648. if (msg.data == "hello") { message_received.store(true); }
  15649. });
  15650. sse.set_reconnect_interval(100);
  15651. sse.set_max_reconnect_attempts(1);
  15652. // Start async
  15653. sse.start_async();
  15654. // Wait for message to be processed
  15655. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15656. sse.stop();
  15657. EXPECT_TRUE(open_called.load());
  15658. EXPECT_TRUE(message_received.load());
  15659. }
  15660. // Test: on_message callback
  15661. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15662. // Endpoint that sends multiple events then closes
  15663. server_->Get("/multi-event", [](const Request &, Response &res) {
  15664. res.set_chunked_content_provider(
  15665. "text/event-stream", [](size_t offset, DataSink &sink) {
  15666. if (offset == 0) {
  15667. std::string events = "data: message1\n\ndata: message2\n\n";
  15668. sink.write(events.data(), events.size());
  15669. }
  15670. return false;
  15671. });
  15672. });
  15673. Client client("localhost", get_port());
  15674. sse::SSEClient sse(client, "/multi-event");
  15675. std::vector<std::string> received_messages;
  15676. std::mutex messages_mutex;
  15677. sse.on_message([&](const sse::SSEMessage &msg) {
  15678. std::lock_guard<std::mutex> lock(messages_mutex);
  15679. received_messages.push_back(msg.data);
  15680. });
  15681. sse.set_reconnect_interval(100);
  15682. sse.set_max_reconnect_attempts(1);
  15683. sse.start_async();
  15684. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15685. sse.stop();
  15686. std::lock_guard<std::mutex> lock(messages_mutex);
  15687. EXPECT_GE(received_messages.size(), 2u);
  15688. if (received_messages.size() >= 2) {
  15689. EXPECT_EQ(received_messages[0], "message1");
  15690. EXPECT_EQ(received_messages[1], "message2");
  15691. }
  15692. }
  15693. // Test: on_event for specific types
  15694. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15695. Client client("localhost", get_port());
  15696. sse::SSEClient sse(client, "/custom-events");
  15697. std::atomic<bool> update_received{false};
  15698. std::atomic<bool> delete_received{false};
  15699. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15700. if (msg.data == "updated") { update_received.store(true); }
  15701. });
  15702. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15703. if (msg.data == "deleted") { delete_received.store(true); }
  15704. });
  15705. sse.set_max_reconnect_attempts(1);
  15706. sse.start_async();
  15707. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15708. sse.stop();
  15709. EXPECT_TRUE(update_received.load());
  15710. EXPECT_TRUE(delete_received.load());
  15711. }
  15712. // Test: on_error callback on connection failure
  15713. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15714. // Connect to a non-existent port
  15715. Client client("localhost", 59999);
  15716. sse::SSEClient sse(client, "/events");
  15717. std::atomic<bool> error_called{false};
  15718. Error received_error = Error::Success;
  15719. sse.on_error([&](Error err) {
  15720. error_called.store(true);
  15721. received_error = err;
  15722. });
  15723. sse.set_reconnect_interval(50);
  15724. sse.set_max_reconnect_attempts(1);
  15725. sse.start_async();
  15726. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15727. sse.stop();
  15728. EXPECT_TRUE(error_called.load());
  15729. EXPECT_NE(received_error, Error::Success);
  15730. }
  15731. // Test: Last-Event-ID header sent on reconnect
  15732. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15733. // Endpoint that sends event with ID
  15734. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15735. res.set_chunked_content_provider(
  15736. "text/event-stream", [](size_t offset, DataSink &sink) {
  15737. if (offset == 0) {
  15738. std::string event = "id: evt-123\ndata: test\n\n";
  15739. sink.write(event.data(), event.size());
  15740. }
  15741. return false;
  15742. });
  15743. });
  15744. Client client("localhost", get_port());
  15745. sse::SSEClient sse(client, "/event-with-id");
  15746. std::atomic<bool> id_received{false};
  15747. sse.on_message([&](const sse::SSEMessage &msg) {
  15748. if (!msg.id.empty()) { id_received.store(true); }
  15749. });
  15750. sse.set_reconnect_interval(100);
  15751. sse.set_max_reconnect_attempts(1);
  15752. sse.start_async();
  15753. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15754. sse.stop();
  15755. EXPECT_TRUE(id_received.load());
  15756. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15757. }
  15758. // Test: Manual stop
  15759. TEST_F(SSEIntegrationTest, ManualStop) {
  15760. // Endpoint that sends one event and stays open briefly
  15761. std::atomic<bool> handler_running{true};
  15762. server_->Get("/stay-open", [&handler_running](const Request &,
  15763. Response &res) {
  15764. res.set_chunked_content_provider(
  15765. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15766. if (offset == 0) {
  15767. std::string event = "data: connected\n\n";
  15768. sink.write(event.data(), event.size());
  15769. }
  15770. // Keep connection open while handler_running is true
  15771. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15772. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15773. }
  15774. return false;
  15775. });
  15776. });
  15777. Client client("localhost", get_port());
  15778. sse::SSEClient sse(client, "/stay-open");
  15779. std::atomic<bool> connected{false};
  15780. sse.on_open([&connected]() { connected.store(true); });
  15781. sse.set_reconnect_interval(100);
  15782. sse.set_max_reconnect_attempts(1);
  15783. sse.start_async();
  15784. // Wait for connection to establish
  15785. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15786. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15787. }
  15788. EXPECT_TRUE(connected.load());
  15789. EXPECT_TRUE(sse.is_connected());
  15790. // Signal handler to stop
  15791. handler_running.store(false);
  15792. // Stop SSE client
  15793. sse.stop();
  15794. EXPECT_FALSE(sse.is_connected());
  15795. }
  15796. // Test: SSEClient with custom headers
  15797. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15798. // Setup a server endpoint that checks for custom header
  15799. std::atomic<bool> header_received{false};
  15800. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15801. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15802. header_received.store(true);
  15803. }
  15804. res.set_chunked_content_provider("text/event-stream",
  15805. [](size_t, DataSink &) { return false; });
  15806. });
  15807. Client client("localhost", get_port());
  15808. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15809. sse::SSEClient sse(client, "/header-check", headers);
  15810. sse.set_max_reconnect_attempts(1);
  15811. sse.start_async();
  15812. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15813. sse.stop();
  15814. EXPECT_TRUE(header_received.load());
  15815. }
  15816. // Test: Reconnect interval configuration
  15817. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15818. Client client("localhost", get_port());
  15819. sse::SSEClient sse(client, "/events");
  15820. auto &result = sse.set_reconnect_interval(500);
  15821. // Builder pattern should return reference to self
  15822. EXPECT_EQ(&result, &sse);
  15823. }
  15824. // Test: Max reconnect attempts
  15825. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15826. // Connect to non-existent port to force reconnects
  15827. Client client("localhost", 59998);
  15828. sse::SSEClient sse(client, "/events");
  15829. std::atomic<int> error_count{0};
  15830. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15831. sse.set_reconnect_interval(50);
  15832. sse.set_max_reconnect_attempts(2);
  15833. auto start = std::chrono::steady_clock::now();
  15834. sse.start(); // Blocking call
  15835. auto end = std::chrono::steady_clock::now();
  15836. // Should have stopped after 2 failed attempts
  15837. EXPECT_GE(error_count.load(), 2);
  15838. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15839. auto duration =
  15840. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15841. #ifdef _WIN32
  15842. // Windows is much slower for socket connection failures
  15843. EXPECT_LT(duration.count(), 7000);
  15844. #else
  15845. EXPECT_LT(duration.count(), 1000);
  15846. #endif
  15847. }
  15848. // Test: Multi-line data in integration
  15849. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15850. // Endpoint with multi-line data
  15851. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15852. res.set_chunked_content_provider(
  15853. "text/event-stream", [](size_t offset, DataSink &sink) {
  15854. if (offset == 0) {
  15855. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15856. sink.write(event.data(), event.size());
  15857. }
  15858. return false;
  15859. });
  15860. });
  15861. Client client("localhost", get_port());
  15862. sse::SSEClient sse(client, "/multiline-data");
  15863. std::string received_data;
  15864. std::mutex data_mutex;
  15865. sse.on_message([&](const sse::SSEMessage &msg) {
  15866. std::lock_guard<std::mutex> lock(data_mutex);
  15867. received_data = msg.data;
  15868. });
  15869. sse.set_reconnect_interval(100);
  15870. sse.set_max_reconnect_attempts(1);
  15871. sse.start_async();
  15872. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15873. sse.stop();
  15874. std::lock_guard<std::mutex> lock(data_mutex);
  15875. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15876. }
  15877. // Test: Auto-reconnect after server disconnection
  15878. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15879. std::atomic<int> connection_count{0};
  15880. std::atomic<int> message_count{0};
  15881. // Endpoint that sends one event and closes, forcing reconnect
  15882. server_->Get("/reconnect-test",
  15883. [&connection_count](const Request &, Response &res) {
  15884. connection_count.fetch_add(1);
  15885. res.set_chunked_content_provider(
  15886. "text/event-stream", [](size_t offset, DataSink &sink) {
  15887. if (offset == 0) {
  15888. std::string event = "data: hello\n\n";
  15889. sink.write(event.data(), event.size());
  15890. }
  15891. return false; // Close connection after sending
  15892. });
  15893. });
  15894. Client client("localhost", get_port());
  15895. sse::SSEClient sse(client, "/reconnect-test");
  15896. sse.on_message([&message_count](const sse::SSEMessage &) {
  15897. message_count.fetch_add(1);
  15898. });
  15899. sse.set_reconnect_interval(100);
  15900. sse.set_max_reconnect_attempts(3);
  15901. sse.start_async();
  15902. // Wait long enough for multiple reconnects
  15903. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15904. sse.stop();
  15905. // Should have connected multiple times (initial + reconnects)
  15906. EXPECT_GE(connection_count.load(), 2);
  15907. // Should have received messages from multiple connections
  15908. EXPECT_GE(message_count.load(), 2);
  15909. }
  15910. // Test: Last-Event-ID sent on reconnect
  15911. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15912. std::atomic<int> connection_count{0};
  15913. std::vector<std::string> received_last_event_ids;
  15914. std::mutex id_mutex;
  15915. // Endpoint that checks Last-Event-ID header and sends event with ID
  15916. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15917. int conn = connection_count.fetch_add(1);
  15918. // Capture the Last-Event-ID header from each connection
  15919. {
  15920. std::lock_guard<std::mutex> lock(id_mutex);
  15921. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15922. }
  15923. res.set_chunked_content_provider(
  15924. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15925. if (offset == 0) {
  15926. std::string event =
  15927. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15928. sink.write(event.data(), event.size());
  15929. }
  15930. return false;
  15931. });
  15932. });
  15933. Client client("localhost", get_port());
  15934. sse::SSEClient sse(client, "/reconnect-with-id");
  15935. sse.set_reconnect_interval(100);
  15936. sse.set_max_reconnect_attempts(3);
  15937. sse.start_async();
  15938. // Wait for at least 2 connections
  15939. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15940. sse.stop();
  15941. // Verify behavior
  15942. std::lock_guard<std::mutex> lock(id_mutex);
  15943. EXPECT_GE(received_last_event_ids.size(), 2u);
  15944. // First connection should have no Last-Event-ID
  15945. if (!received_last_event_ids.empty()) {
  15946. EXPECT_EQ(received_last_event_ids[0], "");
  15947. }
  15948. // Second connection should have Last-Event-ID from first connection
  15949. if (received_last_event_ids.size() >= 2) {
  15950. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15951. }
  15952. }
  15953. // Test: set_headers updates headers used on reconnect
  15954. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15955. std::vector<std::string> received_tokens;
  15956. std::mutex token_mutex;
  15957. // Endpoint that captures Authorization header
  15958. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15959. {
  15960. std::lock_guard<std::mutex> lock(token_mutex);
  15961. received_tokens.push_back(req.get_header_value("Authorization"));
  15962. }
  15963. res.set_chunked_content_provider(
  15964. "text/event-stream", [](size_t offset, DataSink &sink) {
  15965. if (offset == 0) {
  15966. std::string event = "data: hello\n\n";
  15967. sink.write(event.data(), event.size());
  15968. }
  15969. return false; // Close connection to trigger reconnect
  15970. });
  15971. });
  15972. Client client("localhost", get_port());
  15973. Headers headers = {{"Authorization", "Bearer old-token"}};
  15974. sse::SSEClient sse(client, "/auth-check", headers);
  15975. // Update headers on each successful connection
  15976. sse.on_open(
  15977. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15978. sse.set_reconnect_interval(100);
  15979. sse.set_max_reconnect_attempts(3);
  15980. sse.start_async();
  15981. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15982. sse.stop();
  15983. std::lock_guard<std::mutex> lock(token_mutex);
  15984. ASSERT_GE(received_tokens.size(), 2u);
  15985. // First connection uses original header
  15986. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15987. // Second connection uses updated header from set_headers
  15988. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15989. }
  15990. // Test: 401 allows reconnection (so on_error can refresh headers)
  15991. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15992. std::atomic<int> connection_count{0};
  15993. // Endpoint: returns 401 on first attempt, 200 on second
  15994. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15995. int conn = connection_count.fetch_add(1);
  15996. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15997. res.status = StatusCode::Unauthorized_401;
  15998. res.set_content("Unauthorized", "text/plain");
  15999. return;
  16000. }
  16001. res.set_chunked_content_provider(
  16002. "text/event-stream", [](size_t offset, DataSink &sink) {
  16003. if (offset == 0) {
  16004. std::string event = "data: authenticated\n\n";
  16005. sink.write(event.data(), event.size());
  16006. }
  16007. return false;
  16008. });
  16009. });
  16010. Client client("localhost", get_port());
  16011. Headers headers = {{"Authorization", "Bearer expired"}};
  16012. sse::SSEClient sse(client, "/auth-retry", headers);
  16013. std::atomic<bool> message_received{false};
  16014. // Refresh token on error
  16015. sse.on_error(
  16016. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16017. sse.on_message([&](const sse::SSEMessage &msg) {
  16018. if (msg.data == "authenticated") { message_received.store(true); }
  16019. });
  16020. sse.set_reconnect_interval(100);
  16021. sse.set_max_reconnect_attempts(3);
  16022. sse.start_async();
  16023. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16024. sse.stop();
  16025. // Should have reconnected after 401 and succeeded with new token
  16026. EXPECT_GE(connection_count.load(), 2);
  16027. EXPECT_TRUE(message_received.load());
  16028. }
  16029. TEST(Issue2318Test, EmptyHostString) {
  16030. {
  16031. httplib::Client cli_empty("", PORT);
  16032. auto res = cli_empty.Get("/");
  16033. ASSERT_FALSE(res);
  16034. EXPECT_EQ(httplib::Error::Connection, res.error());
  16035. }
  16036. {
  16037. httplib::Client cli(" ", PORT);
  16038. auto res = cli.Get("/");
  16039. ASSERT_FALSE(res);
  16040. EXPECT_EQ(httplib::Error::Connection, res.error());
  16041. }
  16042. }
  16043. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16044. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16045. Server svr;
  16046. // Set a small payload limit (1KB)
  16047. svr.set_payload_max_length(1024);
  16048. svr.Post("/test", [&](const Request &req, Response &res) {
  16049. res.set_content("Body size: " + std::to_string(req.body.size()),
  16050. "text/plain");
  16051. });
  16052. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16053. auto se = detail::scope_exit([&] {
  16054. svr.stop();
  16055. listen_thread.join();
  16056. });
  16057. svr.wait_until_ready();
  16058. // Create data that compresses well but exceeds limit when decompressed
  16059. // 8KB of repeated null bytes compresses to a very small size
  16060. std::string original_data(8 * 1024, '\0');
  16061. // Compress the data using gzip
  16062. std::string compressed_data;
  16063. detail::gzip_compressor compressor;
  16064. compressor.compress(original_data.data(), original_data.size(), true,
  16065. [&](const char *data, size_t size) {
  16066. compressed_data.append(data, size);
  16067. return true;
  16068. });
  16069. // Verify compression worked (compressed should be much smaller)
  16070. ASSERT_LT(compressed_data.size(), original_data.size());
  16071. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16072. // Send compressed data with Content-Encoding: gzip
  16073. Client cli(HOST, PORT);
  16074. Headers headers = {{"Content-Encoding", "gzip"}};
  16075. auto res =
  16076. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16077. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16079. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16080. }
  16081. #endif
  16082. // ============================================================================
  16083. // OpenSSL-Specific Tests
  16084. // ============================================================================
  16085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16086. X509 *readCertificate(const std::string &strFileName) {
  16087. std::ifstream inStream(strFileName);
  16088. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16089. std::istreambuf_iterator<char>());
  16090. if (strCertPEM.empty()) return (nullptr);
  16091. BIO *pbCert = BIO_new(BIO_s_mem());
  16092. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16093. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16094. BIO_free(pbCert);
  16095. return (pCert);
  16096. }
  16097. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16098. std::ifstream inStream(strFileName);
  16099. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16100. std::istreambuf_iterator<char>());
  16101. if (strPrivateKeyPEM.empty()) return (nullptr);
  16102. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16103. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16104. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16105. BIO_free(pbPrivKey);
  16106. return (pPrivateKey);
  16107. }
  16108. TEST(BindServerTest, UpdateCerts) {
  16109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16110. int port = svr.bind_to_any_port("0.0.0.0");
  16111. ASSERT_TRUE(svr.is_valid());
  16112. ASSERT_TRUE(port > 0);
  16113. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16114. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16115. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16116. ASSERT_TRUE(cert != nullptr);
  16117. ASSERT_TRUE(ca_cert != nullptr);
  16118. ASSERT_TRUE(key != nullptr);
  16119. X509_STORE *cert_store = X509_STORE_new();
  16120. X509_STORE_add_cert(cert_store, ca_cert);
  16121. // svr.update_certs(cert, key, cert_store); // deprecated
  16122. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16123. CLIENT_CA_CERT_FILE);
  16124. ASSERT_TRUE(svr.is_valid());
  16125. svr.stop();
  16126. X509_STORE_free(cert_store);
  16127. X509_free(cert);
  16128. X509_free(ca_cert);
  16129. EVP_PKEY_free(key);
  16130. }
  16131. // Test that update_certs() updates client CA list correctly
  16132. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16133. // Start with file-based constructor
  16134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16135. ASSERT_TRUE(svr.is_valid());
  16136. // Initially no client CA list should be set
  16137. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16138. ASSERT_TRUE(ssl_ctx != nullptr);
  16139. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16140. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16141. EXPECT_EQ(0, count_before);
  16142. // Now update with client CA (PEM string)
  16143. std::string cert_pem, key_pem, ca_pem;
  16144. read_file(SERVER_CERT_FILE, cert_pem);
  16145. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16146. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16147. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16148. ASSERT_TRUE(svr.is_valid());
  16149. // Now client CA list should be set
  16150. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16151. ASSERT_TRUE(ca_list_after != nullptr);
  16152. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16153. }
  16154. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16155. // Test that the file-path SSLServer constructor properly sets the client CA
  16156. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16158. ASSERT_TRUE(svr.is_valid());
  16159. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16160. ASSERT_TRUE(ssl_ctx != nullptr);
  16161. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16162. ASSERT_TRUE(ca_list != nullptr);
  16163. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16164. }
  16165. #endif
  16166. // ============================================================================
  16167. // MbedTLS-Specific Tests
  16168. // ============================================================================
  16169. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16170. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16171. using namespace httplib::tls;
  16172. // Track if callback was invoked
  16173. bool callback_invoked = false;
  16174. // The callback receives void* ctx which is actually MbedTlsContext*
  16175. // We can access the mbedtls_ssl_config via the context
  16176. auto setup_callback = [&callback_invoked](void *ctx) {
  16177. callback_invoked = true;
  16178. // Cast to MbedTlsContext* to access the ssl config
  16179. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16180. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16181. // Use static variables to hold certificate data (simplified for test)
  16182. static mbedtls_x509_crt own_cert;
  16183. static mbedtls_pk_context own_key;
  16184. static mbedtls_x509_crt ca_chain;
  16185. static bool initialized = false;
  16186. if (!initialized) {
  16187. mbedtls_x509_crt_init(&own_cert);
  16188. mbedtls_pk_init(&own_key);
  16189. mbedtls_x509_crt_init(&ca_chain);
  16190. // Load server certificate
  16191. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16192. return false;
  16193. }
  16194. // Load server private key.
  16195. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16196. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16197. #if MBEDTLS_VERSION_MAJOR == 3
  16198. ,
  16199. mbedtls_ctr_drbg_random, nullptr
  16200. #endif
  16201. ) != 0) {
  16202. return false;
  16203. }
  16204. // Load CA chain for client verification
  16205. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16206. return false;
  16207. }
  16208. initialized = true;
  16209. }
  16210. // Configure the SSL config
  16211. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16212. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16213. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16214. // Set minimum TLS version using mbedTLS native API
  16215. #if MBEDTLS_VERSION_MAJOR >= 3
  16216. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16217. #else
  16218. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16219. MBEDTLS_SSL_MINOR_VERSION_3);
  16220. #endif
  16221. return true;
  16222. };
  16223. SSLServer svr(setup_callback);
  16224. ASSERT_TRUE(svr.is_valid());
  16225. ASSERT_TRUE(callback_invoked);
  16226. svr.Get("/test", [&](const Request &req, Response &res) {
  16227. res.set_content("test", "text/plain");
  16228. auto cert = req.peer_cert();
  16229. ASSERT_TRUE(static_cast<bool>(cert));
  16230. auto common_name = cert.subject_cn();
  16231. EXPECT_EQ("Common Name", common_name);
  16232. });
  16233. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16234. auto se = detail::scope_exit([&] {
  16235. svr.stop();
  16236. t.join();
  16237. ASSERT_FALSE(svr.is_running());
  16238. });
  16239. svr.wait_until_ready();
  16240. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16241. cli.enable_server_certificate_verification(false);
  16242. cli.set_connection_timeout(30);
  16243. auto res = cli.Get("/test");
  16244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16245. ASSERT_EQ(StatusCode::OK_200, res->status);
  16246. }
  16247. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16248. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16249. // keep-alive SSL session, which reads through that config in
  16250. // mbedtls_ssl_close_notify.
  16251. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16252. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16253. ASSERT_TRUE(svr.is_valid());
  16254. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16255. res.set_content("test", "text/plain");
  16256. });
  16257. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16258. auto se = detail::scope_exit([&] {
  16259. svr.stop();
  16260. t.join();
  16261. ASSERT_FALSE(svr.is_running());
  16262. });
  16263. svr.wait_until_ready();
  16264. {
  16265. SSLClient cli(HOST, PORT);
  16266. cli.enable_server_certificate_verification(false);
  16267. cli.set_keep_alive(true);
  16268. auto res = cli.Get("/test");
  16269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16270. ASSERT_EQ(StatusCode::OK_200, res->status);
  16271. // cli is destructed here with the keep-alive SSL session still open.
  16272. }
  16273. }
  16274. #endif
  16275. // WebSocket Tests
  16276. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16277. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16278. // defining the meaning of these bits has been negotiated.
  16279. auto make_frame = [](uint8_t first_byte) {
  16280. std::string frame;
  16281. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16282. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16283. frame += "Hello";
  16284. return frame;
  16285. };
  16286. // RSV1 set (0x40)
  16287. {
  16288. detail::BufferStream strm;
  16289. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16290. ws::Opcode opcode;
  16291. std::string payload;
  16292. bool fin;
  16293. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16294. false, 1024));
  16295. }
  16296. // RSV2 set (0x20)
  16297. {
  16298. detail::BufferStream strm;
  16299. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16300. ws::Opcode opcode;
  16301. std::string payload;
  16302. bool fin;
  16303. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16304. false, 1024));
  16305. }
  16306. // RSV3 set (0x10)
  16307. {
  16308. detail::BufferStream strm;
  16309. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16310. ws::Opcode opcode;
  16311. std::string payload;
  16312. bool fin;
  16313. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16314. false, 1024));
  16315. }
  16316. // No RSV bits set - should succeed
  16317. {
  16318. detail::BufferStream strm;
  16319. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16320. ws::Opcode opcode;
  16321. std::string payload;
  16322. bool fin;
  16323. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16324. false, 1024));
  16325. EXPECT_EQ(ws::Opcode::Text, opcode);
  16326. EXPECT_EQ("Hello", payload);
  16327. EXPECT_TRUE(fin);
  16328. }
  16329. }
  16330. TEST(WebSocketTest, ControlFrameValidation) {
  16331. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16332. // payload length <= 125.
  16333. // Ping with FIN=0 - must be rejected
  16334. {
  16335. detail::BufferStream strm;
  16336. std::string frame;
  16337. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16338. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16339. strm.write(frame.data(), frame.size());
  16340. ws::Opcode opcode;
  16341. std::string payload;
  16342. bool fin;
  16343. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16344. false, 1024));
  16345. }
  16346. // Close with FIN=0 - must be rejected
  16347. {
  16348. detail::BufferStream strm;
  16349. std::string frame;
  16350. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16351. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16352. strm.write(frame.data(), frame.size());
  16353. ws::Opcode opcode;
  16354. std::string payload;
  16355. bool fin;
  16356. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16357. false, 1024));
  16358. }
  16359. // Ping with payload_len=126 (extended length) - must be rejected
  16360. {
  16361. detail::BufferStream strm;
  16362. std::string frame;
  16363. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16364. frame += static_cast<char>(126); // payload_len=126 (>125)
  16365. frame += static_cast<char>(0x00); // extended length high byte
  16366. frame += static_cast<char>(126); // extended length low byte
  16367. frame += std::string(126, 'x');
  16368. strm.write(frame.data(), frame.size());
  16369. ws::Opcode opcode;
  16370. std::string payload;
  16371. bool fin;
  16372. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16373. false, 1024));
  16374. }
  16375. // Ping with FIN=1 and payload_len=125 - should succeed
  16376. {
  16377. detail::BufferStream strm;
  16378. std::string frame;
  16379. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16380. frame += static_cast<char>(125); // payload_len=125
  16381. frame += std::string(125, 'x');
  16382. strm.write(frame.data(), frame.size());
  16383. ws::Opcode opcode;
  16384. std::string payload;
  16385. bool fin;
  16386. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16387. false, 1024));
  16388. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16389. EXPECT_EQ(125u, payload.size());
  16390. EXPECT_TRUE(fin);
  16391. }
  16392. }
  16393. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16394. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16395. // length MUST be 0.
  16396. // MSB set - must be rejected
  16397. {
  16398. detail::BufferStream strm;
  16399. std::string frame;
  16400. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16401. frame += static_cast<char>(127); // 64-bit extended length
  16402. frame += static_cast<char>(0x80); // MSB set (invalid)
  16403. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16404. strm.write(frame.data(), frame.size());
  16405. ws::Opcode opcode;
  16406. std::string payload;
  16407. bool fin;
  16408. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16409. false, 1024));
  16410. }
  16411. // MSB clear - should pass length parsing (will be rejected by max_len,
  16412. // but that's a different check; use a small length to verify)
  16413. {
  16414. detail::BufferStream strm;
  16415. std::string frame;
  16416. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16417. frame += static_cast<char>(127); // 64-bit extended length
  16418. frame += std::string(7, '\0'); // high bytes = 0
  16419. frame += static_cast<char>(0x03); // length = 3
  16420. frame += "abc";
  16421. strm.write(frame.data(), frame.size());
  16422. ws::Opcode opcode;
  16423. std::string payload;
  16424. bool fin;
  16425. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16426. false, 1024));
  16427. EXPECT_EQ(ws::Opcode::Text, opcode);
  16428. EXPECT_EQ("abc", payload);
  16429. }
  16430. }
  16431. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16432. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16433. // Valid UTF-8
  16434. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16435. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16436. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16437. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16438. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16439. // Invalid UTF-8
  16440. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16441. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16442. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16443. EXPECT_FALSE(
  16444. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16445. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16446. }
  16447. TEST(WebSocketTest, ConnectAndDisconnect) {
  16448. Server svr;
  16449. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16450. std::string msg;
  16451. while (ws.read(msg)) {}
  16452. });
  16453. auto port = svr.bind_to_any_port(HOST);
  16454. std::thread t([&]() { svr.listen_after_bind(); });
  16455. svr.wait_until_ready();
  16456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16457. ASSERT_TRUE(client.connect());
  16458. EXPECT_TRUE(client.is_open());
  16459. client.close();
  16460. EXPECT_FALSE(client.is_open());
  16461. svr.stop();
  16462. t.join();
  16463. }
  16464. TEST(WebSocketTest, ValidURL) {
  16465. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16466. EXPECT_TRUE(ws1.is_valid());
  16467. ws::WebSocketClient ws2("ws://example.com/path");
  16468. EXPECT_TRUE(ws2.is_valid());
  16469. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16470. EXPECT_TRUE(ws3.is_valid());
  16471. #ifdef CPPHTTPLIB_SSL_ENABLED
  16472. ws::WebSocketClient wss1("wss://example.com/path");
  16473. EXPECT_TRUE(wss1.is_valid());
  16474. ws::WebSocketClient wss2("wss://example.com:443/path");
  16475. EXPECT_TRUE(wss2.is_valid());
  16476. #endif
  16477. }
  16478. TEST(WebSocketTest, InvalidURL) {
  16479. // No scheme
  16480. ws::WebSocketClient ws1("localhost:8080/path");
  16481. EXPECT_FALSE(ws1.is_valid());
  16482. // No path
  16483. ws::WebSocketClient ws2("ws://localhost:8080");
  16484. EXPECT_FALSE(ws2.is_valid());
  16485. // Empty string
  16486. ws::WebSocketClient ws3("");
  16487. EXPECT_FALSE(ws3.is_valid());
  16488. // Missing host
  16489. ws::WebSocketClient ws4("ws://:8080/path");
  16490. EXPECT_FALSE(ws4.is_valid());
  16491. // Port number overflow — should not crash
  16492. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16493. EXPECT_FALSE(ws5.is_valid());
  16494. // Port out of range
  16495. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16496. EXPECT_FALSE(ws6.is_valid());
  16497. }
  16498. TEST(WebSocketTest, UnsupportedScheme) {
  16499. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16500. ws::WebSocketClient ws1("http://localhost:8080/path");
  16501. EXPECT_FALSE(ws1.is_valid());
  16502. ws::WebSocketClient ws2("https://localhost:8080/path");
  16503. EXPECT_FALSE(ws2.is_valid());
  16504. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16505. EXPECT_FALSE(ws3.is_valid());
  16506. #else
  16507. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16508. std::invalid_argument);
  16509. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16510. std::invalid_argument);
  16511. #endif
  16512. }
  16513. TEST(WebSocketTest, ConnectWhenInvalid) {
  16514. ws::WebSocketClient ws("not a valid url");
  16515. EXPECT_FALSE(ws.is_valid());
  16516. EXPECT_FALSE(ws.connect());
  16517. }
  16518. TEST(WebSocketTest, DefaultPort) {
  16519. ws::WebSocketClient ws1("ws://example.com/path");
  16520. EXPECT_TRUE(ws1.is_valid());
  16521. // ws:// defaults to port 80 (verified by successful parse)
  16522. #ifdef CPPHTTPLIB_SSL_ENABLED
  16523. ws::WebSocketClient ws2("wss://example.com/path");
  16524. EXPECT_TRUE(ws2.is_valid());
  16525. // wss:// defaults to port 443 (verified by successful parse)
  16526. #endif
  16527. }
  16528. TEST(WebSocketTest, IPv6LiteralAddress) {
  16529. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16530. EXPECT_TRUE(ws1.is_valid());
  16531. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16532. EXPECT_TRUE(ws2.is_valid());
  16533. }
  16534. TEST(WebSocketTest, ComplexPath) {
  16535. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16536. EXPECT_TRUE(ws1.is_valid());
  16537. ws::WebSocketClient ws2("ws://localhost:8080/");
  16538. EXPECT_TRUE(ws2.is_valid());
  16539. }
  16540. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16541. Server svr;
  16542. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16543. std::string msg;
  16544. while (ws.read(msg)) {}
  16545. });
  16546. auto port = svr.bind_to_any_port(HOST);
  16547. std::thread t([&]() { svr.listen_after_bind(); });
  16548. svr.wait_until_ready();
  16549. auto another_host = "example.com";
  16550. auto wrong_ip = "192.0.2.1";
  16551. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16552. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16553. ASSERT_TRUE(client.connect());
  16554. EXPECT_TRUE(client.is_open());
  16555. client.close();
  16556. svr.stop();
  16557. t.join();
  16558. }
  16559. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16560. Server svr;
  16561. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16562. std::string msg;
  16563. while (ws.read(msg)) {}
  16564. });
  16565. auto port = svr.bind_to_any_port(HOST);
  16566. std::thread t([&]() { svr.listen_after_bind(); });
  16567. svr.wait_until_ready();
  16568. auto wrong_ip = "192.0.2.1";
  16569. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16570. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16571. client.set_connection_timeout(1);
  16572. client.set_read_timeout(1);
  16573. client.set_write_timeout(1);
  16574. EXPECT_FALSE(client.connect());
  16575. EXPECT_FALSE(client.is_open());
  16576. svr.stop();
  16577. t.join();
  16578. }
  16579. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16580. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16581. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16582. // (RFC 6761) is only a map key and the Host header value.
  16583. auto host = "target.invalid";
  16584. Server svr;
  16585. std::string received_host;
  16586. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16587. received_host = req.get_header_value("Host");
  16588. std::string msg;
  16589. while (ws.read(msg)) {}
  16590. });
  16591. auto port = svr.bind_to_any_port(HOST);
  16592. std::thread t([&]() { svr.listen_after_bind(); });
  16593. // ASSERT_* below returns from the test body, which would leave t joinable
  16594. // and make ~thread call std::terminate.
  16595. auto se = detail::scope_exit([&] {
  16596. svr.stop();
  16597. if (t.joinable()) { t.join(); }
  16598. });
  16599. svr.wait_until_ready();
  16600. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16601. std::to_string(port) + "/ws");
  16602. client.set_hostname_addr_map({{host, HOST}});
  16603. ASSERT_TRUE(client.connect());
  16604. EXPECT_TRUE(client.is_open());
  16605. client.close();
  16606. svr.stop();
  16607. t.join();
  16608. // The mapping only redirects the connection; the identity stays host_.
  16609. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16610. }
  16611. class WebSocketIntegrationTest : public ::testing::Test {
  16612. protected:
  16613. void SetUp() override {
  16614. server_ = httplib::detail::make_unique<Server>();
  16615. setup_server();
  16616. start_server();
  16617. }
  16618. void TearDown() override {
  16619. server_->stop();
  16620. if (server_thread_.joinable()) { server_thread_.join(); }
  16621. }
  16622. void setup_server() {
  16623. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16624. std::string msg;
  16625. ws::ReadResult ret;
  16626. while ((ret = ws.read(msg))) {
  16627. if (ret == ws::Binary) {
  16628. ws.send(msg.data(), msg.size());
  16629. } else {
  16630. ws.send(msg);
  16631. }
  16632. }
  16633. });
  16634. server_->WebSocket("/ws-echo-string",
  16635. [](const Request &, ws::WebSocket &ws) {
  16636. std::string msg;
  16637. while (ws.read(msg)) {
  16638. ws.send("echo: " + msg);
  16639. }
  16640. });
  16641. server_->WebSocket(
  16642. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16643. // Echo back request metadata
  16644. ws.send("path:" + req.path);
  16645. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16646. std::string msg;
  16647. while (ws.read(msg)) {}
  16648. });
  16649. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16650. std::string msg;
  16651. ws.read(msg); // wait for a message
  16652. ws.close();
  16653. });
  16654. server_->WebSocket("/ws-close-status",
  16655. [](const Request &, ws::WebSocket &ws) {
  16656. std::string msg;
  16657. ws.read(msg); // wait for a message
  16658. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16659. });
  16660. server_->WebSocket(
  16661. "/ws-subprotocol",
  16662. [](const Request &, ws::WebSocket &ws) {
  16663. std::string msg;
  16664. while (ws.read(msg)) {
  16665. ws.send(msg);
  16666. }
  16667. },
  16668. [](const std::vector<std::string> &protocols) -> std::string {
  16669. for (const auto &p : protocols) {
  16670. if (p == "graphql-ws") { return p; }
  16671. }
  16672. return "";
  16673. });
  16674. }
  16675. void start_server() {
  16676. port_ = server_->bind_to_any_port(HOST);
  16677. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16678. server_->wait_until_ready();
  16679. }
  16680. std::unique_ptr<Server> server_;
  16681. std::thread server_thread_;
  16682. int port_ = 0;
  16683. };
  16684. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16685. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16686. "/ws-echo");
  16687. ASSERT_TRUE(client.connect());
  16688. ASSERT_TRUE(client.is_open());
  16689. ASSERT_TRUE(client.send("Hello WebSocket"));
  16690. std::string msg;
  16691. EXPECT_EQ(ws::Text, client.read(msg));
  16692. EXPECT_EQ("Hello WebSocket", msg);
  16693. client.close();
  16694. }
  16695. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16696. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16697. "/ws-echo");
  16698. ASSERT_TRUE(client.connect());
  16699. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16700. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16701. std::string msg;
  16702. EXPECT_EQ(ws::Binary, client.read(msg));
  16703. EXPECT_EQ(binary_data, msg);
  16704. client.close();
  16705. }
  16706. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16708. "/ws-echo");
  16709. ASSERT_TRUE(client.connect());
  16710. for (int i = 0; i < 10; i++) {
  16711. auto text = "message " + std::to_string(i);
  16712. ASSERT_TRUE(client.send(text));
  16713. std::string msg;
  16714. ASSERT_TRUE(client.read(msg));
  16715. EXPECT_EQ(text, msg);
  16716. }
  16717. client.close();
  16718. }
  16719. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16721. "/ws-close");
  16722. ASSERT_TRUE(client.connect());
  16723. // Send a message to trigger the server to close
  16724. ASSERT_TRUE(client.send("trigger close"));
  16725. // The server will close, so read should return false
  16726. std::string msg;
  16727. EXPECT_FALSE(client.read(msg));
  16728. EXPECT_FALSE(client.is_open());
  16729. }
  16730. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16732. "/ws-echo");
  16733. ASSERT_TRUE(client.connect());
  16734. // 128KB message
  16735. std::string large_data(128 * 1024, 'X');
  16736. ASSERT_TRUE(client.send(large_data));
  16737. std::string msg;
  16738. ASSERT_TRUE(client.read(msg));
  16739. EXPECT_EQ(large_data, msg);
  16740. client.close();
  16741. }
  16742. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16743. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16744. "/ws-echo");
  16745. ASSERT_TRUE(client.connect());
  16746. const int num_threads = 4;
  16747. std::vector<std::thread> threads;
  16748. std::atomic<int> send_count{0};
  16749. for (int t = 0; t < num_threads; t++) {
  16750. threads.emplace_back([&client, &send_count, t]() {
  16751. for (int i = 0; i < 5; i++) {
  16752. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16753. if (client.send(text)) { send_count++; }
  16754. }
  16755. });
  16756. }
  16757. for (auto &th : threads) {
  16758. th.join();
  16759. }
  16760. int received = 0;
  16761. std::string msg;
  16762. while (received < send_count.load()) {
  16763. if (!client.read(msg)) { break; }
  16764. received++;
  16765. }
  16766. EXPECT_EQ(send_count.load(), received);
  16767. client.close();
  16768. }
  16769. TEST_F(WebSocketIntegrationTest, ReadString) {
  16770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16771. "/ws-echo-string");
  16772. ASSERT_TRUE(client.connect());
  16773. ASSERT_TRUE(client.send("hello"));
  16774. std::string msg;
  16775. ASSERT_TRUE(client.read(msg));
  16776. EXPECT_EQ("echo: hello", msg);
  16777. ASSERT_TRUE(client.send("world"));
  16778. ASSERT_TRUE(client.read(msg));
  16779. EXPECT_EQ("echo: world", msg);
  16780. client.close();
  16781. }
  16782. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16783. Headers headers = {{"X-Test-Header", "test-value"}};
  16784. ws::WebSocketClient client(
  16785. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16786. ASSERT_TRUE(client.connect());
  16787. std::string msg;
  16788. ASSERT_TRUE(client.read(msg));
  16789. EXPECT_EQ("path:/ws-request-info", msg);
  16790. ASSERT_TRUE(client.read(msg));
  16791. EXPECT_EQ("header:test-value", msg);
  16792. client.close();
  16793. }
  16794. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16795. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16796. "/ws-echo");
  16797. client.set_read_timeout(1, 0); // 1 second
  16798. ASSERT_TRUE(client.connect());
  16799. // Don't send anything — server echo handler waits for a message,
  16800. // so read() should time out and return false.
  16801. std::string msg;
  16802. EXPECT_FALSE(client.read(msg));
  16803. }
  16804. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16805. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16806. "/ws-echo");
  16807. client.set_read_timeout(5, 0);
  16808. ASSERT_TRUE(client.connect());
  16809. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16810. // The server should reject it and close the connection.
  16811. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16812. client.send(oversized);
  16813. // The server's read() should have failed due to payload limit,
  16814. // so our read() should return false (connection closed).
  16815. std::string msg;
  16816. EXPECT_FALSE(client.read(msg));
  16817. }
  16818. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16820. "/ws-echo");
  16821. client.set_read_timeout(10, 0);
  16822. ASSERT_TRUE(client.connect());
  16823. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16824. // This should succeed.
  16825. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16826. ASSERT_TRUE(client.send(at_limit));
  16827. std::string msg;
  16828. ASSERT_TRUE(client.read(msg));
  16829. EXPECT_EQ(at_limit.size(), msg.size());
  16830. client.close();
  16831. }
  16832. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16834. "/nonexistent");
  16835. EXPECT_FALSE(client.connect());
  16836. EXPECT_FALSE(client.is_open());
  16837. }
  16838. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16840. "/ws-echo");
  16841. ASSERT_TRUE(client.connect());
  16842. ASSERT_TRUE(client.send(""));
  16843. std::string msg;
  16844. EXPECT_EQ(ws::Text, client.read(msg));
  16845. EXPECT_EQ("", msg);
  16846. client.close();
  16847. }
  16848. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16850. "/ws-echo");
  16851. // First connection
  16852. ASSERT_TRUE(client.connect());
  16853. ASSERT_TRUE(client.send("first"));
  16854. std::string msg;
  16855. ASSERT_TRUE(client.read(msg));
  16856. EXPECT_EQ("first", msg);
  16857. client.close();
  16858. EXPECT_FALSE(client.is_open());
  16859. // Reconnect using the same client object
  16860. ASSERT_TRUE(client.connect());
  16861. ASSERT_TRUE(client.is_open());
  16862. ASSERT_TRUE(client.send("second"));
  16863. ASSERT_TRUE(client.read(msg));
  16864. EXPECT_EQ("second", msg);
  16865. client.close();
  16866. }
  16867. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16869. "/ws-close-status");
  16870. ASSERT_TRUE(client.connect());
  16871. // Trigger the server to close with GoingAway status
  16872. ASSERT_TRUE(client.send("trigger"));
  16873. // read() should return false after receiving the close frame
  16874. std::string msg;
  16875. EXPECT_FALSE(client.read(msg));
  16876. EXPECT_FALSE(client.is_open());
  16877. }
  16878. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16880. "/ws-echo");
  16881. ASSERT_TRUE(client.connect());
  16882. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16883. EXPECT_FALSE(client.is_open());
  16884. }
  16885. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16886. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16887. ws::WebSocketClient client(
  16888. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16889. ASSERT_TRUE(client.connect());
  16890. // Server should have selected graphql-ws
  16891. EXPECT_EQ("graphql-ws", client.subprotocol());
  16892. client.close();
  16893. }
  16894. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16895. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16896. ws::WebSocketClient client(
  16897. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16898. ASSERT_TRUE(client.connect());
  16899. // Server should not have selected any subprotocol
  16900. EXPECT_TRUE(client.subprotocol().empty());
  16901. client.close();
  16902. }
  16903. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16904. // Connect without requesting any subprotocol
  16905. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16906. "/ws-subprotocol");
  16907. ASSERT_TRUE(client.connect());
  16908. EXPECT_TRUE(client.subprotocol().empty());
  16909. client.close();
  16910. }
  16911. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16913. "/ws-echo");
  16914. client.set_tcp_nodelay(true);
  16915. client.set_connection_timeout(3, 0);
  16916. bool socket_options_called = false;
  16917. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16918. ASSERT_TRUE(client.connect());
  16919. ASSERT_TRUE(client.is_open());
  16920. EXPECT_TRUE(socket_options_called);
  16921. ASSERT_TRUE(client.send("hello"));
  16922. std::string msg;
  16923. auto result = client.read(msg);
  16924. EXPECT_EQ(result, ws::ReadResult::Text);
  16925. EXPECT_EQ(msg, "hello");
  16926. client.close();
  16927. }
  16928. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16929. Server svr;
  16930. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16931. if (!req.has_header("Authorization")) {
  16932. res.status = StatusCode::Unauthorized_401;
  16933. res.set_content("Unauthorized", "text/plain");
  16934. return Server::HandlerResponse::Handled;
  16935. }
  16936. return Server::HandlerResponse::Unhandled;
  16937. });
  16938. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16939. std::string msg;
  16940. while (ws.read(msg)) {
  16941. ws.send(msg);
  16942. }
  16943. });
  16944. auto port = svr.bind_to_any_port("localhost");
  16945. std::thread t([&]() { svr.listen_after_bind(); });
  16946. svr.wait_until_ready();
  16947. // Without Authorization header - should be rejected before upgrade
  16948. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16949. EXPECT_FALSE(client1.connect());
  16950. // With Authorization header - should succeed
  16951. Headers headers = {{"Authorization", "Bearer token123"}};
  16952. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16953. headers);
  16954. ASSERT_TRUE(client2.connect());
  16955. ASSERT_TRUE(client2.send("hello"));
  16956. std::string msg;
  16957. ASSERT_TRUE(client2.read(msg));
  16958. EXPECT_EQ("hello", msg);
  16959. client2.close();
  16960. svr.stop();
  16961. t.join();
  16962. }
  16963. TEST(WebSocketTest, QueryStringInHandshake) {
  16964. Server svr;
  16965. std::mutex mtx;
  16966. std::string received_target;
  16967. std::string received_token;
  16968. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16969. {
  16970. std::lock_guard<std::mutex> lock(mtx);
  16971. received_target = req.target;
  16972. if (req.has_param("token")) {
  16973. received_token = req.get_param_value("token");
  16974. }
  16975. }
  16976. std::string msg;
  16977. while (ws.read(msg)) {
  16978. ws.send(msg);
  16979. }
  16980. });
  16981. auto port = svr.bind_to_any_port("localhost");
  16982. std::thread t([&]() { svr.listen_after_bind(); });
  16983. svr.wait_until_ready();
  16984. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16985. "/ws?token=ABC&session=123");
  16986. ASSERT_TRUE(client.connect());
  16987. // Round-trip ensures the handler has run and captured the request.
  16988. ASSERT_TRUE(client.send("hello"));
  16989. std::string msg;
  16990. ASSERT_TRUE(client.read(msg));
  16991. EXPECT_EQ("hello", msg);
  16992. client.close();
  16993. {
  16994. std::lock_guard<std::mutex> lock(mtx);
  16995. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16996. EXPECT_EQ("ABC", received_token);
  16997. }
  16998. svr.stop();
  16999. t.join();
  17000. }
  17001. // Run a handshake against a throwaway server and hand the request the server
  17002. // received back to the caller, so tests can assert on the headers the client
  17003. // actually put on the wire.
  17004. static void capture_websocket_handshake_request(
  17005. const Headers &client_headers,
  17006. std::function<void(const Request &, int port)> verify) {
  17007. Server svr;
  17008. std::mutex mtx;
  17009. Request received;
  17010. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17011. {
  17012. std::lock_guard<std::mutex> lock(mtx);
  17013. received = req;
  17014. }
  17015. std::string msg;
  17016. while (ws.read(msg)) {
  17017. ws.send(msg);
  17018. }
  17019. });
  17020. auto port = svr.bind_to_any_port("localhost");
  17021. std::thread t([&]() { svr.listen_after_bind(); });
  17022. auto se = detail::scope_exit([&] {
  17023. svr.stop();
  17024. t.join();
  17025. });
  17026. svr.wait_until_ready();
  17027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17028. client_headers);
  17029. ASSERT_TRUE(client.connect());
  17030. ASSERT_TRUE(client.send("hello"));
  17031. std::string msg;
  17032. ASSERT_TRUE(client.read(msg));
  17033. client.close();
  17034. {
  17035. std::lock_guard<std::mutex> lock(mtx);
  17036. verify(received, port);
  17037. }
  17038. }
  17039. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17040. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17041. // Non-default port must be present in the Host header. Default ports
  17042. // (80/443) are omitted; that logic is covered by
  17043. // MakeHostAndPortStringTest.
  17044. EXPECT_EQ("localhost:" + std::to_string(port),
  17045. req.get_header_value("Host"));
  17046. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17047. req.get_header_value("User-Agent"));
  17048. EXPECT_FALSE(req.has_header("Accept"));
  17049. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17050. EXPECT_FALSE(req.has_header("Content-Length"));
  17051. });
  17052. }
  17053. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17054. capture_websocket_handshake_request(
  17055. {{"Host", "example.com"},
  17056. {"User-Agent", "custom-agent"},
  17057. {"X-Custom", "value"}},
  17058. [](const Request &req, int) {
  17059. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17060. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17061. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17062. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17063. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17064. });
  17065. }
  17066. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17067. capture_websocket_handshake_request(
  17068. {{"Upgrade", "bogus"},
  17069. {"Connection", "close"},
  17070. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17071. {"Sec-WebSocket-Version", "8"}},
  17072. [](const Request &req, int) {
  17073. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17074. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17075. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17076. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17077. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17078. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17079. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17080. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17081. req.get_header_value("Sec-WebSocket-Key"));
  17082. });
  17083. }
  17084. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17085. // A header the client refuses to send must abort the handshake before any
  17086. // part of it reaches the wire; a lone request line would otherwise sit in
  17087. // the peer's buffer as a truncated request.
  17088. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17089. ASSERT_NE(INVALID_SOCKET, srv);
  17090. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17091. sockaddr_in addr{};
  17092. addr.sin_family = AF_INET;
  17093. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17095. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17096. ASSERT_EQ(0, ::listen(srv, 1));
  17097. sockaddr_in bound{};
  17098. socklen_t bound_len = sizeof(bound);
  17099. ASSERT_EQ(
  17100. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17101. auto port = ntohs(bound.sin_port);
  17102. ssize_t received = -1;
  17103. std::thread t([&] {
  17104. // Bound every blocking call so a regression fails the test with a bad
  17105. // value instead of hanging the suite.
  17106. fd_set rfds;
  17107. FD_ZERO(&rfds);
  17108. FD_SET(srv, &rfds);
  17109. timeval tv{5, 0};
  17110. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17111. 0) {
  17112. return;
  17113. }
  17114. sockaddr_in cli_addr{};
  17115. socklen_t cli_len = sizeof(cli_addr);
  17116. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17117. if (cli == INVALID_SOCKET) { return; }
  17118. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17119. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17120. char buf[4096];
  17121. received = ::recv(cli, buf, sizeof(buf), 0);
  17122. });
  17123. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17124. // connect() has already shut the socket down by the time it returns false,
  17125. // so the peer sees EOF without waiting for the client to be destroyed.
  17126. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17127. {{"X-Bad", "a\r\nInjected: 1"}});
  17128. EXPECT_FALSE(client.connect());
  17129. t.join();
  17130. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17131. EXPECT_EQ(0, received);
  17132. }
  17133. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17134. // The socket path doubles as the URL host, so it must not contain '/'.
  17135. const char *shard = getenv("GTEST_SHARD_INDEX");
  17136. const std::string sock_path =
  17137. shard ? std::string("httplib-ws-") + shard + ".sock"
  17138. : std::string("httplib-ws.sock");
  17139. std::remove(sock_path.c_str());
  17140. Server svr;
  17141. std::mutex mtx;
  17142. std::string received_host;
  17143. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17144. {
  17145. std::lock_guard<std::mutex> lock(mtx);
  17146. received_host = req.get_header_value("Host");
  17147. }
  17148. std::string msg;
  17149. while (ws.read(msg)) {
  17150. ws.send(msg);
  17151. }
  17152. });
  17153. svr.set_address_family(AF_UNIX);
  17154. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17155. auto se = detail::scope_exit([&] {
  17156. svr.stop();
  17157. t.join();
  17158. std::remove(sock_path.c_str());
  17159. });
  17160. svr.wait_until_ready();
  17161. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17162. client.set_address_family(AF_UNIX);
  17163. ASSERT_TRUE(client.connect());
  17164. ASSERT_TRUE(client.send("hello"));
  17165. std::string msg;
  17166. ASSERT_TRUE(client.read(msg));
  17167. client.close();
  17168. {
  17169. std::lock_guard<std::mutex> lock(mtx);
  17170. // There is no host:port for a Unix socket, so the same "localhost"
  17171. // placeholder the HTTP client uses is expected.
  17172. EXPECT_EQ("localhost", received_host);
  17173. }
  17174. }
  17175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17176. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17177. protected:
  17178. void SetUp() override {
  17179. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17180. SERVER_PRIVATE_KEY_FILE);
  17181. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17182. std::string msg;
  17183. ws::ReadResult ret;
  17184. while ((ret = ws.read(msg))) {
  17185. if (ret == ws::Binary) {
  17186. ws.send(msg.data(), msg.size());
  17187. } else {
  17188. ws.send(msg);
  17189. }
  17190. }
  17191. });
  17192. port_ = server_->bind_to_any_port(HOST);
  17193. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17194. server_->wait_until_ready();
  17195. }
  17196. void TearDown() override {
  17197. server_->stop();
  17198. if (server_thread_.joinable()) { server_thread_.join(); }
  17199. }
  17200. std::unique_ptr<SSLServer> server_;
  17201. std::thread server_thread_;
  17202. int port_ = 0;
  17203. };
  17204. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17205. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17206. "/ws-echo");
  17207. client.enable_server_certificate_verification(false);
  17208. ASSERT_TRUE(client.connect());
  17209. ASSERT_TRUE(client.is_open());
  17210. ASSERT_TRUE(client.send("Hello WSS"));
  17211. std::string msg;
  17212. EXPECT_EQ(ws::Text, client.read(msg));
  17213. EXPECT_EQ("Hello WSS", msg);
  17214. client.close();
  17215. }
  17216. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17217. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17218. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17219. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17220. // client (without calling close() first) is the only path that runs
  17221. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17222. // bug exactly.
  17223. //
  17224. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17225. // when linked against an instrumented libssl; run under Valgrind to catch it
  17226. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17227. // suite (the freed session otherwise stalls on the close handshake) — this test
  17228. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17229. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17230. {
  17231. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17232. "/ws-echo");
  17233. client.enable_server_certificate_verification(false);
  17234. client.set_read_timeout(2, 0);
  17235. client.set_write_timeout(2, 0);
  17236. ASSERT_TRUE(client.connect());
  17237. ASSERT_TRUE(client.is_open());
  17238. ASSERT_TRUE(client.send("still open"));
  17239. // Intentionally do NOT call client.close(): leaving scope runs
  17240. // shutdown_and_close() with the WebSocket still open, which must send the
  17241. // close frame while the TLS session is still alive.
  17242. }
  17243. }
  17244. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17245. // shutdown_and_close() at the start of connect(), reproducing the same
  17246. // use-after-free within the test body rather than at scope exit. The second
  17247. // connect must succeed and echo, proving the close handshake ran over a live
  17248. // session. See the note above about memory-tool requirements.
  17249. TEST_F(WebSocketSSLIntegrationTest,
  17250. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17251. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17252. "/ws-echo");
  17253. client.enable_server_certificate_verification(false);
  17254. client.set_read_timeout(2, 0);
  17255. client.set_write_timeout(2, 0);
  17256. ASSERT_TRUE(client.connect());
  17257. ASSERT_TRUE(client.is_open());
  17258. ASSERT_TRUE(client.send("still open"));
  17259. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17260. // the still-open connection, which must not touch a freed TLS session.
  17261. ASSERT_TRUE(client.connect());
  17262. ASSERT_TRUE(client.is_open());
  17263. ASSERT_TRUE(client.send("after reconnect"));
  17264. std::string msg;
  17265. EXPECT_EQ(ws::Text, client.read(msg));
  17266. EXPECT_EQ("after reconnect", msg);
  17267. client.close();
  17268. }
  17269. #endif
  17270. #ifdef CPPHTTPLIB_SSL_ENABLED
  17271. class WebSocketSSLCATest : public ::testing::Test {
  17272. protected:
  17273. void SetUp() override {
  17274. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17275. SERVER_PRIVATE_KEY_FILE);
  17276. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17277. std::string msg;
  17278. while (ws.read(msg)) {
  17279. ws.send(msg);
  17280. }
  17281. });
  17282. port_ = server_->bind_to_any_port("127.0.0.1");
  17283. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17284. server_->wait_until_ready();
  17285. }
  17286. void TearDown() override {
  17287. server_->stop();
  17288. if (server_thread_.joinable()) { server_thread_.join(); }
  17289. }
  17290. std::string url() const {
  17291. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17292. }
  17293. std::unique_ptr<SSLServer> server_;
  17294. std::thread server_thread_;
  17295. int port_ = 0;
  17296. };
  17297. // A custom CA loaded as PEM verifies the server with full certificate
  17298. // verification enabled
  17299. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17300. ws::WebSocketClient client(url());
  17301. std::string cert;
  17302. read_file(SERVER_CERT2_FILE, cert);
  17303. client.load_ca_cert_store(cert.c_str(), cert.size());
  17304. ASSERT_TRUE(client.connect());
  17305. ASSERT_TRUE(client.send("hello"));
  17306. std::string msg;
  17307. EXPECT_EQ(ws::Text, client.read(msg));
  17308. EXPECT_EQ("hello", msg);
  17309. client.close();
  17310. }
  17311. // A custom CA that does not cover the server must fail verification (the
  17312. // custom CA is exclusive; system certs are not loaded alongside it)
  17313. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17314. ws::WebSocketClient client(url());
  17315. std::string cert;
  17316. read_file(CLIENT_CA_CERT_FILE, cert);
  17317. client.load_ca_cert_store(cert.c_str(), cert.size());
  17318. ASSERT_FALSE(client.connect());
  17319. }
  17320. // Regression test: reconnecting with a native custom CA store used to reuse
  17321. // a store handle the previous TLS context had already freed (use-after-free
  17322. // under the OpenSSL backend). The context now lives as long as the client.
  17323. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17324. ws::WebSocketClient client(url());
  17325. std::string cert;
  17326. read_file(SERVER_CERT2_FILE, cert);
  17327. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17328. ASSERT_TRUE(client.connect());
  17329. client.close();
  17330. ASSERT_TRUE(client.connect());
  17331. ASSERT_TRUE(client.send("again"));
  17332. std::string msg;
  17333. EXPECT_EQ(ws::Text, client.read(msg));
  17334. EXPECT_EQ("again", msg);
  17335. client.close();
  17336. }
  17337. // Regression test: a certificate with a trusted chain but no identity match
  17338. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17339. // verification entirely for IP hosts, so this connection succeeded there.
  17340. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17341. // chain verification while the identity check must still fail.
  17342. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17344. ASSERT_TRUE(svr.is_valid());
  17345. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17346. std::string msg;
  17347. while (ws.read(msg)) {
  17348. ws.send(msg);
  17349. }
  17350. });
  17351. auto port = svr.bind_to_any_port("127.0.0.1");
  17352. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17353. auto se = detail::scope_exit([&] {
  17354. svr.stop();
  17355. t.join();
  17356. });
  17357. svr.wait_until_ready();
  17358. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17359. "/echo");
  17360. std::string cert;
  17361. read_file(SERVER_CERT_FILE, cert);
  17362. client.load_ca_cert_store(cert.c_str(), cert.size());
  17363. ASSERT_FALSE(client.connect());
  17364. }
  17365. #endif
  17366. #if !defined(_WIN32)
  17367. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17368. auto secret_dir = std::string("./symlink_test_secret");
  17369. auto served_dir = std::string("./symlink_test_served");
  17370. auto secret_file = secret_dir + "/secret.txt";
  17371. auto symlink_path = served_dir + "/escape";
  17372. // Setup: create directories and files
  17373. mkdir(secret_dir.c_str(), 0755);
  17374. mkdir(served_dir.c_str(), 0755);
  17375. {
  17376. std::ofstream ofs(secret_file);
  17377. ofs << "SECRET_DATA";
  17378. }
  17379. // Create symlink using absolute path so it resolves correctly
  17380. #ifdef PATH_MAX
  17381. char abs_secret[PATH_MAX];
  17382. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17383. #else
  17384. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17385. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17386. ASSERT_NE(nullptr, abs_secret);
  17387. #endif
  17388. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17389. auto se = detail::scope_exit([&] {
  17390. unlink(symlink_path.c_str());
  17391. unlink(secret_file.c_str());
  17392. rmdir(served_dir.c_str());
  17393. rmdir(secret_dir.c_str());
  17394. });
  17395. Server svr;
  17396. svr.set_mount_point("/", served_dir);
  17397. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17398. auto se2 = detail::scope_exit([&] {
  17399. svr.stop();
  17400. listen_thread.join();
  17401. });
  17402. svr.wait_until_ready();
  17403. Client cli("localhost", PORT);
  17404. // Symlink pointing outside base dir should be blocked
  17405. auto res = cli.Get("/escape/secret.txt");
  17406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17407. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17408. }
  17409. #endif
  17410. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17411. // A GET request with Content-Length to a static file handler must have its
  17412. // body drained before the keep-alive connection is reused. Otherwise the
  17413. // unread body bytes are interpreted as the next HTTP request.
  17414. //
  17415. // The body is sent AFTER receiving the first response (as in the original
  17416. // PoC) so that the stream_line_reader cannot buffer it together with the
  17417. // headers of the first request.
  17418. Server svr;
  17419. svr.set_mount_point("/", "./www");
  17420. std::atomic<int> smuggled_count(0);
  17421. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17422. smuggled_count++;
  17423. res.set_content("oops", "text/plain");
  17424. });
  17425. auto port = svr.bind_to_any_port("localhost");
  17426. thread t = thread([&] { svr.listen_after_bind(); });
  17427. auto se = detail::scope_exit([&] {
  17428. svr.stop();
  17429. t.join();
  17430. });
  17431. svr.wait_until_ready();
  17432. auto error = Error::Success;
  17433. auto sock = detail::create_client_socket(
  17434. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17435. /*connection_timeout_sec=*/2, 0,
  17436. /*read_timeout_sec=*/2, 0,
  17437. /*write_timeout_sec=*/2, 0, std::string(), error);
  17438. ASSERT_NE(INVALID_SOCKET, sock);
  17439. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17440. // The "smuggled" request will be sent as the body of the outer GET
  17441. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17442. "Host: localhost\r\n"
  17443. "Connection: close\r\n"
  17444. "\r\n";
  17445. // Step 1: Send only the outer request headers (no body yet)
  17446. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17447. "Host: localhost\r\n"
  17448. "Content-Length: " +
  17449. std::to_string(smuggled.size()) +
  17450. "\r\n"
  17451. "\r\n";
  17452. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17453. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17454. // Step 2: Read the first response (server serves file without reading body)
  17455. std::string first_response;
  17456. char buf[4096];
  17457. for (;;) {
  17458. auto n = recv(sock, buf, sizeof(buf), 0);
  17459. if (n <= 0) break;
  17460. first_response.append(buf, static_cast<size_t>(n));
  17461. // Stop once we have a complete response (headers + body)
  17462. auto hdr_end = first_response.find("\r\n\r\n");
  17463. if (hdr_end != std::string::npos) {
  17464. // Check for Content-Length to know when the body is complete
  17465. auto cl_pos = first_response.find("Content-Length:");
  17466. if (cl_pos != std::string::npos) {
  17467. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17468. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17469. auto cl = std::stoul(
  17470. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17471. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17472. } else {
  17473. break; // No Content-Length, assume headers-only response
  17474. }
  17475. }
  17476. }
  17477. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17478. // Step 3: Now send the body, which looks like a new HTTP request.
  17479. // On a vulnerable server the keep-alive loop reads this as a second request.
  17480. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17481. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17482. // Step 4: Try to read a second response (should NOT exist after fix)
  17483. std::string second_response;
  17484. for (;;) {
  17485. auto n = recv(sock, buf, sizeof(buf), 0);
  17486. if (n <= 0) break;
  17487. second_response.append(buf, static_cast<size_t>(n));
  17488. }
  17489. // The smuggled request must NOT have been processed
  17490. EXPECT_EQ(0, smuggled_count.load());
  17491. }
  17492. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17493. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17494. // must be rejected with 400 Bad Request.
  17495. Server svr;
  17496. svr.Post("/test", [&](const Request &, Response &res) {
  17497. res.set_content("ok", "text/plain");
  17498. });
  17499. thread t = thread([&] { svr.listen(HOST, PORT); });
  17500. auto se = detail::scope_exit([&] {
  17501. svr.stop();
  17502. t.join();
  17503. ASSERT_FALSE(svr.is_running());
  17504. });
  17505. svr.wait_until_ready();
  17506. // Exact "chunked"
  17507. {
  17508. auto req = "POST /test HTTP/1.1\r\n"
  17509. "Host: localhost\r\n"
  17510. "Content-Length: 5\r\n"
  17511. "Transfer-Encoding: chunked\r\n"
  17512. "Connection: close\r\n"
  17513. "\r\n"
  17514. "hello";
  17515. std::string response;
  17516. ASSERT_TRUE(send_request(1, req, &response));
  17517. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17518. response.substr(0, response.find("\r\n")));
  17519. }
  17520. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17521. {
  17522. auto req = "POST /test HTTP/1.1\r\n"
  17523. "Host: localhost\r\n"
  17524. "Content-Length: 5\r\n"
  17525. "Transfer-Encoding: gzip, chunked\r\n"
  17526. "Connection: close\r\n"
  17527. "\r\n"
  17528. "hello";
  17529. std::string response;
  17530. ASSERT_TRUE(send_request(1, req, &response));
  17531. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17532. response.substr(0, response.find("\r\n")));
  17533. }
  17534. }
  17535. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17536. Server svr;
  17537. svr.Post("/test", [&](const Request &, Response &res) {
  17538. res.set_content("ok", "text/plain");
  17539. });
  17540. thread t = thread([&] { svr.listen(HOST, PORT); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17548. // length cannot be determined, so the server must answer 400 and close
  17549. // rather than treat the request as bodyless and leave the body in the
  17550. // socket for the next request to pick up.
  17551. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17552. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17553. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17554. std::string response;
  17555. ASSERT_TRUE(send_request(1, req, &response));
  17556. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17557. response.substr(0, response.find("\r\n")))
  17558. << transfer_encoding;
  17559. }
  17560. // RFC 9110 5.3: the codings may also be split across several
  17561. // Transfer-Encoding lines, which combine in the order they were received.
  17562. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17563. // just like the single-line "chunked, gzip" above.
  17564. {
  17565. auto req = "POST /test HTTP/1.1\r\n"
  17566. "Host: localhost\r\n"
  17567. "Transfer-Encoding: chunked\r\n"
  17568. "Transfer-Encoding: gzip\r\n"
  17569. "\r\n"
  17570. "0\r\n\r\n";
  17571. std::string response;
  17572. ASSERT_TRUE(send_request(1, req, &response));
  17573. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17574. response.substr(0, response.find("\r\n")));
  17575. }
  17576. // A sequence ending in chunked stays valid.
  17577. auto req = "POST /test HTTP/1.1\r\n"
  17578. "Host: localhost\r\n"
  17579. "Transfer-Encoding: gzip, chunked\r\n"
  17580. "Connection: close\r\n"
  17581. "\r\n"
  17582. "0\r\n\r\n";
  17583. std::string response;
  17584. ASSERT_TRUE(send_request(1, req, &response));
  17585. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17586. // ...including when it is spread over several lines.
  17587. auto split_req = "POST /test HTTP/1.1\r\n"
  17588. "Host: localhost\r\n"
  17589. "Transfer-Encoding: gzip\r\n"
  17590. "Transfer-Encoding: chunked\r\n"
  17591. "Connection: close\r\n"
  17592. "\r\n"
  17593. "0\r\n\r\n";
  17594. std::string split_response;
  17595. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17596. EXPECT_EQ("HTTP/1.1 200 OK",
  17597. split_response.substr(0, split_response.find("\r\n")));
  17598. }
  17599. // Regression for issue #2450: a DELETE without Content-Length on a
  17600. // keep-alive connection must not let the post-response drain consume the
  17601. // next request's bytes.
  17602. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17603. Server svr;
  17604. std::atomic<int> delete_count(0);
  17605. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17606. delete_count++;
  17607. res.status = StatusCode::NoContent_204;
  17608. });
  17609. auto port = svr.bind_to_any_port(HOST);
  17610. thread t = thread([&] { svr.listen_after_bind(); });
  17611. auto se = detail::scope_exit([&] {
  17612. svr.stop();
  17613. t.join();
  17614. });
  17615. svr.wait_until_ready();
  17616. auto error = Error::Success;
  17617. auto sock = detail::create_client_socket(
  17618. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17619. /*connection_timeout_sec=*/2, 0,
  17620. /*read_timeout_sec=*/2, 0,
  17621. /*write_timeout_sec=*/2, 0, std::string(), error);
  17622. ASSERT_NE(INVALID_SOCKET, sock);
  17623. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17624. auto send_request_and_read_response = [&](const std::string &req,
  17625. std::string &out) -> bool {
  17626. auto sent = send(sock, req.data(), req.size(), 0);
  17627. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17628. char buf[4096];
  17629. for (;;) {
  17630. auto n = recv(sock, buf, sizeof(buf), 0);
  17631. if (n <= 0) { return !out.empty(); }
  17632. out.append(buf, static_cast<size_t>(n));
  17633. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17634. }
  17635. };
  17636. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17637. "Host: localhost\r\n"
  17638. "\r\n";
  17639. std::string resp1;
  17640. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17641. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17642. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17643. "Host: localhost\r\n"
  17644. "Connection: close\r\n"
  17645. "\r\n";
  17646. std::string resp2;
  17647. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17648. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17649. EXPECT_EQ(2, delete_count.load());
  17650. }
  17651. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17652. Server svr;
  17653. svr.Post("/ingest", [&](const Request &, Response &res,
  17654. const ContentReader &content_reader) {
  17655. auto consumed = content_reader([](const char *, size_t) { return false; });
  17656. EXPECT_FALSE(consumed);
  17657. res.status = StatusCode::Conflict_409;
  17658. res.set_header("Connection", "close");
  17659. });
  17660. auto port = svr.bind_to_any_port(HOST);
  17661. thread t = thread([&] { svr.listen_after_bind(); });
  17662. auto se = detail::scope_exit([&] {
  17663. svr.stop();
  17664. t.join();
  17665. });
  17666. svr.wait_until_ready();
  17667. auto error = Error::Success;
  17668. auto sock = detail::create_client_socket(
  17669. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17670. /*connection_timeout_sec=*/2, 0,
  17671. /*read_timeout_sec=*/1, 0,
  17672. /*write_timeout_sec=*/2, 0, std::string(), error);
  17673. ASSERT_NE(INVALID_SOCKET, sock);
  17674. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17675. std::string request = "POST /ingest HTTP/1.1\r\n"
  17676. "Host: localhost\r\n"
  17677. "Transfer-Encoding: chunked\r\n"
  17678. "\r\n"
  17679. "4\r\n"
  17680. "data\r\n";
  17681. auto sent = send(sock, request.data(), request.size(), 0);
  17682. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17683. std::string response;
  17684. ssize_t received = 0;
  17685. do {
  17686. char buf[4096];
  17687. received = recv(sock, buf, sizeof(buf), 0);
  17688. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17689. } while (received > 0);
  17690. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17691. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17692. EXPECT_EQ(0, received);
  17693. }
  17694. namespace no_proxy_test {
  17695. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17696. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17697. // calling listen().
  17698. class ScopedServer {
  17699. public:
  17700. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17701. ~ScopedServer() {
  17702. svr_.stop();
  17703. if (th_.joinable()) { th_.join(); }
  17704. }
  17705. Server &svr() { return svr_; }
  17706. int port() const { return port_; }
  17707. void listen() {
  17708. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17709. svr_.wait_until_ready();
  17710. }
  17711. private:
  17712. Server svr_;
  17713. std::thread th_;
  17714. int port_ = 0;
  17715. };
  17716. class ProxyAndTargetServers {
  17717. public:
  17718. ProxyAndTargetServers() {
  17719. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17720. proxy_hits_++;
  17721. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17722. res.set_content("via-proxy", "text/plain");
  17723. });
  17724. target_.Get(".*", [this](const Request &req, Response &res) {
  17725. target_hits_++;
  17726. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17727. res.set_content("direct", "text/plain");
  17728. });
  17729. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17730. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17731. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17732. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17733. proxy_mock_.wait_until_ready();
  17734. target_.wait_until_ready();
  17735. }
  17736. ~ProxyAndTargetServers() {
  17737. proxy_mock_.stop();
  17738. target_.stop();
  17739. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17740. if (target_thread_.joinable()) { target_thread_.join(); }
  17741. }
  17742. Server &proxy_mock() { return proxy_mock_; }
  17743. Server &target() { return target_; }
  17744. int proxy_port() const { return proxy_port_; }
  17745. int target_port() const { return target_port_; }
  17746. int proxy_hits() const { return proxy_hits_.load(); }
  17747. int target_hits() const { return target_hits_.load(); }
  17748. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17749. void reset_counters() {
  17750. proxy_hits_ = 0;
  17751. target_hits_ = 0;
  17752. last_had_proxy_authz_ = false;
  17753. }
  17754. private:
  17755. Server proxy_mock_;
  17756. Server target_;
  17757. std::thread proxy_thread_;
  17758. std::thread target_thread_;
  17759. int proxy_port_ = 0;
  17760. int target_port_ = 0;
  17761. std::atomic<int> proxy_hits_{0};
  17762. std::atomic<int> target_hits_{0};
  17763. std::atomic<bool> last_had_proxy_authz_{false};
  17764. };
  17765. inline std::unique_ptr<Client> make_client(const std::string &host,
  17766. ProxyAndTargetServers &s) {
  17767. auto cli = detail::make_unique<Client>(host, s.target_port());
  17768. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17769. cli->set_proxy("127.0.0.1", s.proxy_port());
  17770. return cli;
  17771. }
  17772. } // namespace no_proxy_test
  17773. using no_proxy_test::make_client;
  17774. using no_proxy_test::ProxyAndTargetServers;
  17775. TEST(NoProxyTest, ExactHostnameBypasses) {
  17776. ProxyAndTargetServers s;
  17777. auto cli = make_client("example.com", s);
  17778. cli->set_no_proxy({"example.com"});
  17779. auto res = cli->Get("/");
  17780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17781. EXPECT_EQ(0, s.proxy_hits());
  17782. EXPECT_EQ(1, s.target_hits());
  17783. }
  17784. TEST(NoProxyTest, SubdomainBypasses) {
  17785. ProxyAndTargetServers s;
  17786. auto cli = make_client("foo.example.com", s);
  17787. cli->set_no_proxy({"example.com"});
  17788. auto res = cli->Get("/");
  17789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17790. EXPECT_EQ(0, s.proxy_hits());
  17791. EXPECT_EQ(1, s.target_hits());
  17792. }
  17793. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17794. // Regression guard: "evilexample.com" must not be considered a subdomain
  17795. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17796. // check would let traffic bypass the proxy and leak credentials direct
  17797. // to the attacker host.
  17798. ProxyAndTargetServers s;
  17799. auto cli = make_client("evilexample.com", s);
  17800. cli->set_no_proxy({"example.com"});
  17801. auto res = cli->Get("/");
  17802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17803. EXPECT_GE(s.proxy_hits(), 1);
  17804. EXPECT_EQ(0, s.target_hits());
  17805. }
  17806. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17807. ProxyAndTargetServers s;
  17808. auto cli = make_client("example.com.evil.com", s);
  17809. cli->set_no_proxy({"example.com"});
  17810. auto res = cli->Get("/");
  17811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17812. EXPECT_GE(s.proxy_hits(), 1);
  17813. EXPECT_EQ(0, s.target_hits());
  17814. }
  17815. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17816. ProxyAndTargetServers s;
  17817. auto cli = make_client("example.com", s);
  17818. cli->set_no_proxy({".example.com"});
  17819. auto res = cli->Get("/");
  17820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17821. EXPECT_EQ(0, s.proxy_hits());
  17822. EXPECT_EQ(1, s.target_hits());
  17823. }
  17824. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17825. ProxyAndTargetServers s;
  17826. auto cli = make_client("Example.COM", s);
  17827. cli->set_no_proxy({"EXAMPLE.com"});
  17828. auto res = cli->Get("/");
  17829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17830. EXPECT_EQ(0, s.proxy_hits());
  17831. EXPECT_EQ(1, s.target_hits());
  17832. }
  17833. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17834. ProxyAndTargetServers s;
  17835. auto cli = make_client("example.com.", s);
  17836. cli->set_no_proxy({"example.com"});
  17837. auto res = cli->Get("/");
  17838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17839. EXPECT_EQ(0, s.proxy_hits());
  17840. EXPECT_EQ(1, s.target_hits());
  17841. }
  17842. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17843. // Trailing dots must be normalized on BOTH sides — host and entry.
  17844. // An implementation that only strips the host-side trailing dot would
  17845. // fail to match host "example.com" against entry "example.com." because
  17846. // a literal substring search would compare 11 chars against 12.
  17847. ProxyAndTargetServers s;
  17848. auto cli = make_client("example.com", s);
  17849. cli->set_no_proxy({"example.com."});
  17850. auto res = cli->Get("/");
  17851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17852. EXPECT_EQ(0, s.proxy_hits());
  17853. EXPECT_EQ(1, s.target_hits());
  17854. }
  17855. TEST(NoProxyTest, WildcardBypassesEverything) {
  17856. ProxyAndTargetServers s;
  17857. auto cli = make_client("anything.invalid.test", s);
  17858. cli->set_no_proxy({"*"});
  17859. auto res = cli->Get("/");
  17860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17861. EXPECT_EQ(0, s.proxy_hits());
  17862. EXPECT_EQ(1, s.target_hits());
  17863. }
  17864. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17865. ProxyAndTargetServers s;
  17866. Client cli("127.0.0.1", s.target_port());
  17867. cli.set_proxy("127.0.0.1", s.proxy_port());
  17868. cli.set_no_proxy({"127.0.0.1"});
  17869. auto res = cli.Get("/");
  17870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17871. EXPECT_EQ(0, s.proxy_hits());
  17872. EXPECT_EQ(1, s.target_hits());
  17873. }
  17874. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17875. ProxyAndTargetServers s;
  17876. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17877. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17878. cli.set_proxy("127.0.0.1", s.proxy_port());
  17879. cli.set_no_proxy({"::1"});
  17880. auto res = cli.Get("/");
  17881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17882. EXPECT_EQ(0, s.proxy_hits());
  17883. EXPECT_EQ(1, s.target_hits());
  17884. }
  17885. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17886. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17887. // must still be recognized as IPv6 for CIDR matching. Implementations
  17888. // that detect IPv6 only when the host begins with '[' would parse the
  17889. // host as a hostname and miss the match.
  17890. ProxyAndTargetServers s;
  17891. Client cli("fe80::1", s.target_port());
  17892. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17893. cli.set_proxy("127.0.0.1", s.proxy_port());
  17894. cli.set_no_proxy({"fe80::/10"});
  17895. auto res = cli.Get("/");
  17896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17897. EXPECT_EQ(0, s.proxy_hits());
  17898. EXPECT_EQ(1, s.target_hits());
  17899. }
  17900. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17901. ProxyAndTargetServers s;
  17902. Client cli("::1", s.target_port());
  17903. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17904. cli.set_proxy("127.0.0.1", s.proxy_port());
  17905. cli.set_no_proxy({"[::1]"});
  17906. auto res = cli.Get("/");
  17907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17908. EXPECT_EQ(0, s.proxy_hits());
  17909. EXPECT_EQ(1, s.target_hits());
  17910. }
  17911. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17912. ProxyAndTargetServers s;
  17913. Client cli("fe80::1", s.target_port());
  17914. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17915. cli.set_proxy("127.0.0.1", s.proxy_port());
  17916. cli.set_no_proxy({"[fe80::]/10"});
  17917. auto res = cli.Get("/");
  17918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17919. EXPECT_EQ(0, s.proxy_hits());
  17920. EXPECT_EQ(1, s.target_hits());
  17921. }
  17922. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17923. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17924. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17925. // tricks via address-family conversion.
  17926. ProxyAndTargetServers s;
  17927. Client cli("::ffff:127.0.0.1", s.target_port());
  17928. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17929. cli.set_proxy("127.0.0.1", s.proxy_port());
  17930. cli.set_no_proxy({"127.0.0.1"});
  17931. auto res = cli.Get("/");
  17932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17933. EXPECT_GE(s.proxy_hits(), 1);
  17934. EXPECT_EQ(0, s.target_hits());
  17935. }
  17936. TEST(NoProxyTest, IPv4CidrMatch) {
  17937. ProxyAndTargetServers s;
  17938. Client cli("127.0.0.1", s.target_port());
  17939. cli.set_proxy("127.0.0.1", s.proxy_port());
  17940. cli.set_no_proxy({"127.0.0.0/8"});
  17941. auto res = cli.Get("/");
  17942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17943. EXPECT_EQ(0, s.proxy_hits());
  17944. EXPECT_EQ(1, s.target_hits());
  17945. }
  17946. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17947. ProxyAndTargetServers s;
  17948. Client cli("127.0.0.1", s.target_port());
  17949. cli.set_proxy("127.0.0.1", s.proxy_port());
  17950. cli.set_no_proxy({"10.0.0.0/8"});
  17951. auto res = cli.Get("/");
  17952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17953. EXPECT_GE(s.proxy_hits(), 1);
  17954. EXPECT_EQ(0, s.target_hits());
  17955. }
  17956. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17957. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17958. // IPv4 target matches.
  17959. ProxyAndTargetServers s;
  17960. Client cli("127.0.0.1", s.target_port());
  17961. cli.set_proxy("127.0.0.1", s.proxy_port());
  17962. cli.set_no_proxy({"0.0.0.0/0"});
  17963. auto res = cli.Get("/");
  17964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17965. EXPECT_EQ(0, s.proxy_hits());
  17966. EXPECT_EQ(1, s.target_hits());
  17967. }
  17968. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17969. ProxyAndTargetServers s;
  17970. Client cli("127.0.0.1", s.target_port());
  17971. cli.set_proxy("127.0.0.1", s.proxy_port());
  17972. cli.set_no_proxy({"127.0.0.1"});
  17973. auto res = cli.Get("/");
  17974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17975. EXPECT_EQ(0, s.proxy_hits());
  17976. EXPECT_EQ(1, s.target_hits());
  17977. }
  17978. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17979. ProxyAndTargetServers s;
  17980. Client cli("127.0.0.1", s.target_port());
  17981. cli.set_proxy("127.0.0.1", s.proxy_port());
  17982. cli.set_no_proxy({"127.0.0.0/33"});
  17983. auto res = cli.Get("/");
  17984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17985. EXPECT_GE(s.proxy_hits(), 1);
  17986. EXPECT_EQ(0, s.target_hits());
  17987. }
  17988. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17989. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17990. ProxyAndTargetServers s;
  17991. Client cli("127.0.0.1", s.target_port());
  17992. cli.set_proxy("127.0.0.1", s.proxy_port());
  17993. cli.set_no_proxy({"127.0.0.1/"});
  17994. auto res = cli.Get("/");
  17995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17996. EXPECT_GE(s.proxy_hits(), 1);
  17997. EXPECT_EQ(0, s.target_hits());
  17998. }
  17999. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18000. ProxyAndTargetServers s;
  18001. auto cli = make_client("internal.corp", s);
  18002. cli->set_proxy_basic_auth("u", "p");
  18003. cli->set_no_proxy({"internal.corp"});
  18004. auto res = cli->Get("/");
  18005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18006. EXPECT_EQ(1, s.target_hits());
  18007. EXPECT_EQ(0, s.proxy_hits());
  18008. EXPECT_FALSE(s.last_had_proxy_authz())
  18009. << "Proxy-Authorization must not be sent direct to the target";
  18010. }
  18011. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18012. ProxyAndTargetServers s;
  18013. auto cli = make_client("public.example", s);
  18014. cli->set_proxy_basic_auth("u", "p");
  18015. cli->set_no_proxy({"internal.corp"}); // does not match
  18016. auto res = cli->Get("/");
  18017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18018. EXPECT_GE(s.proxy_hits(), 1);
  18019. EXPECT_TRUE(s.last_had_proxy_authz());
  18020. }
  18021. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18022. ProxyAndTargetServers s;
  18023. auto cli = make_client("anything.test", s);
  18024. auto res = cli->Get("/");
  18025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18026. EXPECT_GE(s.proxy_hits(), 1);
  18027. EXPECT_EQ(0, s.target_hits());
  18028. }
  18029. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18030. ProxyAndTargetServers s;
  18031. auto cli = make_client("example.com", s);
  18032. cli->set_no_proxy({"example.com:8080"});
  18033. auto res = cli->Get("/");
  18034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18035. EXPECT_GE(s.proxy_hits(), 1);
  18036. EXPECT_EQ(0, s.target_hits());
  18037. }
  18038. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18039. ProxyAndTargetServers s;
  18040. auto cli = make_client("anything.test", s);
  18041. cli->set_no_proxy({"", " ", "\t"});
  18042. auto res = cli->Get("/");
  18043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18044. EXPECT_GE(s.proxy_hits(), 1);
  18045. EXPECT_EQ(0, s.target_hits());
  18046. }
  18047. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18048. // An entry with leading/trailing whitespace must still match — env-style
  18049. // values are commonly pasted with stray spaces and an implementation
  18050. // that feeds the raw token directly to inet_pton would fail to match
  18051. // valid CIDRs because of the spaces.
  18052. ProxyAndTargetServers s;
  18053. Client cli("127.0.0.1", s.target_port());
  18054. cli.set_proxy("127.0.0.1", s.proxy_port());
  18055. cli.set_no_proxy({" 127.0.0.0/8 "});
  18056. auto res = cli.Get("/");
  18057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18058. EXPECT_EQ(0, s.proxy_hits());
  18059. EXPECT_EQ(1, s.target_hits());
  18060. }
  18061. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18062. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18063. // go direct and must NOT carry Proxy-Authorization.
  18064. std::atomic<int> proxy_hits{0};
  18065. std::atomic<int> target_hits{0};
  18066. std::atomic<bool> target_saw_authz{false};
  18067. no_proxy_test::ScopedServer proxy_mock, target;
  18068. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18069. proxy_hits++;
  18070. res.status = 302;
  18071. res.set_header("Location", "http://127.0.0.1:" +
  18072. std::to_string(target.port()) + "/landed");
  18073. });
  18074. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18075. target_hits++;
  18076. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18077. res.set_content("direct", "text/plain");
  18078. });
  18079. proxy_mock.listen();
  18080. target.listen();
  18081. Client cli("public.example", target.port());
  18082. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18083. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18084. cli.set_proxy_basic_auth("u", "p");
  18085. cli.set_no_proxy({"127.0.0.1"});
  18086. cli.set_follow_location(true);
  18087. auto res = cli.Get("/redir");
  18088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18089. EXPECT_GE(proxy_hits.load(), 1);
  18090. EXPECT_GE(target_hits.load(), 1);
  18091. EXPECT_FALSE(target_saw_authz.load());
  18092. }
  18093. #ifdef CPPHTTPLIB_SSL_ENABLED
  18094. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18095. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18096. // proxy creds would be sent to the (possibly hostile) origin.
  18097. std::atomic<int> target_hits{0};
  18098. std::atomic<bool> target_saw_proxy_authz{false};
  18099. no_proxy_test::ScopedServer target;
  18100. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18101. target_hits++;
  18102. if (req.has_header("Proxy-Authorization")) {
  18103. target_saw_proxy_authz = true;
  18104. }
  18105. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18106. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18107. "nonce=\"abc\", algorithm=MD5");
  18108. });
  18109. target.listen();
  18110. // The proxy address is set to the target's port: the bypass MUST kick in;
  18111. // if it doesn't, the test still routes "via proxy" to the same server and
  18112. // the Proxy-Authorization assertion below catches the leak.
  18113. Client cli("evil.example", target.port());
  18114. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18115. cli.set_proxy("127.0.0.1", target.port());
  18116. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18117. cli.set_no_proxy({"evil.example"});
  18118. auto res = cli.Get("/x");
  18119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18120. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18121. EXPECT_EQ(1, target_hits.load());
  18122. EXPECT_FALSE(target_saw_proxy_authz.load());
  18123. }
  18124. #endif
  18125. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18126. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18127. std::atomic<int> proxy_hits{0};
  18128. std::atomic<int> bypass_hits{0};
  18129. std::atomic<bool> proxy_saw_c_url{false};
  18130. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18131. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18132. proxy_hits++;
  18133. if (req.path.find("/start") != std::string::npos) {
  18134. res.status = 302;
  18135. res.set_header("Location", "http://127.0.0.1:" +
  18136. std::to_string(bypass_server.port()) +
  18137. "/middle");
  18138. return;
  18139. }
  18140. if (req.path.find("/end") != std::string::npos) {
  18141. proxy_saw_c_url = true;
  18142. res.set_content("c-via-proxy", "text/plain");
  18143. return;
  18144. }
  18145. res.set_content("unexpected", "text/plain");
  18146. });
  18147. // public.example's "advertised" port is arbitrary (the request never lands
  18148. // there — it goes through the proxy), but use a dynamic value to stay
  18149. // friendly with sharded parallel runs.
  18150. int public_port = bypass_server.port();
  18151. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18152. bypass_hits++;
  18153. res.status = 302;
  18154. res.set_header("Location", "http://public.example:" +
  18155. std::to_string(public_port) + "/end");
  18156. });
  18157. proxy_mock.listen();
  18158. bypass_server.listen();
  18159. Client cli("public.example", public_port);
  18160. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18161. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18162. cli.set_no_proxy({"127.0.0.1"});
  18163. cli.set_follow_location(true);
  18164. auto res = cli.Get("/start");
  18165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18166. EXPECT_EQ(StatusCode::OK_200, res->status);
  18167. EXPECT_EQ("c-via-proxy", res->body);
  18168. EXPECT_GE(proxy_hits.load(), 2);
  18169. EXPECT_GE(bypass_hits.load(), 1);
  18170. EXPECT_TRUE(proxy_saw_c_url.load());
  18171. }
  18172. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18173. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18174. // request reconnects to the correct endpoint.
  18175. std::atomic<int> proxy_hits{0};
  18176. std::atomic<int> target_hits{0};
  18177. no_proxy_test::ScopedServer proxy_mock, target;
  18178. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18179. proxy_hits++;
  18180. res.set_content("via-proxy", "text/plain");
  18181. });
  18182. target.svr().Get(".*", [&](const Request &, Response &res) {
  18183. target_hits++;
  18184. res.set_content("direct", "text/plain");
  18185. });
  18186. proxy_mock.listen();
  18187. target.listen();
  18188. Client cli("public.example", target.port());
  18189. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18190. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18191. cli.set_keep_alive(true);
  18192. auto res1 = cli.Get("/a");
  18193. ASSERT_TRUE(res1);
  18194. EXPECT_EQ("via-proxy", res1->body);
  18195. EXPECT_EQ(1, proxy_hits.load());
  18196. EXPECT_EQ(0, target_hits.load());
  18197. cli.set_no_proxy({"public.example"});
  18198. auto res2 = cli.Get("/b");
  18199. ASSERT_TRUE(res2);
  18200. EXPECT_EQ("direct", res2->body);
  18201. EXPECT_EQ(1, proxy_hits.load());
  18202. EXPECT_EQ(1, target_hits.load());
  18203. }
  18204. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18205. namespace proxy_tunnel_test {
  18206. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18207. class ScopedSSLServer {
  18208. public:
  18209. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18210. port_ = svr_.bind_to_any_port("127.0.0.1");
  18211. }
  18212. ~ScopedSSLServer() {
  18213. svr_.stop();
  18214. if (th_.joinable()) { th_.join(); }
  18215. }
  18216. SSLServer &svr() { return svr_; }
  18217. int port() const { return port_; }
  18218. void listen() {
  18219. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18220. svr_.wait_until_ready();
  18221. }
  18222. private:
  18223. SSLServer svr_;
  18224. std::thread th_;
  18225. int port_ = 0;
  18226. };
  18227. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18228. class ScopedConnectProxy {
  18229. public:
  18230. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18231. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18232. if (listen_fd_ < 0) { return; }
  18233. int yes = 1;
  18234. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18235. sockaddr_in a{};
  18236. a.sin_family = AF_INET;
  18237. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18238. a.sin_port = 0;
  18239. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18240. return;
  18241. }
  18242. socklen_t alen = sizeof(a);
  18243. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18244. 0) {
  18245. return;
  18246. }
  18247. port_ = ntohs(a.sin_port);
  18248. if (::listen(listen_fd_, 1) != 0) { return; }
  18249. th_ = std::thread([this] { run(); });
  18250. }
  18251. ~ScopedConnectProxy() {
  18252. stop_ = true;
  18253. if (listen_fd_ >= 0) {
  18254. ::shutdown(listen_fd_, SHUT_RDWR);
  18255. ::close(listen_fd_);
  18256. }
  18257. if (th_.joinable()) { th_.join(); }
  18258. }
  18259. int port() const { return port_; }
  18260. int connect_hits() const { return connect_hits_.load(); }
  18261. private:
  18262. void run() {
  18263. while (!stop_.load()) {
  18264. fd_set rfds;
  18265. FD_ZERO(&rfds);
  18266. FD_SET(listen_fd_, &rfds);
  18267. timeval tv{0, 100 * 1000};
  18268. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18269. if (sel <= 0) { continue; }
  18270. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18271. if (client_fd < 0) { continue; }
  18272. std::string req;
  18273. char buf[2048];
  18274. while (req.find("\r\n\r\n") == std::string::npos) {
  18275. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18276. if (n <= 0) { break; }
  18277. req.append(buf, static_cast<size_t>(n));
  18278. }
  18279. if (req.compare(0, 7, "CONNECT") != 0) {
  18280. ::close(client_fd);
  18281. continue;
  18282. }
  18283. connect_hits_++;
  18284. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18285. ::send(client_fd, ok, std::strlen(ok), 0);
  18286. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18287. sockaddr_in o{};
  18288. o.sin_family = AF_INET;
  18289. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18290. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18291. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18292. 0) {
  18293. ::close(client_fd);
  18294. ::close(origin_fd);
  18295. continue;
  18296. }
  18297. auto forward = [](int from, int to) {
  18298. char b[8192];
  18299. for (;;) {
  18300. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18301. if (n <= 0) { break; }
  18302. ssize_t off = 0;
  18303. while (off < n) {
  18304. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18305. if (s <= 0) {
  18306. off = n;
  18307. break;
  18308. }
  18309. off += s;
  18310. }
  18311. }
  18312. ::shutdown(to, SHUT_WR);
  18313. };
  18314. std::thread t1([&] { forward(client_fd, origin_fd); });
  18315. std::thread t2([&] { forward(origin_fd, client_fd); });
  18316. t1.join();
  18317. t2.join();
  18318. ::close(client_fd);
  18319. ::close(origin_fd);
  18320. }
  18321. }
  18322. int forward_port_ = -1;
  18323. int listen_fd_ = -1;
  18324. int port_ = 0;
  18325. std::thread th_;
  18326. std::atomic<bool> stop_{false};
  18327. std::atomic<int> connect_hits_{0};
  18328. };
  18329. } // namespace proxy_tunnel_test
  18330. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18331. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18332. // retry; otherwise proxy creds would be sent to the origin.
  18333. std::atomic<int> origin_hits{0};
  18334. std::atomic<bool> origin_saw_proxy_authz{false};
  18335. proxy_tunnel_test::ScopedSSLServer origin;
  18336. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18337. origin_hits++;
  18338. if (req.has_header("Proxy-Authorization")) {
  18339. origin_saw_proxy_authz = true;
  18340. }
  18341. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18342. res.set_header("Proxy-Authenticate",
  18343. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18344. "algorithm=MD5");
  18345. });
  18346. origin.listen();
  18347. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18348. ASSERT_NE(0, proxy.port());
  18349. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18350. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18351. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18352. // and answer with its own status, making this test flaky.
  18353. SSLClient cli("127.0.0.1", origin.port());
  18354. cli.enable_server_certificate_verification(false);
  18355. cli.set_proxy("127.0.0.1", proxy.port());
  18356. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18357. auto res = cli.Get("/x");
  18358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18359. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18360. EXPECT_EQ(1, origin_hits.load());
  18361. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18362. EXPECT_EQ(1, proxy.connect_hits());
  18363. }
  18364. #endif