1
0

test.cc 704 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  595. string original = "Piri Tommy Villiers - on & on";
  596. string encoded = httplib::encode_uri_component(original);
  597. string decoded = httplib::decode_uri_component(encoded);
  598. EXPECT_EQ(decoded, original);
  599. }
  600. TEST(TrimTests, TrimStringTests) {
  601. EXPECT_EQ("abc", detail::trim_copy("abc"));
  602. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  603. EXPECT_TRUE(detail::trim_copy("").empty());
  604. }
  605. TEST(AsciiTest, LocaleIndependentClassification) {
  606. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  607. // which consult the global C locale: std::isalnum(0xC5) can return true
  608. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  609. // helpers must classify every byte by the ASCII grammar alone.
  610. for (int i = 0; i < 256; i++) {
  611. auto c = static_cast<char>(i);
  612. auto is_digit = i >= '0' && i <= '9';
  613. auto is_upper = i >= 'A' && i <= 'Z';
  614. auto is_lower = i >= 'a' && i <= 'z';
  615. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  616. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  617. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  618. << "byte " << i;
  619. }
  620. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  621. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  622. // Non-ASCII bytes must be percent-encoded, never passed through as
  623. // alphanumeric.
  624. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  625. }
  626. TEST(FromCharsTest, Double) {
  627. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  628. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  629. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  630. auto parse = [](const std::string &s, double &v) {
  631. return detail::from_chars(s.data(), s.data() + s.size(), v);
  632. };
  633. double v = -1.0;
  634. // Representative quality values.
  635. EXPECT_EQ(parse("0", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.0);
  637. EXPECT_EQ(parse("1", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.8);
  641. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.001);
  643. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  644. EXPECT_DOUBLE_EQ(v, 1.0);
  645. // A missing integer or fractional part is tolerated.
  646. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  647. EXPECT_DOUBLE_EQ(v, 0.5);
  648. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 5.0);
  650. // Values outside [0, 1] still parse; the caller range-checks them.
  651. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  652. EXPECT_DOUBLE_EQ(v, 123.456);
  653. // Stops at the first byte that is not part of the number and reports where.
  654. std::string trailing = "0.9, text/html";
  655. auto r = parse(trailing, v);
  656. EXPECT_EQ(r.ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.9);
  658. EXPECT_EQ(*r.ptr, ',');
  659. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  660. // outright, and an 'e'/'E' simply ends the number.
  661. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  662. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  663. std::string exp_input = "1.5e3";
  664. r = parse(exp_input, v);
  665. EXPECT_EQ(r.ec, std::errc{});
  666. EXPECT_DOUBLE_EQ(v, 1.5);
  667. EXPECT_EQ(*r.ptr, 'e');
  668. // Invalid inputs.
  669. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  670. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  671. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  672. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  673. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  674. // Pathological but well-formed inputs must stay bounded (no overflow, no
  675. // out-of-bounds table access) and stay within [0, 1] for the caller.
  676. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  677. std::errc{});
  678. EXPECT_DOUBLE_EQ(v, 0.0);
  679. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  680. std::errc{});
  681. EXPECT_GE(v, 0.0);
  682. EXPECT_LE(v, 1.0);
  683. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  684. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  685. }
  686. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  687. // Simple case without quality values
  688. std::vector<std::string> result1;
  689. EXPECT_TRUE(detail::parse_accept_header(
  690. "text/html,application/json,text/plain", result1));
  691. EXPECT_EQ(result1.size(), 3U);
  692. EXPECT_EQ(result1[0], "text/html");
  693. EXPECT_EQ(result1[1], "application/json");
  694. EXPECT_EQ(result1[2], "text/plain");
  695. // With quality values
  696. std::vector<std::string> result2;
  697. EXPECT_TRUE(detail::parse_accept_header(
  698. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  699. EXPECT_EQ(result2.size(), 3U);
  700. EXPECT_EQ(result2[0], "application/json"); // highest q value
  701. EXPECT_EQ(result2[1], "text/html");
  702. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  703. }
  704. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  705. // Mixed with and without quality values
  706. std::vector<std::string> result;
  707. EXPECT_TRUE(detail::parse_accept_header(
  708. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  709. EXPECT_EQ(result.size(), 3U);
  710. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  711. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  712. EXPECT_EQ(result[2], "application/json"); // q=0.5
  713. }
  714. TEST(ParseAcceptHeaderTest, EdgeCases) {
  715. // Empty header
  716. std::vector<std::string> empty_result;
  717. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  718. EXPECT_TRUE(empty_result.empty());
  719. // Single type
  720. std::vector<std::string> single_result;
  721. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  722. EXPECT_EQ(single_result.size(), 1U);
  723. EXPECT_EQ(single_result[0], "application/json");
  724. // Wildcard types
  725. std::vector<std::string> wildcard_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  728. EXPECT_EQ(wildcard_result.size(), 3U);
  729. EXPECT_EQ(wildcard_result[0], "application/json");
  730. EXPECT_EQ(wildcard_result[1], "text/*");
  731. EXPECT_EQ(wildcard_result[2], "*/*");
  732. }
  733. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  734. // Common browser Accept header
  735. std::vector<std::string> browser_result;
  736. EXPECT_TRUE(
  737. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  738. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  739. browser_result));
  740. EXPECT_EQ(browser_result.size(), 6U);
  741. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  742. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  743. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  744. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  745. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  746. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  747. // API client header
  748. std::vector<std::string> api_result;
  749. EXPECT_TRUE(detail::parse_accept_header(
  750. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  751. api_result));
  752. EXPECT_EQ(api_result.size(), 3U);
  753. EXPECT_EQ(api_result[0], "application/json");
  754. EXPECT_EQ(api_result[1], "application/xml");
  755. EXPECT_EQ(api_result[2], "text/plain");
  756. }
  757. TEST(ParseAcceptHeaderTest, SpecialCases) {
  758. // Quality value with 3 decimal places
  759. std::vector<std::string> decimal_result;
  760. EXPECT_TRUE(detail::parse_accept_header(
  761. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  762. EXPECT_EQ(decimal_result.size(), 2U);
  763. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  764. EXPECT_EQ(decimal_result[1], "text/html");
  765. // Zero quality (should still be included but with lowest priority)
  766. std::vector<std::string> zero_q_result;
  767. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  768. zero_q_result));
  769. EXPECT_EQ(zero_q_result.size(), 2U);
  770. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  771. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  772. // No spaces around commas
  773. std::vector<std::string> no_space_result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  776. no_space_result));
  777. EXPECT_EQ(no_space_result.size(), 3U);
  778. EXPECT_EQ(no_space_result[0], "text/html");
  779. EXPECT_EQ(no_space_result[1], "application/json");
  780. EXPECT_EQ(no_space_result[2], "text/plain");
  781. }
  782. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  783. // Quality values always use '.' as the decimal separator, so parsing must
  784. // not depend on the process locale. An embedding application may have
  785. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  786. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  787. std::string saved = cur ? cur : "C";
  788. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  789. "fr_FR.UTF-8"};
  790. bool switched = false;
  791. for (const auto loc : comma_locales) {
  792. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  793. std::localeconv()->decimal_point[0] == ',') {
  794. switched = true;
  795. break;
  796. }
  797. }
  798. if (!switched) {
  799. std::setlocale(LC_NUMERIC, saved.c_str());
  800. GTEST_SKIP() << "no comma-decimal locale available on this host";
  801. }
  802. // The higher-weighted type appears later in the list, so a correct parse
  803. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  804. // sensitive parse reads both weights as 0 and leaves the original order.
  805. std::vector<std::string> result;
  806. EXPECT_TRUE(detail::parse_accept_header(
  807. "application/json;q=0.1,text/html;q=0.9", result));
  808. ASSERT_EQ(result.size(), 2U);
  809. EXPECT_EQ(result[0], "text/html");
  810. EXPECT_EQ(result[1], "application/json");
  811. std::setlocale(LC_NUMERIC, saved.c_str());
  812. }
  813. TEST(ParseAcceptHeaderTest, InvalidCases) {
  814. std::vector<std::string> result;
  815. // Invalid quality value (> 1.0)
  816. EXPECT_FALSE(
  817. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  818. // Invalid quality value (< 0.0)
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  821. // Invalid quality value (not a number)
  822. EXPECT_FALSE(detail::parse_accept_header(
  823. "text/html;q=invalid,application/json", result));
  824. // Empty quality value
  825. EXPECT_FALSE(
  826. detail::parse_accept_header("text/html;q=,application/json", result));
  827. // Invalid media type format (no slash and not wildcard)
  828. EXPECT_FALSE(
  829. detail::parse_accept_header("invalidtype,application/json", result));
  830. // Empty media type
  831. result.clear();
  832. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  833. // Only commas
  834. result.clear();
  835. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  836. // Valid cases should still work
  837. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "*/*");
  840. EXPECT_TRUE(detail::parse_accept_header("*", result));
  841. EXPECT_EQ(result.size(), 1U);
  842. EXPECT_EQ(result[0], "*");
  843. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  844. EXPECT_EQ(result.size(), 1U);
  845. EXPECT_EQ(result[0], "text/*");
  846. }
  847. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  848. Server svr;
  849. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  850. EXPECT_EQ(req.accept_content_types.size(), 3U);
  851. EXPECT_EQ(req.accept_content_types[0], "application/json");
  852. EXPECT_EQ(req.accept_content_types[1], "text/html");
  853. EXPECT_EQ(req.accept_content_types[2], "*/*");
  854. res.set_content("ok", "text/plain");
  855. });
  856. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  857. EXPECT_TRUE(false);
  858. res.set_content("bad request", "text/plain");
  859. });
  860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  861. auto se = detail::scope_exit([&] {
  862. svr.stop();
  863. listen_thread.join();
  864. ASSERT_FALSE(svr.is_running());
  865. });
  866. svr.wait_until_ready();
  867. Client cli("localhost", PORT);
  868. {
  869. auto res = cli.Get(
  870. "/accept_ok",
  871. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::OK_200, res->status);
  874. }
  875. {
  876. auto res = cli.Get("/accept_bad_request",
  877. Headers{{"Accept", "text/html;q=abc,application/json"}});
  878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  880. }
  881. }
  882. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  883. Server svr;
  884. svr.Get("/", [](const Request & /*req*/, Response &res) {
  885. res.set_content("ok", "text/plain");
  886. });
  887. std::atomic<int> start_count{0};
  888. std::atomic<bool> running_when_called{false};
  889. svr.set_start_handler([&]() {
  890. running_when_called = svr.is_running();
  891. start_count++;
  892. });
  893. auto port = svr.bind_to_any_port(HOST);
  894. std::thread t([&]() { svr.listen_after_bind(); });
  895. auto se = detail::scope_exit([&] {
  896. svr.stop();
  897. t.join();
  898. ASSERT_FALSE(svr.is_running());
  899. });
  900. svr.wait_until_ready();
  901. // A successful request proves the accept loop is running, which the start
  902. // handler precedes; so by now the handler must have run exactly once.
  903. Client cli(HOST, port);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res = cli.Get("/");
  906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  907. EXPECT_EQ(StatusCode::OK_200, res->status);
  908. EXPECT_EQ(1, start_count.load());
  909. EXPECT_TRUE(running_when_called.load());
  910. }
  911. TEST(DivideTest, DivideStringTests) {
  912. auto divide = [](const std::string &str, char d) {
  913. std::string lhs;
  914. std::string rhs;
  915. detail::divide(str, d,
  916. [&](const char *lhs_data, std::size_t lhs_size,
  917. const char *rhs_data, std::size_t rhs_size) {
  918. lhs.assign(lhs_data, lhs_size);
  919. rhs.assign(rhs_data, rhs_size);
  920. });
  921. return std::make_pair(std::move(lhs), std::move(rhs));
  922. };
  923. {
  924. const auto res = divide("", '=');
  925. EXPECT_EQ(res.first, "");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("=", '=');
  930. EXPECT_EQ(res.first, "");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide(" ", '=');
  935. EXPECT_EQ(res.first, " ");
  936. EXPECT_EQ(res.second, "");
  937. }
  938. {
  939. const auto res = divide("a", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("a=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide("=b", '=');
  950. EXPECT_EQ(res.first, "");
  951. EXPECT_EQ(res.second, "b");
  952. }
  953. {
  954. const auto res = divide("a=b", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "b");
  957. }
  958. {
  959. const auto res = divide("a=b=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "b=");
  962. }
  963. {
  964. const auto res = divide("a=b=c", '=');
  965. EXPECT_EQ(res.first, "a");
  966. EXPECT_EQ(res.second, "b=c");
  967. }
  968. }
  969. TEST(SplitTest, ParseQueryString) {
  970. string s = "key1=val1&key2=val2&key3=val3";
  971. Params dic;
  972. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  973. [&](const char *b, const char *e) {
  974. string key, val;
  975. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  976. if (key.empty()) {
  977. key.assign(b2, e2);
  978. } else {
  979. val.assign(b2, e2);
  980. }
  981. });
  982. dic.emplace(key, val);
  983. });
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. TEST(SplitTest, ParseInvalidQueryTests) {
  989. {
  990. string s = " ";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. {
  996. string s = " = =";
  997. Params dict;
  998. detail::parse_query_text(s, dict);
  999. EXPECT_TRUE(dict.empty());
  1000. }
  1001. }
  1002. TEST(ParseQueryTest, ParseQueryString) {
  1003. {
  1004. std::string s = "key1=val1&key2=val2&key3=val3";
  1005. Params dic;
  1006. detail::parse_query_text(s, dic);
  1007. EXPECT_EQ("val1", dic.find("key1")->second);
  1008. EXPECT_EQ("val2", dic.find("key2")->second);
  1009. EXPECT_EQ("val3", dic.find("key3")->second);
  1010. }
  1011. {
  1012. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1013. Params dic;
  1014. detail::parse_query_text(s, dic);
  1015. EXPECT_EQ("", dic.find("key1")->second);
  1016. EXPECT_EQ("val1", dic.find("key2")->second);
  1017. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1018. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1019. }
  1020. }
  1021. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1022. Params dic;
  1023. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1024. dic.emplace("key1", "val1");
  1025. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1026. dic.emplace("key2", "val2");
  1027. dic.emplace("key3", "val3");
  1028. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1029. }
  1030. // Joins every entry of a Headers or Params into "key=value " so a whole
  1031. // traversal can be compared in one assertion. Both are instantiations of the
  1032. // same insertion-ordered container, so one helper serves both.
  1033. template <typename Map> static std::string entries_to_string(const Map &m) {
  1034. std::string s;
  1035. for (const auto &entry : m) {
  1036. s += entry.first + "=" + entry.second + " ";
  1037. }
  1038. return s;
  1039. }
  1040. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1041. // Params used to be a std::multimap, which sorted by name and handed the
  1042. // caller's query back alphabetised. A client signing its query string could
  1043. // not reproduce the order it asked for.
  1044. Params dic;
  1045. dic.emplace("zulu", "1");
  1046. dic.emplace("alpha", "2");
  1047. dic.emplace("mike", "3");
  1048. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1049. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1050. }
  1051. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1052. Params dic;
  1053. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1054. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1055. }
  1056. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1057. Request req;
  1058. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1059. req.params);
  1060. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1061. EXPECT_EQ("first", req.get_param_value("tag"));
  1062. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1063. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1064. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1065. EXPECT_EQ("", req.get_param_value("tag", 3));
  1066. }
  1067. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1068. // Params shares its container with Headers, which matches field names
  1069. // case-insensitively. Parameter names must not pick that up.
  1070. Params dic;
  1071. dic.emplace("Key", "upper");
  1072. dic.emplace("key", "lower");
  1073. EXPECT_EQ(2U, dic.size());
  1074. EXPECT_EQ(1U, dic.count("Key"));
  1075. EXPECT_EQ(1U, dic.count("key"));
  1076. EXPECT_EQ("upper", dic.find("Key")->second);
  1077. EXPECT_EQ("lower", dic.find("key")->second);
  1078. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1079. }
  1080. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1081. Server svr;
  1082. std::string order;
  1083. svr.Get("/order", [&](const Request &req, Response &res) {
  1084. order = entries_to_string(req.params);
  1085. res.set_content("ok", "text/plain");
  1086. });
  1087. thread t = thread([&] { svr.listen(HOST, PORT); });
  1088. auto se = detail::scope_exit([&] {
  1089. svr.stop();
  1090. t.join();
  1091. ASSERT_FALSE(svr.is_running());
  1092. });
  1093. svr.wait_until_ready();
  1094. Client cli(HOST, PORT);
  1095. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1096. ASSERT_TRUE(res);
  1097. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1098. }
  1099. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1100. Server svr;
  1101. std::string field_order, file_order;
  1102. svr.Post("/order", [&](const Request &req, Response &res) {
  1103. for (const auto &field : req.form.fields) {
  1104. field_order += field.first + "=" + field.second.content + " ";
  1105. }
  1106. for (const auto &file : req.form.files) {
  1107. file_order += file.first + "=" + file.second.filename + " ";
  1108. }
  1109. res.set_content("ok", "text/plain");
  1110. });
  1111. thread t = thread([&] { svr.listen(HOST, PORT); });
  1112. auto se = detail::scope_exit([&] {
  1113. svr.stop();
  1114. t.join();
  1115. ASSERT_FALSE(svr.is_running());
  1116. });
  1117. svr.wait_until_ready();
  1118. UploadFormDataItems items = {
  1119. {"zulu", "1", "", ""},
  1120. {"alpha", "2", "", ""},
  1121. {"mike", "3", "", ""},
  1122. {"zebra", "z", "z.txt", "text/plain"},
  1123. {"apple", "a", "a.txt", "text/plain"},
  1124. };
  1125. Client cli(HOST, PORT);
  1126. auto res = cli.Post("/order", items);
  1127. ASSERT_TRUE(res);
  1128. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1129. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1130. }
  1131. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1132. Server svr;
  1133. std::vector<std::string> values;
  1134. std::string first, second, out_of_range, order;
  1135. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1136. values = req.form.get_fields("tag");
  1137. first = req.form.get_field("tag", 0);
  1138. second = req.form.get_field("tag", 1);
  1139. out_of_range = req.form.get_field("tag", 2);
  1140. for (const auto &field : req.form.fields) {
  1141. order += field.first + "=" + field.second.content + " ";
  1142. }
  1143. res.set_content("ok", "text/plain");
  1144. });
  1145. thread t = thread([&] { svr.listen(HOST, PORT); });
  1146. auto se = detail::scope_exit([&] {
  1147. svr.stop();
  1148. t.join();
  1149. ASSERT_FALSE(svr.is_running());
  1150. });
  1151. svr.wait_until_ready();
  1152. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1153. // not adjacent in the container.
  1154. UploadFormDataItems items = {
  1155. {"tag", "first", "", ""},
  1156. {"other", "x", "", ""},
  1157. {"tag", "second", "", ""},
  1158. };
  1159. Client cli(HOST, PORT);
  1160. auto res = cli.Post("/repeated", items);
  1161. ASSERT_TRUE(res);
  1162. ASSERT_EQ(2U, values.size());
  1163. EXPECT_EQ("first", values[0]);
  1164. EXPECT_EQ("second", values[1]);
  1165. EXPECT_EQ("first", first);
  1166. EXPECT_EQ("second", second);
  1167. // std::multimap already kept entries sharing a name in insertion order, so
  1168. // everything above passes without this change too. The whole traversal is
  1169. // what tells the two apart: sorting by name would hoist "other" to the front
  1170. // and the two "tag" parts would end up adjacent.
  1171. EXPECT_EQ("tag=first other=x tag=second ", order);
  1172. // Advancing past the last entry of a name used to run off the container;
  1173. // the container's saturating increment makes it return the default instead.
  1174. EXPECT_EQ("", out_of_range);
  1175. }
  1176. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1177. // Server::read_content() keeps a FormFields::iterator alive across the
  1178. // content callbacks that fill the part it points at. The container is
  1179. // vector-backed, so a later emplace can reallocate and invalidate an older
  1180. // iterator; 64 parts grow the vector through seven reallocations, which
  1181. // checks that every part's content still lands in its own entry.
  1182. const size_t part_count = 64;
  1183. // One formula for both the parts sent and the values expected back, so the
  1184. // two cannot drift apart.
  1185. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1186. auto content_of = [](size_t i) {
  1187. return std::string(64, static_cast<char>('a' + (i % 26)));
  1188. };
  1189. Server svr;
  1190. std::vector<std::pair<std::string, std::string>> received;
  1191. svr.Post("/many", [&](const Request &req, Response &res) {
  1192. for (const auto &field : req.form.fields) {
  1193. received.emplace_back(field.first, field.second.content);
  1194. }
  1195. res.set_content("ok", "text/plain");
  1196. });
  1197. thread t = thread([&] { svr.listen(HOST, PORT); });
  1198. auto se = detail::scope_exit([&] {
  1199. svr.stop();
  1200. t.join();
  1201. ASSERT_FALSE(svr.is_running());
  1202. });
  1203. svr.wait_until_ready();
  1204. UploadFormDataItems items;
  1205. for (size_t i = 0; i < part_count; i++) {
  1206. items.push_back({name_of(i), content_of(i), "", ""});
  1207. }
  1208. Client cli(HOST, PORT);
  1209. auto res = cli.Post("/many", items);
  1210. ASSERT_TRUE(res);
  1211. ASSERT_EQ(part_count, received.size());
  1212. for (size_t i = 0; i < part_count; i++) {
  1213. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1214. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1215. }
  1216. }
  1217. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1218. string content_type = "multipart/form-data; boundary=something";
  1219. string boundary;
  1220. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1221. EXPECT_TRUE(ret);
  1222. EXPECT_EQ(boundary, "something");
  1223. }
  1224. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1225. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1226. string boundary;
  1227. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1228. EXPECT_TRUE(ret);
  1229. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1230. }
  1231. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1232. string content_type =
  1233. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1234. string boundary;
  1235. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1236. EXPECT_TRUE(ret);
  1237. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1238. }
  1239. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1240. string content_type =
  1241. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1242. string boundary;
  1243. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1244. EXPECT_TRUE(ret);
  1245. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1246. }
  1247. TEST(GetHeaderValueTest, DefaultValue) {
  1248. Headers headers = {{"Dummy", "Dummy"}};
  1249. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1250. EXPECT_STREQ("text/plain", val);
  1251. }
  1252. TEST(GetHeaderValueTest, DefaultValueInt) {
  1253. Headers headers = {{"Dummy", "Dummy"}};
  1254. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1255. EXPECT_EQ(100ull, val);
  1256. }
  1257. TEST(GetHeaderValueTest, RegularValue) {
  1258. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1259. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1260. EXPECT_STREQ("text/html", val);
  1261. }
  1262. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1263. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1264. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1265. EXPECT_STREQ("text/html", val);
  1266. }
  1267. TEST(GetHeaderValueTest, SetContent) {
  1268. Response res;
  1269. res.set_content("html", "text/html");
  1270. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1271. res.set_content("text", "text/plain");
  1272. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1273. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1274. }
  1275. TEST(GetHeaderValueTest, RegularValueInt) {
  1276. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1277. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1278. EXPECT_EQ(100ull, val);
  1279. }
  1280. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1281. Headers headers = {{"Content-Length", "x"}};
  1282. auto is_invalid_value = false;
  1283. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1284. is_invalid_value);
  1285. EXPECT_EQ(0ull, val);
  1286. EXPECT_TRUE(is_invalid_value);
  1287. }
  1288. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1289. // An all-digit value that overflows size_t must be reported as invalid, not
  1290. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1291. // a large length to a small one on 32-bit builds, leaving the framing length
  1292. // wrong while is_invalid_value stayed false.
  1293. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1294. auto is_invalid_value = false;
  1295. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1296. is_invalid_value);
  1297. EXPECT_TRUE(is_invalid_value);
  1298. // A well-formed length is unaffected.
  1299. Headers ok = {{"Content-Length", "1234"}};
  1300. is_invalid_value = false;
  1301. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1302. is_invalid_value);
  1303. EXPECT_EQ(1234ull, val);
  1304. EXPECT_FALSE(is_invalid_value);
  1305. }
  1306. TEST(GetHeaderValueTest, Range) {
  1307. {
  1308. Headers headers = {make_range_header({{1, -1}})};
  1309. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1310. EXPECT_STREQ("bytes=1-", val);
  1311. }
  1312. {
  1313. Headers headers = {make_range_header({{-1, 1}})};
  1314. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1315. EXPECT_STREQ("bytes=-1", val);
  1316. }
  1317. {
  1318. Headers headers = {make_range_header({{1, 10}})};
  1319. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1320. EXPECT_STREQ("bytes=1-10", val);
  1321. }
  1322. {
  1323. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1324. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1325. EXPECT_STREQ("bytes=1-10, 100-", val);
  1326. }
  1327. {
  1328. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1329. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1330. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1331. }
  1332. {
  1333. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1334. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1335. EXPECT_STREQ("bytes=0-0, -1", val);
  1336. }
  1337. }
  1338. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1339. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1340. // to depend on the standard library (libstdc++ handed back duplicates in
  1341. // reverse insertion order, libc++ in insertion order).
  1342. Request req;
  1343. req.set_header("Accept-Encoding", "gzip");
  1344. req.set_header("Accept-Encoding", "deflate");
  1345. req.set_header("Accept-Encoding", "br");
  1346. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1347. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1348. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1349. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1350. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1351. }
  1352. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1353. Request req;
  1354. req.set_header("X-Test", "only");
  1355. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1356. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1357. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1358. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1359. }
  1360. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1361. Headers headers;
  1362. headers.emplace("Host", "example.com");
  1363. headers.emplace("Accept-Encoding", "gzip");
  1364. headers.emplace("User-Agent", "test");
  1365. headers.emplace("Accept-Encoding", "deflate");
  1366. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1367. "Accept-Encoding=deflate ",
  1368. entries_to_string(headers));
  1369. }
  1370. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1371. Headers headers = {{"Content-Type", "text/html"},
  1372. {"CONTENT-TYPE", "text/xml"}};
  1373. EXPECT_EQ(2U, headers.count("content-type"));
  1374. auto it = headers.find("content-type");
  1375. ASSERT_TRUE(it != headers.end());
  1376. EXPECT_EQ("text/html", it->second);
  1377. }
  1378. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1379. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1380. // drop only those fields and leave everything positioned between them.
  1381. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1382. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1383. auto rng = headers.equal_range("a");
  1384. headers.erase(rng.first, rng.second);
  1385. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1386. }
  1387. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1388. Headers headers = {
  1389. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1390. EXPECT_EQ(3U, headers.erase("A"));
  1391. EXPECT_EQ(0U, headers.count("A"));
  1392. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1393. }
  1394. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1395. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1396. headers.emplace_front("Host", "example.com");
  1397. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1398. entries_to_string(headers));
  1399. }
  1400. TEST(ParseHeaderValueTest, Range) {
  1401. {
  1402. Ranges ranges;
  1403. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1404. EXPECT_TRUE(ret);
  1405. EXPECT_EQ(1u, ranges.size());
  1406. EXPECT_EQ(1u, ranges[0].first);
  1407. EXPECT_EQ(-1, ranges[0].second);
  1408. }
  1409. {
  1410. Ranges ranges;
  1411. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1412. EXPECT_TRUE(ret);
  1413. EXPECT_EQ(1u, ranges.size());
  1414. EXPECT_EQ(-1, ranges[0].first);
  1415. EXPECT_EQ(1u, ranges[0].second);
  1416. }
  1417. {
  1418. Ranges ranges;
  1419. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1420. EXPECT_TRUE(ret);
  1421. EXPECT_EQ(1u, ranges.size());
  1422. EXPECT_EQ(1u, ranges[0].first);
  1423. EXPECT_EQ(10u, ranges[0].second);
  1424. }
  1425. {
  1426. Ranges ranges;
  1427. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1428. EXPECT_FALSE(ret);
  1429. }
  1430. {
  1431. Ranges ranges;
  1432. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1433. EXPECT_TRUE(ret);
  1434. EXPECT_EQ(2u, ranges.size());
  1435. EXPECT_EQ(1u, ranges[0].first);
  1436. EXPECT_EQ(10u, ranges[0].second);
  1437. EXPECT_EQ(100u, ranges[1].first);
  1438. EXPECT_EQ(-1, ranges[1].second);
  1439. }
  1440. {
  1441. Ranges ranges;
  1442. auto ret =
  1443. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1444. EXPECT_TRUE(ret);
  1445. EXPECT_EQ(3u, ranges.size());
  1446. EXPECT_EQ(1u, ranges[0].first);
  1447. EXPECT_EQ(10u, ranges[0].second);
  1448. EXPECT_EQ(100u, ranges[1].first);
  1449. EXPECT_EQ(200u, ranges[1].second);
  1450. EXPECT_EQ(300u, ranges[2].first);
  1451. EXPECT_EQ(400u, ranges[2].second);
  1452. }
  1453. {
  1454. Ranges ranges;
  1455. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1456. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1457. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1458. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1459. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1460. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1461. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1462. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1463. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1464. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1465. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1466. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1467. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1468. EXPECT_TRUE(ranges.empty());
  1469. }
  1470. }
  1471. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1472. Request req;
  1473. req.set_header("Accept-Encoding", "gzip");
  1474. Response res;
  1475. res.set_header("Content-Type", "text/plain");
  1476. auto ret = detail::encoding_type(req, res);
  1477. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1478. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1479. #else
  1480. EXPECT_TRUE(ret == detail::EncodingType::None);
  1481. #endif
  1482. }
  1483. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1484. Request req;
  1485. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1486. Response res;
  1487. res.set_header("Content-Type", "text/plain");
  1488. auto ret = detail::encoding_type(req, res);
  1489. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1490. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1491. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1492. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1493. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1494. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1495. #else
  1496. EXPECT_TRUE(ret == detail::EncodingType::None);
  1497. #endif
  1498. }
  1499. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1500. Request req;
  1501. req.set_header("Accept-Encoding",
  1502. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1503. Response res;
  1504. res.set_header("Content-Type", "text/plain");
  1505. auto ret = detail::encoding_type(req, res);
  1506. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1507. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1508. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1509. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1510. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1512. #else
  1513. EXPECT_TRUE(ret == detail::EncodingType::None);
  1514. #endif
  1515. }
  1516. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1517. // All supported encodings rejected with q=0 should return None
  1518. Request req;
  1519. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1520. Response res;
  1521. res.set_header("Content-Type", "text/plain");
  1522. auto ret = detail::encoding_type(req, res);
  1523. EXPECT_TRUE(ret == detail::EncodingType::None);
  1524. }
  1525. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1526. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1527. Request req;
  1528. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1529. Response res;
  1530. res.set_header("Content-Type", "text/plain");
  1531. auto ret = detail::encoding_type(req, res);
  1532. EXPECT_TRUE(ret == detail::EncodingType::None);
  1533. }
  1534. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1535. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1536. Request req;
  1537. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1538. Response res;
  1539. res.set_header("Content-Type", "text/plain");
  1540. auto ret = detail::encoding_type(req, res);
  1541. EXPECT_TRUE(ret == detail::EncodingType::None);
  1542. }
  1543. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1544. // RFC 7231: Accept-Encoding values are case-insensitive
  1545. Request req;
  1546. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1547. Response res;
  1548. res.set_header("Content-Type", "text/plain");
  1549. auto ret = detail::encoding_type(req, res);
  1550. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1551. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1552. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1553. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1554. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1555. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1556. #else
  1557. EXPECT_TRUE(ret == detail::EncodingType::None);
  1558. #endif
  1559. }
  1560. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1561. // q value should determine priority, not hardcoded order
  1562. Request req;
  1563. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1564. Response res;
  1565. res.set_header("Content-Type", "text/plain");
  1566. auto ret = detail::encoding_type(req, res);
  1567. // gzip has highest q=1.0, so it should be selected even though
  1568. // br and zstd are also supported
  1569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1570. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1571. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1572. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1573. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1575. #else
  1576. EXPECT_TRUE(ret == detail::EncodingType::None);
  1577. #endif
  1578. }
  1579. TEST(BufferStreamTest, read) {
  1580. detail::BufferStream strm1;
  1581. Stream &strm = strm1;
  1582. EXPECT_EQ(5, strm.write("hello"));
  1583. char buf[512];
  1584. EXPECT_EQ(2, strm.read(buf, 2));
  1585. EXPECT_EQ('h', buf[0]);
  1586. EXPECT_EQ('e', buf[1]);
  1587. EXPECT_EQ(2, strm.read(buf, 2));
  1588. EXPECT_EQ('l', buf[0]);
  1589. EXPECT_EQ('l', buf[1]);
  1590. EXPECT_EQ(1, strm.read(buf, 1));
  1591. EXPECT_EQ('o', buf[0]);
  1592. EXPECT_EQ(0, strm.read(buf, 1));
  1593. }
  1594. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1595. auto host = "www.httpwatch.com";
  1596. auto ip = hosted_at(host);
  1597. EXPECT_EQ("23.96.13.243", ip);
  1598. std::vector<std::string> addrs;
  1599. hosted_at(host, addrs);
  1600. EXPECT_EQ(1u, addrs.size());
  1601. }
  1602. #if 0 // It depends on each test environment...
  1603. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1604. auto host = "www.youtube.com";
  1605. std::vector<std::string> addrs;
  1606. hosted_at(host, addrs);
  1607. EXPECT_EQ(20u, addrs.size());
  1608. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1609. EXPECT_TRUE(it != addrs.end());
  1610. }
  1611. #endif
  1612. class ChunkedEncodingTest : public ::testing::Test {
  1613. protected:
  1614. ChunkedEncodingTest()
  1615. : cli_(HOST, PORT)
  1616. #ifdef CPPHTTPLIB_SSL_ENABLED
  1617. ,
  1618. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1619. #endif
  1620. {
  1621. cli_.set_connection_timeout(2);
  1622. #ifdef CPPHTTPLIB_SSL_ENABLED
  1623. cli_.enable_server_certificate_verification(false);
  1624. #endif
  1625. }
  1626. virtual void SetUp() {
  1627. read_file("./image.jpg", image_data_);
  1628. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content("Hello World!", "text/plain");
  1630. });
  1631. svr_.Get(
  1632. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1633. res.set_chunked_content_provider(
  1634. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1635. size_t remaining = image_data_.size() - offset;
  1636. if (remaining == 0) {
  1637. sink.done();
  1638. } else {
  1639. constexpr size_t CHUNK_SIZE = 1024;
  1640. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1641. sink.write(&image_data_[offset], send_size);
  1642. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1643. }
  1644. return true;
  1645. });
  1646. });
  1647. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1648. svr_.wait_until_ready();
  1649. }
  1650. virtual void TearDown() {
  1651. svr_.stop();
  1652. if (!request_threads_.empty()) {
  1653. std::this_thread::sleep_for(std::chrono::seconds(1));
  1654. for (auto &t : request_threads_) {
  1655. t.join();
  1656. }
  1657. }
  1658. t_.join();
  1659. }
  1660. #ifdef CPPHTTPLIB_SSL_ENABLED
  1661. SSLClient cli_;
  1662. SSLServer svr_;
  1663. #else
  1664. Client cli_;
  1665. Server svr_;
  1666. #endif
  1667. thread t_;
  1668. std::vector<thread> request_threads_;
  1669. std::string image_data_;
  1670. };
  1671. TEST_F(ChunkedEncodingTest, NormalGet) {
  1672. auto res = cli_.Get("/chunked");
  1673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1674. std::string out;
  1675. read_file("./image.jpg", out);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. EXPECT_EQ(out, res->body);
  1678. }
  1679. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1680. std::string body;
  1681. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1682. body.append(data, data_length);
  1683. return true;
  1684. });
  1685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1686. std::string out;
  1687. read_file("./image.jpg", out);
  1688. EXPECT_EQ(StatusCode::OK_200, res->status);
  1689. EXPECT_EQ(out, body);
  1690. }
  1691. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1692. std::string body;
  1693. auto res = cli_.Get(
  1694. "/chunked",
  1695. [&](const Response &response) {
  1696. EXPECT_EQ(StatusCode::OK_200, response.status);
  1697. return true;
  1698. },
  1699. [&](const char *data, size_t data_length) {
  1700. body.append(data, data_length);
  1701. return true;
  1702. });
  1703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1704. std::string out;
  1705. read_file("./image.jpg", out);
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ(out, body);
  1708. }
  1709. TEST(RangeTest, FromHTTPBin_Online) {
  1710. auto host = "httpbingo.org";
  1711. auto path = std::string{"/range/32"};
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. auto port = 443;
  1714. SSLClient cli(host, port);
  1715. #else
  1716. auto port = 80;
  1717. Client cli(host, port);
  1718. #endif
  1719. cli.set_connection_timeout(5);
  1720. {
  1721. auto res = cli.Get(path);
  1722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1723. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1724. EXPECT_EQ(StatusCode::OK_200, res->status);
  1725. }
  1726. {
  1727. Headers headers = {make_range_header({{1, -1}})};
  1728. auto res = cli.Get(path, headers);
  1729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1730. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1732. }
  1733. {
  1734. Headers headers = {make_range_header({{1, 10}})};
  1735. auto res = cli.Get(path, headers);
  1736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1737. EXPECT_EQ("bcdefghijk", res->body);
  1738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1739. }
  1740. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1741. // entire resource, while the original httpbin returned 200. Both are
  1742. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1743. {
  1744. Headers headers = {make_range_header({{0, 31}})};
  1745. auto res = cli.Get(path, headers);
  1746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1747. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1748. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1749. res->status == StatusCode::PartialContent_206);
  1750. }
  1751. {
  1752. Headers headers = {make_range_header({{0, -1}})};
  1753. auto res = cli.Get(path, headers);
  1754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1755. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1756. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1757. res->status == StatusCode::PartialContent_206);
  1758. }
  1759. // go-httpbin returns 206 with clamped range for over-range requests,
  1760. // while the original httpbin returned 416. Both behaviors are observed
  1761. // in real servers, so we only verify the request succeeds.
  1762. {
  1763. Headers headers = {make_range_header({{0, 32}})};
  1764. auto res = cli.Get(path, headers);
  1765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1766. }
  1767. }
  1768. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1769. auto host = "unresolvableaddress.local";
  1770. auto path = std::string{"/"};
  1771. #ifdef CPPHTTPLIB_SSL_ENABLED
  1772. auto port = 443;
  1773. SSLClient cli(host, port);
  1774. #else
  1775. auto port = 80;
  1776. Client cli(host, port);
  1777. #endif
  1778. cli.set_connection_timeout(1);
  1779. {
  1780. auto res = cli.Get(path);
  1781. ASSERT_FALSE(res);
  1782. }
  1783. std::this_thread::sleep_for(std::chrono::seconds(8));
  1784. }
  1785. #if defined(__linux__) && defined(__GLIBC__) && \
  1786. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1787. // Forward declaration: in split builds split.py strips `inline` and moves the
  1788. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1789. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1790. // against the symbol in both header-only and split builds.
  1791. namespace httplib {
  1792. namespace detail {
  1793. int getaddrinfo_with_timeout(const char *node, const char *service,
  1794. const struct addrinfo *hints,
  1795. struct addrinfo **res, time_t timeout_sec);
  1796. } // namespace detail
  1797. } // namespace httplib
  1798. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1799. //
  1800. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1801. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1802. // gai_suspend() call hits the connection timeout the function calls
  1803. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1804. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1805. // still alive and still references the now-destroyed stack frame.
  1806. //
  1807. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1808. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1809. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1810. // and runs them in a container.
  1811. namespace {
  1812. bool should_run_issue_2431_tests() {
  1813. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1814. return v && *v && std::string(v) != "0";
  1815. }
  1816. std::string unique_unresolvable_host(int n) {
  1817. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1818. // glibc still asks the configured nameserver — which is exactly the path
  1819. // we want to exercise. A unique label per call avoids the resolver cache.
  1820. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1821. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1822. std::to_string(n) + ".invalid";
  1823. }
  1824. } // namespace
  1825. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1826. if (!should_run_issue_2431_tests()) {
  1827. GTEST_SKIP()
  1828. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1829. }
  1830. for (int i = 0; i < 8; ++i) {
  1831. struct addrinfo hints;
  1832. memset(&hints, 0, sizeof(hints));
  1833. hints.ai_family = AF_UNSPEC;
  1834. hints.ai_socktype = SOCK_STREAM;
  1835. auto host = unique_unresolvable_host(i);
  1836. struct addrinfo *result = nullptr;
  1837. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1838. &result, /*timeout_sec=*/1);
  1839. if (rc == 0 && result) { freeaddrinfo(result); }
  1840. }
  1841. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1842. // stack region they still believe holds their gaicb.
  1843. std::this_thread::sleep_for(std::chrono::seconds(3));
  1844. }
  1845. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1846. if (!should_run_issue_2431_tests()) {
  1847. GTEST_SKIP()
  1848. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1849. }
  1850. std::atomic<bool> stop{false};
  1851. std::vector<std::thread> threads;
  1852. for (int t = 0; t < 8; ++t) {
  1853. threads.emplace_back([t, &stop] {
  1854. int i = 0;
  1855. while (!stop.load(std::memory_order_relaxed)) {
  1856. struct addrinfo hints;
  1857. memset(&hints, 0, sizeof(hints));
  1858. hints.ai_family = AF_UNSPEC;
  1859. hints.ai_socktype = SOCK_STREAM;
  1860. auto host = unique_unresolvable_host(t * 100000 + i++);
  1861. struct addrinfo *result = nullptr;
  1862. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1863. &result, /*timeout_sec=*/1);
  1864. if (rc == 0 && result) { freeaddrinfo(result); }
  1865. }
  1866. });
  1867. }
  1868. std::this_thread::sleep_for(std::chrono::seconds(8));
  1869. stop.store(true, std::memory_order_relaxed);
  1870. for (auto &th : threads) {
  1871. th.join();
  1872. }
  1873. std::this_thread::sleep_for(std::chrono::seconds(3));
  1874. }
  1875. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1876. if (!should_run_issue_2431_tests()) {
  1877. GTEST_SKIP()
  1878. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1879. }
  1880. std::atomic<bool> stop{false};
  1881. std::vector<std::thread> threads;
  1882. for (int t = 0; t < 8; ++t) {
  1883. threads.emplace_back([t, &stop] {
  1884. int i = 0;
  1885. while (!stop.load(std::memory_order_relaxed)) {
  1886. auto host = unique_unresolvable_host(t * 100000 + i++);
  1887. Client cli(host, 80);
  1888. cli.set_connection_timeout(1, 0);
  1889. cli.set_read_timeout(1, 0);
  1890. cli.set_write_timeout(1, 0);
  1891. (void)cli.Get("/");
  1892. }
  1893. });
  1894. }
  1895. std::this_thread::sleep_for(std::chrono::seconds(8));
  1896. stop.store(true, std::memory_order_relaxed);
  1897. for (auto &th : threads) {
  1898. th.join();
  1899. }
  1900. std::this_thread::sleep_for(std::chrono::seconds(3));
  1901. }
  1902. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1903. TEST(ConnectionErrorTest, InvalidHost) {
  1904. auto host = "-abcde.com";
  1905. #ifdef CPPHTTPLIB_SSL_ENABLED
  1906. auto port = 443;
  1907. SSLClient cli(host, port);
  1908. #else
  1909. auto port = 80;
  1910. Client cli(host, port);
  1911. #endif
  1912. cli.set_connection_timeout(std::chrono::seconds(2));
  1913. auto res = cli.Get("/");
  1914. ASSERT_TRUE(!res);
  1915. EXPECT_EQ(Error::Connection, res.error());
  1916. }
  1917. TEST(ConnectionErrorTest, InvalidHost2) {
  1918. auto host = "httpcan.org/";
  1919. #ifdef CPPHTTPLIB_SSL_ENABLED
  1920. SSLClient cli(host);
  1921. #else
  1922. Client cli(host);
  1923. #endif
  1924. cli.set_connection_timeout(std::chrono::seconds(2));
  1925. auto res = cli.Get("/");
  1926. ASSERT_TRUE(!res);
  1927. EXPECT_EQ(Error::Connection, res.error());
  1928. }
  1929. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1930. auto host = "httpcan.org/";
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. SSLClient cli(host);
  1933. #else
  1934. Client cli(host);
  1935. #endif
  1936. cli.set_connection_timeout(std::chrono::seconds(2));
  1937. auto res = cli.Get("/");
  1938. ASSERT_TRUE(!res);
  1939. stringstream s;
  1940. s << "error code: " << res.error();
  1941. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1942. }
  1943. TEST(ConnectionErrorTest, InvalidPort) {
  1944. auto host = "localhost";
  1945. auto port = 44380;
  1946. #ifdef CPPHTTPLIB_SSL_ENABLED
  1947. SSLClient cli(host, port);
  1948. #else
  1949. Client cli(host, port);
  1950. #endif
  1951. cli.set_connection_timeout(std::chrono::seconds(2));
  1952. auto res = cli.Get("/");
  1953. ASSERT_TRUE(!res);
  1954. EXPECT_TRUE(Error::Connection == res.error() ||
  1955. Error::ConnectionTimeout == res.error());
  1956. }
  1957. TEST(ConnectionErrorTest, Timeout_Online) {
  1958. auto host = "google.com";
  1959. #ifdef CPPHTTPLIB_SSL_ENABLED
  1960. auto port = 44380;
  1961. SSLClient cli(host, port);
  1962. #else
  1963. auto port = 8080;
  1964. Client cli(host, port);
  1965. #endif
  1966. cli.set_connection_timeout(std::chrono::seconds(2));
  1967. // only probe one address type so that the error reason
  1968. // correlates to the timed-out IPv4, not the unsupported
  1969. // IPv6 connection attempt
  1970. cli.set_address_family(AF_INET);
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(!res);
  1973. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1974. }
  1975. TEST(CancelTest, NoCancel_Online) {
  1976. auto host = "httpbingo.org";
  1977. auto path = std::string{"/range/32"};
  1978. #ifdef CPPHTTPLIB_SSL_ENABLED
  1979. auto port = 443;
  1980. SSLClient cli(host, port);
  1981. #else
  1982. auto port = 80;
  1983. Client cli(host, port);
  1984. #endif
  1985. cli.set_connection_timeout(std::chrono::seconds(5));
  1986. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1988. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1989. EXPECT_EQ(StatusCode::OK_200, res->status);
  1990. }
  1991. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1992. // Use /bytes with a large payload so that the DownloadProgress callback
  1993. // (which only fires for Content-Length responses) is invoked before the
  1994. // entire body is received, giving cancellation a chance to fire.
  1995. auto host = "httpbingo.org";
  1996. auto path = std::string{"/bytes/524288"};
  1997. #ifdef CPPHTTPLIB_SSL_ENABLED
  1998. auto port = 443;
  1999. SSLClient cli(host, port);
  2000. #else
  2001. auto port = 80;
  2002. Client cli(host, port);
  2003. #endif
  2004. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2005. cli.set_connection_timeout(std::chrono::seconds(5));
  2006. ASSERT_TRUE(!res);
  2007. EXPECT_EQ(Error::Canceled, res.error());
  2008. }
  2009. TEST(CancelTest, WithCancelLargePayload_Online) {
  2010. auto host = "httpbingo.org";
  2011. auto path = std::string{"/bytes/524288"};
  2012. #ifdef CPPHTTPLIB_SSL_ENABLED
  2013. auto port = 443;
  2014. SSLClient cli(host, port);
  2015. #else
  2016. auto port = 80;
  2017. Client cli(host, port);
  2018. #endif
  2019. cli.set_connection_timeout(std::chrono::seconds(5));
  2020. uint32_t count = 0;
  2021. auto res =
  2022. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2023. ASSERT_TRUE(!res);
  2024. EXPECT_EQ(Error::Canceled, res.error());
  2025. }
  2026. TEST(CancelTest, NoCancelPost) {
  2027. Server svr;
  2028. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2029. res.set_content("Hello World!", "text/plain");
  2030. });
  2031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2032. auto se = detail::scope_exit([&] {
  2033. svr.stop();
  2034. thread.join();
  2035. ASSERT_FALSE(svr.is_running());
  2036. });
  2037. svr.wait_until_ready();
  2038. Client cli(HOST, PORT);
  2039. cli.set_connection_timeout(std::chrono::seconds(5));
  2040. auto res =
  2041. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2042. "application/json", [](uint64_t, uint64_t) { return true; });
  2043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2044. EXPECT_EQ("Hello World!", res->body);
  2045. EXPECT_EQ(StatusCode::OK_200, res->status);
  2046. }
  2047. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2048. Server svr;
  2049. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2050. res.set_content("Hello World!", "text/plain");
  2051. });
  2052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2053. auto se = detail::scope_exit([&] {
  2054. svr.stop();
  2055. thread.join();
  2056. ASSERT_FALSE(svr.is_running());
  2057. });
  2058. svr.wait_until_ready();
  2059. Client cli(HOST, PORT);
  2060. cli.set_connection_timeout(std::chrono::seconds(5));
  2061. auto res =
  2062. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2063. "application/json", [](uint64_t, uint64_t) { return false; });
  2064. ASSERT_TRUE(!res);
  2065. EXPECT_EQ(Error::Canceled, res.error());
  2066. }
  2067. TEST(CancelTest, WithCancelLargePayloadPost) {
  2068. Server svr;
  2069. svr.set_payload_max_length(200 * 1024 * 1024);
  2070. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2071. res.set_content(LARGE_DATA, "text/plain");
  2072. });
  2073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2074. auto se = detail::scope_exit([&] {
  2075. svr.stop();
  2076. thread.join();
  2077. ASSERT_FALSE(svr.is_running());
  2078. });
  2079. svr.wait_until_ready();
  2080. Client cli(HOST, PORT);
  2081. cli.set_payload_max_length(200 * 1024 * 1024);
  2082. cli.set_connection_timeout(std::chrono::seconds(5));
  2083. auto res =
  2084. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2085. "application/json", [](uint64_t, uint64_t) { return false; });
  2086. ASSERT_TRUE(!res);
  2087. EXPECT_EQ(Error::Canceled, res.error());
  2088. }
  2089. TEST(CancelTest, NoCancelPut) {
  2090. Server svr;
  2091. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2092. res.set_content("Hello World!", "text/plain");
  2093. });
  2094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2095. auto se = detail::scope_exit([&] {
  2096. svr.stop();
  2097. thread.join();
  2098. ASSERT_FALSE(svr.is_running());
  2099. });
  2100. svr.wait_until_ready();
  2101. Client cli(HOST, PORT);
  2102. cli.set_connection_timeout(std::chrono::seconds(5));
  2103. auto res =
  2104. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2105. "application/json", [](uint64_t, uint64_t) { return true; });
  2106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2107. EXPECT_EQ("Hello World!", res->body);
  2108. EXPECT_EQ(StatusCode::OK_200, res->status);
  2109. }
  2110. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2111. Server svr;
  2112. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2113. res.set_content("Hello World!", "text/plain");
  2114. });
  2115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2116. auto se = detail::scope_exit([&] {
  2117. svr.stop();
  2118. thread.join();
  2119. ASSERT_FALSE(svr.is_running());
  2120. });
  2121. svr.wait_until_ready();
  2122. Client cli(HOST, PORT);
  2123. cli.set_connection_timeout(std::chrono::seconds(5));
  2124. auto res =
  2125. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2126. "application/json", [](uint64_t, uint64_t) { return false; });
  2127. ASSERT_TRUE(!res);
  2128. EXPECT_EQ(Error::Canceled, res.error());
  2129. }
  2130. TEST(CancelTest, WithCancelLargePayloadPut) {
  2131. Server svr;
  2132. svr.set_payload_max_length(200 * 1024 * 1024);
  2133. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2134. res.set_content(LARGE_DATA, "text/plain");
  2135. });
  2136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2137. auto se = detail::scope_exit([&] {
  2138. svr.stop();
  2139. thread.join();
  2140. ASSERT_FALSE(svr.is_running());
  2141. });
  2142. svr.wait_until_ready();
  2143. Client cli(HOST, PORT);
  2144. cli.set_payload_max_length(200 * 1024 * 1024);
  2145. cli.set_connection_timeout(std::chrono::seconds(5));
  2146. auto res =
  2147. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2148. "application/json", [](uint64_t, uint64_t) { return false; });
  2149. ASSERT_TRUE(!res);
  2150. EXPECT_EQ(Error::Canceled, res.error());
  2151. }
  2152. TEST(CancelTest, NoCancelPatch) {
  2153. Server svr;
  2154. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2155. res.set_content("Hello World!", "text/plain");
  2156. });
  2157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2158. auto se = detail::scope_exit([&] {
  2159. svr.stop();
  2160. thread.join();
  2161. ASSERT_FALSE(svr.is_running());
  2162. });
  2163. svr.wait_until_ready();
  2164. Client cli(HOST, PORT);
  2165. cli.set_connection_timeout(std::chrono::seconds(5));
  2166. auto res =
  2167. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2168. "application/json", [](uint64_t, uint64_t) { return true; });
  2169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2170. EXPECT_EQ("Hello World!", res->body);
  2171. EXPECT_EQ(StatusCode::OK_200, res->status);
  2172. }
  2173. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2174. Server svr;
  2175. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2176. res.set_content("Hello World!", "text/plain");
  2177. });
  2178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2179. auto se = detail::scope_exit([&] {
  2180. svr.stop();
  2181. thread.join();
  2182. ASSERT_FALSE(svr.is_running());
  2183. });
  2184. svr.wait_until_ready();
  2185. Client cli(HOST, PORT);
  2186. cli.set_connection_timeout(std::chrono::seconds(5));
  2187. auto res =
  2188. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2189. "application/json", [](uint64_t, uint64_t) { return false; });
  2190. ASSERT_TRUE(!res);
  2191. EXPECT_EQ(Error::Canceled, res.error());
  2192. }
  2193. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2194. Server svr;
  2195. svr.set_payload_max_length(200 * 1024 * 1024);
  2196. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2197. res.set_content(LARGE_DATA, "text/plain");
  2198. });
  2199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2200. auto se = detail::scope_exit([&] {
  2201. svr.stop();
  2202. thread.join();
  2203. ASSERT_FALSE(svr.is_running());
  2204. });
  2205. svr.wait_until_ready();
  2206. Client cli(HOST, PORT);
  2207. cli.set_payload_max_length(200 * 1024 * 1024);
  2208. cli.set_connection_timeout(std::chrono::seconds(5));
  2209. auto res =
  2210. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2211. "application/json", [](uint64_t, uint64_t) { return false; });
  2212. ASSERT_TRUE(!res);
  2213. EXPECT_EQ(Error::Canceled, res.error());
  2214. }
  2215. TEST(CancelTest, NoCancelDelete) {
  2216. Server svr;
  2217. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2218. res.set_content("Hello World!", "text/plain");
  2219. });
  2220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2221. auto se = detail::scope_exit([&] {
  2222. svr.stop();
  2223. thread.join();
  2224. ASSERT_FALSE(svr.is_running());
  2225. });
  2226. svr.wait_until_ready();
  2227. Client cli(HOST, PORT);
  2228. cli.set_connection_timeout(std::chrono::seconds(5));
  2229. auto res =
  2230. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2231. "application/json", [](uint64_t, uint64_t) { return true; });
  2232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2233. EXPECT_EQ("Hello World!", res->body);
  2234. EXPECT_EQ(StatusCode::OK_200, res->status);
  2235. }
  2236. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2237. Server svr;
  2238. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2239. res.set_content("Hello World!", "text/plain");
  2240. });
  2241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2242. auto se = detail::scope_exit([&] {
  2243. svr.stop();
  2244. thread.join();
  2245. ASSERT_FALSE(svr.is_running());
  2246. });
  2247. svr.wait_until_ready();
  2248. Client cli(HOST, PORT);
  2249. cli.set_connection_timeout(std::chrono::seconds(5));
  2250. auto res =
  2251. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2252. "application/json", [](uint64_t, uint64_t) { return false; });
  2253. ASSERT_TRUE(!res);
  2254. EXPECT_EQ(Error::Canceled, res.error());
  2255. }
  2256. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2257. Server svr;
  2258. svr.set_payload_max_length(200 * 1024 * 1024);
  2259. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2260. res.set_content(LARGE_DATA, "text/plain");
  2261. });
  2262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2263. auto se = detail::scope_exit([&] {
  2264. svr.stop();
  2265. thread.join();
  2266. ASSERT_FALSE(svr.is_running());
  2267. });
  2268. svr.wait_until_ready();
  2269. Client cli(HOST, PORT);
  2270. cli.set_payload_max_length(200 * 1024 * 1024);
  2271. cli.set_connection_timeout(std::chrono::seconds(5));
  2272. auto res =
  2273. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2274. "application/json", [](uint64_t, uint64_t) { return false; });
  2275. ASSERT_TRUE(!res);
  2276. EXPECT_EQ(Error::Canceled, res.error());
  2277. }
  2278. static std::string remove_whitespace(const std::string &input) {
  2279. std::string output;
  2280. output.reserve(input.size());
  2281. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2282. [](unsigned char c) { return !std::isspace(c); });
  2283. return output;
  2284. }
  2285. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2286. auto host = "httpbingo.org";
  2287. auto path = std::string{"/basic-auth/hello/world"};
  2288. #ifdef CPPHTTPLIB_SSL_ENABLED
  2289. auto port = 443;
  2290. SSLClient cli(host, port);
  2291. #else
  2292. auto port = 80;
  2293. Client cli(host, port);
  2294. #endif
  2295. {
  2296. auto res = cli.Get(path);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2299. }
  2300. {
  2301. auto res = cli.Get(
  2302. path, Headers{make_basic_authentication_header("hello", "world")});
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. auto body = remove_whitespace(res->body);
  2305. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2306. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2307. EXPECT_EQ(StatusCode::OK_200, res->status);
  2308. }
  2309. {
  2310. cli.set_basic_auth("hello", "world");
  2311. auto res = cli.Get(path);
  2312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2313. auto body = remove_whitespace(res->body);
  2314. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2315. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2316. EXPECT_EQ(StatusCode::OK_200, res->status);
  2317. }
  2318. {
  2319. cli.set_basic_auth("hello", "bad");
  2320. auto res = cli.Get(path);
  2321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2322. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2323. }
  2324. {
  2325. cli.set_basic_auth("bad", "world");
  2326. auto res = cli.Get(path);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2329. }
  2330. }
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2333. auto host = "httpbingo.org";
  2334. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2335. auto paths = std::vector<std::string>{
  2336. "/digest-auth/auth/hello/world/MD5",
  2337. "/digest-auth/auth/hello/world/SHA-256",
  2338. };
  2339. auto port = 443;
  2340. SSLClient cli(host, port);
  2341. {
  2342. auto res = cli.Get(unauth_path);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2345. }
  2346. {
  2347. cli.set_digest_auth("hello", "world");
  2348. for (const auto &path : paths) {
  2349. auto res = cli.Get(path.c_str());
  2350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2351. auto body = remove_whitespace(res->body);
  2352. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2353. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2354. EXPECT_EQ(StatusCode::OK_200, res->status);
  2355. }
  2356. cli.set_digest_auth("hello", "bad");
  2357. for (const auto &path : paths) {
  2358. auto res = cli.Get(path.c_str());
  2359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2360. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2361. }
  2362. }
  2363. }
  2364. #endif
  2365. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2366. auto host = "google.com";
  2367. auto another_host = "example.com";
  2368. auto wrong_ip = "0.0.0.0";
  2369. #ifdef CPPHTTPLIB_SSL_ENABLED
  2370. SSLClient cli(host);
  2371. #else
  2372. Client cli(host);
  2373. #endif
  2374. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2375. auto res = cli.Get("/");
  2376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2377. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2378. }
  2379. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2380. auto host = "google.com";
  2381. auto wrong_ip = "0.0.0.0";
  2382. #ifdef CPPHTTPLIB_SSL_ENABLED
  2383. SSLClient cli(host);
  2384. #else
  2385. Client cli(host);
  2386. #endif
  2387. cli.set_hostname_addr_map({{host, wrong_ip}});
  2388. auto res = cli.Get("/");
  2389. ASSERT_TRUE(!res);
  2390. EXPECT_EQ(Error::Connection, res.error());
  2391. }
  2392. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2393. // A mapped value that is not an IP literal must be resolved. "localhost"
  2394. // resolves from the hosts file, so this test needs no external DNS.
  2395. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2396. auto host = "target.invalid";
  2397. Server svr;
  2398. std::string received_host;
  2399. svr.Get("/hi", [&](const Request &req, Response &res) {
  2400. received_host = req.get_header_value("Host");
  2401. res.set_content("Hello World!", "text/plain");
  2402. });
  2403. auto port = svr.bind_to_any_port(HOST);
  2404. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2405. auto se = detail::scope_exit([&] {
  2406. svr.stop();
  2407. thread.join();
  2408. ASSERT_FALSE(svr.is_running());
  2409. });
  2410. svr.wait_until_ready();
  2411. Client cli(host, port);
  2412. cli.set_hostname_addr_map({{host, HOST}});
  2413. auto res = cli.Get("/hi");
  2414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2415. EXPECT_EQ(StatusCode::OK_200, res->status);
  2416. // The mapping only redirects the connection; the identity stays host_.
  2417. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2418. }
  2419. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2420. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2421. auto host = "target.invalid";
  2422. Server svr;
  2423. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2424. res.set_content("Hello World!", "text/plain");
  2425. });
  2426. auto port = svr.bind_to_any_port("127.0.0.1");
  2427. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2428. auto se = detail::scope_exit([&] {
  2429. svr.stop();
  2430. thread.join();
  2431. ASSERT_FALSE(svr.is_running());
  2432. });
  2433. svr.wait_until_ready();
  2434. Client cli(host, port);
  2435. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2436. auto res = cli.Get("/hi");
  2437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2438. EXPECT_EQ(StatusCode::OK_200, res->status);
  2439. }
  2440. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2441. // An empty mapped value must leave host_ as the connection target. Without
  2442. // that guard the empty value would become the host argument, getaddrinfo
  2443. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2444. // loopback - silently connecting somewhere the caller never asked for.
  2445. // The server listens on loopback, so such a fallback would succeed and is
  2446. // therefore observable as a failure of this test.
  2447. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2448. Server svr;
  2449. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto port = svr.bind_to_any_port(HOST);
  2453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2454. auto se = detail::scope_exit([&] {
  2455. svr.stop();
  2456. thread.join();
  2457. ASSERT_FALSE(svr.is_running());
  2458. });
  2459. svr.wait_until_ready();
  2460. Client cli(blackhole, port);
  2461. cli.set_hostname_addr_map({{blackhole, ""}});
  2462. cli.set_connection_timeout(1);
  2463. auto res = cli.Get("/hi");
  2464. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2465. }
  2466. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2467. auto host = "httpbingo.org";
  2468. auto path = std::string{"/absolute-redirect/3"};
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. SSLClient cli(host);
  2471. #else
  2472. Client cli(host);
  2473. #endif
  2474. cli.set_follow_location(true);
  2475. auto res = cli.Get(path);
  2476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2477. EXPECT_EQ(StatusCode::OK_200, res->status);
  2478. }
  2479. TEST(RedirectTest, Redirect_Online) {
  2480. auto host = "httpbingo.org";
  2481. auto path = std::string{"/redirect/3"};
  2482. #ifdef CPPHTTPLIB_SSL_ENABLED
  2483. SSLClient cli(host);
  2484. #else
  2485. Client cli(host);
  2486. #endif
  2487. cli.set_follow_location(true);
  2488. auto res = cli.Get(path);
  2489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(RelativeRedirectTest, Redirect_Online) {
  2493. auto host = "httpbingo.org";
  2494. auto path = std::string{"/relative-redirect/3"};
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_follow_location(true);
  2501. auto res = cli.Get(path);
  2502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2503. EXPECT_EQ(StatusCode::OK_200, res->status);
  2504. }
  2505. TEST(TooManyRedirectTest, Redirect_Online) {
  2506. auto host = "httpbingo.org";
  2507. auto path = std::string{"/redirect/21"};
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host);
  2510. #else
  2511. Client cli(host);
  2512. #endif
  2513. cli.set_follow_location(true);
  2514. auto res = cli.Get(path);
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2517. }
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. TEST(YahooRedirectTest, Redirect_Online) {
  2520. Client cli("yahoo.com");
  2521. auto res = cli.Get("/");
  2522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2523. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2524. cli.set_follow_location(true);
  2525. res = cli.Get("/");
  2526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2527. EXPECT_EQ(StatusCode::OK_200, res->status);
  2528. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2529. }
  2530. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2531. #define REDIR_HOST "httpbingo.org"
  2532. #define REDIR_PATH "/redirect-to"
  2533. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2534. SSLClient cli(REDIR_HOST);
  2535. cli.set_follow_location(true);
  2536. auto res =
  2537. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. }
  2541. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2542. SSLClient cli(REDIR_HOST);
  2543. cli.set_follow_location(true);
  2544. Params params;
  2545. params.emplace("url", "http://example.com");
  2546. params.emplace("status_code", "302");
  2547. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ(StatusCode::OK_200, res->status);
  2550. }
  2551. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2552. SSLClient cli(REDIR_HOST);
  2553. cli.set_follow_location(true);
  2554. Params params;
  2555. params.emplace("url", "http://example.com");
  2556. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2558. EXPECT_EQ(StatusCode::OK_200, res->status);
  2559. }
  2560. TEST(UrlWithSpace, Redirect_Online) {
  2561. SSLClient cli("edge.forgecdn.net");
  2562. cli.set_follow_location(true);
  2563. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ(StatusCode::OK_200, res->status);
  2566. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2567. }
  2568. #endif
  2569. #if !defined(_WIN32) && !defined(_WIN64)
  2570. TEST(ReceiveSignals, Signal) {
  2571. auto setupSignalHandlers = []() {
  2572. struct sigaction act;
  2573. sigemptyset(&act.sa_mask);
  2574. act.sa_flags = SA_SIGINFO;
  2575. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2576. switch (sig) {
  2577. case SIGINT:
  2578. default: break;
  2579. }
  2580. };
  2581. ::sigaction(SIGINT, &act, nullptr);
  2582. };
  2583. Server svr;
  2584. int port = 0;
  2585. auto thread = std::thread([&]() {
  2586. setupSignalHandlers();
  2587. port = svr.bind_to_any_port(HOST);
  2588. svr.listen_after_bind();
  2589. });
  2590. auto se = detail::scope_exit([&] {
  2591. svr.stop();
  2592. thread.join();
  2593. ASSERT_FALSE(svr.is_running());
  2594. });
  2595. svr.wait_until_ready();
  2596. ASSERT_TRUE(svr.is_running());
  2597. pthread_kill(thread.native_handle(), SIGINT);
  2598. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2599. ASSERT_TRUE(svr.is_running());
  2600. }
  2601. #endif
  2602. TEST(RedirectToDifferentPort, Redirect) {
  2603. Server svr1;
  2604. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2605. res.set_content("Hello World!", "text/plain");
  2606. });
  2607. int svr1_port = 0;
  2608. auto thread1 = std::thread([&]() {
  2609. svr1_port = svr1.bind_to_any_port(HOST);
  2610. svr1.listen_after_bind();
  2611. });
  2612. Server svr2;
  2613. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2614. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2615. });
  2616. int svr2_port = 0;
  2617. auto thread2 = std::thread([&]() {
  2618. svr2_port = svr2.bind_to_any_port(HOST);
  2619. svr2.listen_after_bind();
  2620. });
  2621. auto se = detail::scope_exit([&] {
  2622. svr2.stop();
  2623. thread2.join();
  2624. svr1.stop();
  2625. thread1.join();
  2626. ASSERT_FALSE(svr2.is_running());
  2627. ASSERT_FALSE(svr1.is_running());
  2628. });
  2629. svr1.wait_until_ready();
  2630. svr2.wait_until_ready();
  2631. Client cli("localhost", svr2_port);
  2632. cli.set_follow_location(true);
  2633. auto res = cli.Get("/2");
  2634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2635. EXPECT_EQ(StatusCode::OK_200, res->status);
  2636. EXPECT_EQ("Hello World!", res->body);
  2637. }
  2638. static void
  2639. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2640. Server svr1;
  2641. std::string captured_authorization;
  2642. svr1.Get("/target", [&](const Request &req, Response &res) {
  2643. captured_authorization = req.get_header_value("Authorization");
  2644. res.set_content("OK", "text/plain");
  2645. });
  2646. int svr1_port = 0;
  2647. auto thread1 = std::thread([&]() {
  2648. svr1_port = svr1.bind_to_any_port(HOST);
  2649. svr1.listen_after_bind();
  2650. });
  2651. Server svr2;
  2652. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2653. res.set_redirect(
  2654. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2655. });
  2656. int svr2_port = 0;
  2657. auto thread2 = std::thread([&]() {
  2658. svr2_port = svr2.bind_to_any_port(HOST);
  2659. svr2.listen_after_bind();
  2660. });
  2661. auto se = detail::scope_exit([&] {
  2662. svr2.stop();
  2663. thread2.join();
  2664. svr1.stop();
  2665. thread1.join();
  2666. ASSERT_FALSE(svr2.is_running());
  2667. ASSERT_FALSE(svr1.is_running());
  2668. });
  2669. svr1.wait_until_ready();
  2670. svr2.wait_until_ready();
  2671. Client cli("localhost", svr2_port);
  2672. cli.set_follow_location(true);
  2673. set_auth(cli);
  2674. auto res = cli.Get("/redir");
  2675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2676. EXPECT_EQ(StatusCode::OK_200, res->status);
  2677. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2678. EXPECT_TRUE(captured_authorization.empty());
  2679. }
  2680. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2681. TestDoNotForwardCredentialsOnRedirect(
  2682. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2683. }
  2684. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2685. TestDoNotForwardCredentialsOnRedirect(
  2686. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2687. }
  2688. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2689. Server svr1;
  2690. std::string captured_cookie;
  2691. bool target_hit = false;
  2692. svr1.Get("/target", [&](const Request &req, Response &res) {
  2693. captured_cookie = req.get_header_value("Cookie");
  2694. target_hit = true;
  2695. res.set_content("OK", "text/plain");
  2696. });
  2697. int svr1_port = 0;
  2698. auto thread1 = std::thread([&]() {
  2699. svr1_port = svr1.bind_to_any_port(HOST);
  2700. svr1.listen_after_bind();
  2701. });
  2702. Server svr2;
  2703. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2704. res.set_redirect(
  2705. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2706. });
  2707. int svr2_port = 0;
  2708. auto thread2 = std::thread([&]() {
  2709. svr2_port = svr2.bind_to_any_port(HOST);
  2710. svr2.listen_after_bind();
  2711. });
  2712. auto se = detail::scope_exit([&] {
  2713. svr2.stop();
  2714. thread2.join();
  2715. svr1.stop();
  2716. thread1.join();
  2717. ASSERT_FALSE(svr2.is_running());
  2718. ASSERT_FALSE(svr1.is_running());
  2719. });
  2720. svr1.wait_until_ready();
  2721. svr2.wait_until_ready();
  2722. Client cli("localhost", svr2_port);
  2723. cli.set_follow_location(true);
  2724. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2725. auto res = cli.Get("/redir", headers);
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. EXPECT_TRUE(target_hit);
  2729. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2730. EXPECT_TRUE(captured_cookie.empty());
  2731. }
  2732. TEST(RedirectToSamePort, ForwardCookie) {
  2733. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2734. // header so that ordinary session flows keep working.
  2735. Server svr;
  2736. std::string captured_cookie;
  2737. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2738. res.set_redirect("/target", 302);
  2739. });
  2740. svr.Get("/target", [&](const Request &req, Response &res) {
  2741. captured_cookie = req.get_header_value("Cookie");
  2742. res.set_content("OK", "text/plain");
  2743. });
  2744. auto port = svr.bind_to_any_port(HOST);
  2745. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, port);
  2753. cli.set_follow_location(true);
  2754. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2755. auto res = cli.Get("/redir", headers);
  2756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2757. EXPECT_EQ(StatusCode::OK_200, res->status);
  2758. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2759. }
  2760. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2761. Server svr;
  2762. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2763. // Port number that overflows int — should not crash
  2764. res.set_redirect("http://localhost:99999999999999999999/target");
  2765. });
  2766. auto port = svr.bind_to_any_port(HOST);
  2767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. Client cli(HOST, port);
  2775. cli.set_follow_location(true);
  2776. auto res = cli.Get("/redir");
  2777. // Should fail gracefully, not crash (no valid response due to bad port)
  2778. EXPECT_FALSE(res);
  2779. }
  2780. TEST(RedirectFromPageWithContent, Redirect) {
  2781. Server svr;
  2782. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2783. res.set_content("___", "text/plain");
  2784. res.set_redirect("/2");
  2785. });
  2786. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("Hello World!", "text/plain");
  2788. });
  2789. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. th.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. {
  2797. Client cli("localhost", PORT);
  2798. cli.set_follow_location(true);
  2799. std::string body;
  2800. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2801. body.append(data, data_length);
  2802. return true;
  2803. });
  2804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2805. EXPECT_EQ(StatusCode::OK_200, res->status);
  2806. EXPECT_EQ("Hello World!", body);
  2807. }
  2808. {
  2809. Client cli("localhost", PORT);
  2810. std::string body;
  2811. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2812. body.append(data, data_length);
  2813. return true;
  2814. });
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. EXPECT_EQ(StatusCode::Found_302, res->status);
  2817. EXPECT_EQ("___", body);
  2818. }
  2819. }
  2820. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2821. Server svr;
  2822. auto port_str = std::to_string(PORT);
  2823. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2824. auto expected_host = "[::1]:" + port_str;
  2825. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2826. res.set_content("___", "text/plain");
  2827. // res.set_redirect("/2");
  2828. res.set_redirect(redirect_url);
  2829. });
  2830. svr.Get("/2", [&](const Request &req, Response &res) {
  2831. auto host_header = req.headers.find("Host");
  2832. ASSERT_TRUE(host_header != req.headers.end());
  2833. EXPECT_EQ(expected_host, host_header->second);
  2834. res.set_content("Hello World!", "text/plain");
  2835. });
  2836. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. th.join();
  2840. ASSERT_FALSE(svr.is_running());
  2841. });
  2842. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2843. // actually starts anything, so the condition !svr.is_running() will
  2844. // always remain true, and the loop never stops.
  2845. // This basically counts how many milliseconds have passed since the
  2846. // call to svr.listen(), and if after 5 seconds nothing started yet
  2847. // aborts the test.
  2848. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2849. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2850. ASSERT_LT(milliseconds, 5000U);
  2851. }
  2852. {
  2853. Client cli("::1", PORT);
  2854. cli.set_follow_location(true);
  2855. std::string body;
  2856. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2857. body.append(data, data_length);
  2858. return true;
  2859. });
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. EXPECT_EQ(StatusCode::OK_200, res->status);
  2862. EXPECT_EQ("Hello World!", body);
  2863. }
  2864. {
  2865. Client cli("::1", PORT);
  2866. std::string body;
  2867. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2868. body.append(data, data_length);
  2869. return true;
  2870. });
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. EXPECT_EQ(StatusCode::Found_302, res->status);
  2873. EXPECT_EQ("___", body);
  2874. }
  2875. }
  2876. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2877. Server svr;
  2878. svr.Get("/foo", [](const Request &req, Response &res) {
  2879. auto a = req.params.find("a");
  2880. if (a != req.params.end()) {
  2881. res.set_content((*a).second, "text/plain");
  2882. res.status = StatusCode::OK_200;
  2883. } else {
  2884. res.status = StatusCode::BadRequest_400;
  2885. }
  2886. });
  2887. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2888. auto se = detail::scope_exit([&] {
  2889. svr.stop();
  2890. thread.join();
  2891. ASSERT_FALSE(svr.is_running());
  2892. });
  2893. svr.wait_until_ready();
  2894. {
  2895. Client cli(HOST, PORT);
  2896. cli.set_path_encode(false);
  2897. auto res = cli.Get("/foo?a=explicitly+encoded");
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. // This expects it back with a space, as the `+` won't have been
  2901. // url-encoded, and server-side the params get decoded turning `+`
  2902. // into spaces.
  2903. EXPECT_EQ("explicitly encoded", res->body);
  2904. }
  2905. }
  2906. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2907. // When path encoding is disabled the client must transmit the supplied
  2908. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2909. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2910. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2911. // than a space (0x20). Assert on the raw wire target to catch this.
  2912. Server svr;
  2913. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2914. svr.Get("/foo", [&](const Request &req, Response &res) {
  2915. EXPECT_EQ(expected_target, req.target);
  2916. res.status = StatusCode::OK_200;
  2917. });
  2918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2919. auto se = detail::scope_exit([&] {
  2920. svr.stop();
  2921. thread.join();
  2922. ASSERT_FALSE(svr.is_running());
  2923. });
  2924. svr.wait_until_ready();
  2925. {
  2926. Client cli(HOST, PORT);
  2927. cli.set_path_encode(false);
  2928. auto res = cli.Get(expected_target.c_str());
  2929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2930. EXPECT_EQ(StatusCode::OK_200, res->status);
  2931. }
  2932. }
  2933. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2934. // `open_stream()` used to skip the path encoding that the buffered send
  2935. // path applies, so the same `path` produced different bytes in the request
  2936. // line depending on which API was used. Assert the two agree.
  2937. Server svr;
  2938. std::string target;
  2939. svr.Get(".*", [&](const Request &req, Response &res) {
  2940. target = req.target;
  2941. res.status = StatusCode::OK_200;
  2942. });
  2943. auto port = svr.bind_to_any_port(HOST);
  2944. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2945. auto se = detail::scope_exit([&] {
  2946. svr.stop();
  2947. thread.join();
  2948. ASSERT_FALSE(svr.is_running());
  2949. });
  2950. svr.wait_until_ready();
  2951. struct {
  2952. const char *path;
  2953. const char *expected;
  2954. } cases[] = {
  2955. {"/a b?x=1", "/a%20b?x=1"},
  2956. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2957. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2958. };
  2959. for (const auto &c : cases) {
  2960. Client cli(HOST, port);
  2961. target.clear();
  2962. auto res = cli.Get(c.path);
  2963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2964. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2965. auto buffered_target = target;
  2966. target.clear();
  2967. auto handle = cli.open_stream("GET", c.path);
  2968. EXPECT_TRUE(handle.is_valid())
  2969. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2970. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2971. }
  2972. }
  2973. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2974. // The `set_path_encode(false)` contract — transmit the supplied target
  2975. // verbatim — must hold for the streaming API too.
  2976. Server svr;
  2977. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2978. std::string target;
  2979. svr.Get("/foo", [&](const Request &req, Response &res) {
  2980. target = req.target;
  2981. res.status = StatusCode::OK_200;
  2982. });
  2983. auto port = svr.bind_to_any_port(HOST);
  2984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. {
  2992. Client cli(HOST, port);
  2993. cli.set_path_encode(false);
  2994. auto handle = cli.open_stream("GET", expected_target);
  2995. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2996. EXPECT_EQ(expected_target, target);
  2997. }
  2998. }
  2999. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3000. // With path encoding enabled a CR/LF in the target is percent-encoded
  3001. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3002. // write_request_line still backstops `set_path_encode(false)`, which is
  3003. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3004. Server svr;
  3005. // Captured before routing: the decoded path contains a newline, which a
  3006. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3007. std::string target;
  3008. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3009. target = req.target;
  3010. res.status = StatusCode::OK_200;
  3011. return Server::HandlerResponse::Handled;
  3012. });
  3013. auto port = svr.bind_to_any_port(HOST);
  3014. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3015. auto se = detail::scope_exit([&] {
  3016. svr.stop();
  3017. thread.join();
  3018. ASSERT_FALSE(svr.is_running());
  3019. });
  3020. svr.wait_until_ready();
  3021. {
  3022. Client cli(HOST, port);
  3023. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3024. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3025. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3026. }
  3027. }
  3028. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3029. // Nothing may reach the wire: a raw CR/LF target would split the request
  3030. // line and inject headers.
  3031. Server svr;
  3032. // Pre-routing so that "not called" means nothing reached the server at all,
  3033. // rather than merely failing to match a handler pattern.
  3034. auto handler_called = false;
  3035. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3036. handler_called = true;
  3037. res.status = StatusCode::OK_200;
  3038. return Server::HandlerResponse::Handled;
  3039. });
  3040. auto port = svr.bind_to_any_port(HOST);
  3041. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. {
  3049. Client cli(HOST, port);
  3050. cli.set_path_encode(false);
  3051. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3052. EXPECT_FALSE(handle.is_valid());
  3053. EXPECT_EQ(Error::Write, handle.error);
  3054. EXPECT_FALSE(handler_called);
  3055. }
  3056. }
  3057. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3058. // Which of the two branches runs is decided by whether the query component
  3059. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3060. // an empty query and must still fall back to building one from
  3061. // `req.params`, while a non-empty query must win over `req.params`.
  3062. Server svr;
  3063. std::string target;
  3064. svr.Get("/foo", [&](const Request &req, Response &res) {
  3065. target = req.target;
  3066. res.status = StatusCode::OK_200;
  3067. });
  3068. auto port = svr.bind_to_any_port(HOST);
  3069. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3070. auto se = detail::scope_exit([&] {
  3071. svr.stop();
  3072. thread.join();
  3073. ASSERT_FALSE(svr.is_running());
  3074. });
  3075. svr.wait_until_ready();
  3076. {
  3077. // Trailing `?` -> empty query component -> `req.params` is used.
  3078. Client cli(HOST, port);
  3079. Request req;
  3080. req.method = "GET";
  3081. req.path = "/foo?";
  3082. req.params.emplace("a", "1");
  3083. target.clear();
  3084. auto res = cli.send(req);
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ("/foo?a=1", target);
  3087. }
  3088. {
  3089. // Non-empty query in `req.path` -> `req.params` is not appended.
  3090. Client cli(HOST, port);
  3091. Request req;
  3092. req.method = "GET";
  3093. req.path = "/foo?b=2";
  3094. req.params.emplace("a", "1");
  3095. target.clear();
  3096. auto res = cli.send(req);
  3097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3098. EXPECT_EQ("/foo?b=2", target);
  3099. }
  3100. }
  3101. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3102. Server svr;
  3103. svr.Get("/", [](const Request &req, Response &) {
  3104. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3105. });
  3106. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3107. auto se = detail::scope_exit([&] {
  3108. svr.stop();
  3109. thread.join();
  3110. ASSERT_FALSE(svr.is_running());
  3111. });
  3112. svr.wait_until_ready();
  3113. {
  3114. Client cli(HOST, PORT);
  3115. cli.set_path_encode(false);
  3116. auto res = cli.Get("/?something=%0A");
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. }
  3120. }
  3121. TEST(BindServerTest, BindDualStack) {
  3122. Server svr;
  3123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3124. res.set_content("Hello World!", "text/plain");
  3125. });
  3126. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3127. auto se = detail::scope_exit([&] {
  3128. svr.stop();
  3129. thread.join();
  3130. ASSERT_FALSE(svr.is_running());
  3131. });
  3132. svr.wait_until_ready();
  3133. {
  3134. Client cli("127.0.0.1", PORT);
  3135. auto res = cli.Get("/1");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::OK_200, res->status);
  3138. EXPECT_EQ("Hello World!", res->body);
  3139. }
  3140. {
  3141. Client cli("::1", PORT);
  3142. auto res = cli.Get("/1");
  3143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3144. EXPECT_EQ(StatusCode::OK_200, res->status);
  3145. EXPECT_EQ("Hello World!", res->body);
  3146. }
  3147. }
  3148. TEST(BindServerTest, BindAndListenSeparately) {
  3149. Server svr;
  3150. int port = svr.bind_to_any_port("0.0.0.0");
  3151. ASSERT_TRUE(svr.is_valid());
  3152. ASSERT_TRUE(port > 0);
  3153. svr.stop();
  3154. }
  3155. // Reports whether anything is still listening on a loopback port. A plain
  3156. // connect() is used instead of a Client request because a socket left bound by
  3157. // mistake accepts the connection into its backlog and never answers, which
  3158. // would hang the test instead of failing it.
  3159. static bool is_loopback_port_accepting(int port) {
  3160. sockaddr_in addr{};
  3161. addr.sin_family = AF_INET;
  3162. addr.sin_port = htons(static_cast<uint16_t>(port));
  3163. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3164. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3165. EXPECT_NE(sock, INVALID_SOCKET);
  3166. if (sock == INVALID_SOCKET) { return false; }
  3167. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3168. static_cast<socklen_t>(sizeof(addr)));
  3169. detail::close_socket(sock);
  3170. return ret == 0;
  3171. }
  3172. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3173. Server svr;
  3174. auto port = svr.bind_to_any_port("127.0.0.1");
  3175. ASSERT_TRUE(port > 0);
  3176. svr.stop();
  3177. // bind_to_any_port() already called listen(2), so until stop() closed the
  3178. // descriptor the port kept accepting connections into the backlog. ASSERT
  3179. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3180. // below blocks forever in the accept loop.
  3181. ASSERT_FALSE(is_loopback_port_accepting(port));
  3182. // Nothing is left to accept on, so listen_after_bind() must report failure
  3183. // instead of returning success without ever serving.
  3184. EXPECT_FALSE(svr.listen_after_bind());
  3185. // The failed listen marks the server decommissioned, so a waiter returns
  3186. // instead of spinning forever.
  3187. svr.wait_until_ready();
  3188. }
  3189. #ifdef CPPHTTPLIB_SSL_ENABLED
  3190. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3192. CLIENT_CA_CERT_DIR);
  3193. int port = svr.bind_to_any_port("0.0.0.0");
  3194. ASSERT_TRUE(svr.is_valid());
  3195. ASSERT_TRUE(port > 0);
  3196. svr.stop();
  3197. }
  3198. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3199. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3200. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3201. int port = svr.bind_to_any_port("0.0.0.0");
  3202. ASSERT_TRUE(svr.is_valid());
  3203. ASSERT_TRUE(port > 0);
  3204. svr.stop();
  3205. }
  3206. TEST(BindServerTest, UpdateCertsPem) {
  3207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3208. int port = svr.bind_to_any_port("0.0.0.0");
  3209. ASSERT_TRUE(svr.is_valid());
  3210. ASSERT_TRUE(port > 0);
  3211. // Read PEM files
  3212. std::string cert_pem, key_pem, ca_pem;
  3213. read_file(SERVER_CERT_FILE, cert_pem);
  3214. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3215. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3216. // Update server certificates using PEM API
  3217. ASSERT_TRUE(
  3218. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3219. ASSERT_TRUE(svr.is_valid());
  3220. svr.stop();
  3221. }
  3222. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3223. // Start server with client CA (enables client auth)
  3224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3225. ASSERT_TRUE(svr.is_valid());
  3226. bool handler_called = false;
  3227. svr.Get("/test", [&](const Request &req, Response &res) {
  3228. handler_called = true;
  3229. // Verify client certificate is present
  3230. auto cert = req.peer_cert();
  3231. EXPECT_TRUE(static_cast<bool>(cert));
  3232. res.set_content("ok", "text/plain");
  3233. });
  3234. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3235. auto se = detail::scope_exit([&] {
  3236. svr.stop();
  3237. t.join();
  3238. ASSERT_FALSE(svr.is_running());
  3239. });
  3240. svr.wait_until_ready();
  3241. // Read PEM files
  3242. std::string cert_pem, key_pem, ca_pem;
  3243. read_file(SERVER_CERT_FILE, cert_pem);
  3244. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3245. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3246. // Update server certificates and client CA using PEM API while server running
  3247. ASSERT_TRUE(
  3248. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3249. // Connect with client certificate
  3250. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3251. cli.enable_server_certificate_verification(false);
  3252. cli.set_connection_timeout(30);
  3253. auto res = cli.Get("/test");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. ASSERT_EQ(StatusCode::OK_200, res->status);
  3256. ASSERT_TRUE(handler_called);
  3257. EXPECT_EQ("ok", res->body);
  3258. }
  3259. #endif
  3260. TEST(ErrorHandlerTest, ContentLength) {
  3261. Server svr;
  3262. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3263. res.status = StatusCode::OK_200;
  3264. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3265. "text/html"); // <= Content-Length still 13
  3266. });
  3267. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3268. res.set_content("Hello World!\n", "text/plain");
  3269. res.status = 524;
  3270. });
  3271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3272. auto se = detail::scope_exit([&] {
  3273. svr.stop();
  3274. thread.join();
  3275. ASSERT_FALSE(svr.is_running());
  3276. });
  3277. svr.wait_until_ready();
  3278. {
  3279. Client cli(HOST, PORT);
  3280. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3286. }
  3287. }
  3288. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3289. TEST(ExceptionTest, WithoutExceptionHandler) {
  3290. Server svr;
  3291. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3292. throw std::runtime_error("exception...");
  3293. });
  3294. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3295. throw std::runtime_error("exception\r\n...");
  3296. });
  3297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3298. auto se = detail::scope_exit([&] {
  3299. svr.stop();
  3300. listen_thread.join();
  3301. ASSERT_FALSE(svr.is_running());
  3302. });
  3303. svr.wait_until_ready();
  3304. Client cli("localhost", PORT);
  3305. {
  3306. auto res = cli.Get("/exception");
  3307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3310. }
  3311. {
  3312. auto res = cli.Get("/unknown");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3315. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3316. }
  3317. }
  3318. TEST(ExceptionTest, WithExceptionHandler) {
  3319. Server svr;
  3320. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3321. std::exception_ptr ep) {
  3322. EXPECT_FALSE(ep == nullptr);
  3323. try {
  3324. std::rethrow_exception(ep);
  3325. } catch (std::exception &e) {
  3326. EXPECT_EQ("abc", std::string(e.what()));
  3327. } catch (...) {}
  3328. res.status = StatusCode::InternalServerError_500;
  3329. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3330. "text/html"); // <= Content-Length still 13 at this point
  3331. });
  3332. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3333. res.set_content("Hello World!\n", "text/plain");
  3334. throw std::runtime_error("abc");
  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. for (size_t i = 0; i < 10; i++) {
  3344. Client cli(HOST, PORT);
  3345. for (size_t j = 0; j < 100; j++) {
  3346. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3348. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3350. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3351. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3352. }
  3353. cli.set_keep_alive(true);
  3354. for (size_t j = 0; j < 100; j++) {
  3355. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3357. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3358. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3359. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3360. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3361. }
  3362. }
  3363. }
  3364. TEST(ExceptionTest, AndErrorHandler) {
  3365. Server svr;
  3366. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3367. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3368. });
  3369. svr.set_exception_handler(
  3370. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3371. EXPECT_FALSE(ep == nullptr);
  3372. try {
  3373. std::rethrow_exception(ep);
  3374. } catch (std::exception &e) {
  3375. res.set_content(e.what(), "text/html");
  3376. } catch (...) {}
  3377. res.status = StatusCode::InternalServerError_500;
  3378. });
  3379. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3380. throw std::runtime_error("EXCEPTION");
  3381. });
  3382. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3383. res.set_content("ERROR", "text/html");
  3384. res.status = StatusCode::InternalServerError_500;
  3385. });
  3386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. thread.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. Client cli(HOST, PORT);
  3394. {
  3395. auto res = cli.Get("/exception");
  3396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ("EXCEPTION", res->body);
  3399. }
  3400. {
  3401. auto res = cli.Get("/error");
  3402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3404. EXPECT_EQ("ERROR", res->body);
  3405. }
  3406. {
  3407. auto res = cli.Get("/invalid");
  3408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3409. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3410. EXPECT_EQ("NOT_FOUND", res->body);
  3411. }
  3412. }
  3413. #endif
  3414. TEST(NoContentTest, ContentLength) {
  3415. Server svr;
  3416. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3417. res.status = StatusCode::NoContent_204;
  3418. });
  3419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. {
  3427. Client cli(HOST, PORT);
  3428. auto res = cli.Get("/hi");
  3429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3430. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3431. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3432. }
  3433. }
  3434. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3435. #ifdef CPPHTTPLIB_SSL_ENABLED
  3436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3437. ASSERT_TRUE(svr.is_valid());
  3438. #else
  3439. Server svr;
  3440. #endif
  3441. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3442. if (req.path == "/routing_handler") {
  3443. res.set_header("PRE_ROUTING", "on");
  3444. res.set_content("Routing Handler", "text/plain");
  3445. return httplib::Server::HandlerResponse::Handled;
  3446. }
  3447. return httplib::Server::HandlerResponse::Unhandled;
  3448. });
  3449. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3450. res.set_content("Error", "text/html");
  3451. });
  3452. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3453. if (req.path == "/routing_handler") {
  3454. res.set_header("POST_ROUTING", "on");
  3455. }
  3456. });
  3457. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3458. res.set_content("Hello World!\n", "text/plain");
  3459. });
  3460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3461. auto se = detail::scope_exit([&] {
  3462. svr.stop();
  3463. thread.join();
  3464. ASSERT_FALSE(svr.is_running());
  3465. });
  3466. svr.wait_until_ready();
  3467. {
  3468. #ifdef CPPHTTPLIB_SSL_ENABLED
  3469. SSLClient cli(HOST, PORT);
  3470. cli.enable_server_certificate_verification(false);
  3471. #else
  3472. Client cli(HOST, PORT);
  3473. #endif
  3474. auto res = cli.Get("/routing_handler");
  3475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("Routing Handler", res->body);
  3478. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3479. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3480. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3481. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3482. }
  3483. {
  3484. #ifdef CPPHTTPLIB_SSL_ENABLED
  3485. SSLClient cli(HOST, PORT);
  3486. cli.enable_server_certificate_verification(false);
  3487. #else
  3488. Client cli(HOST, PORT);
  3489. #endif
  3490. auto res = cli.Get("/hi");
  3491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3492. EXPECT_EQ(StatusCode::OK_200, res->status);
  3493. EXPECT_EQ("Hello World!\n", res->body);
  3494. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3495. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3496. }
  3497. {
  3498. #ifdef CPPHTTPLIB_SSL_ENABLED
  3499. SSLClient cli(HOST, PORT);
  3500. cli.enable_server_certificate_verification(false);
  3501. #else
  3502. Client cli(HOST, PORT);
  3503. #endif
  3504. auto res = cli.Get("/aaa");
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3507. EXPECT_EQ("Error", res->body);
  3508. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3509. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3510. }
  3511. }
  3512. TEST(RequestHandlerTest, PreRequestHandler) {
  3513. auto route_path = "/user/:user";
  3514. Server svr;
  3515. svr.Get("/hi", [](const Request &, Response &res) {
  3516. res.set_content("hi", "text/plain");
  3517. });
  3518. svr.Get(route_path, [](const Request &req, Response &res) {
  3519. res.set_content(req.path_params.at("user"), "text/plain");
  3520. });
  3521. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3522. if (req.matched_route == route_path) {
  3523. auto user = req.path_params.at("user");
  3524. if (user != "john") {
  3525. res.status = StatusCode::Forbidden_403;
  3526. res.set_content("error", "text/html");
  3527. return Server::HandlerResponse::Handled;
  3528. }
  3529. }
  3530. return Server::HandlerResponse::Unhandled;
  3531. });
  3532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3533. auto se = detail::scope_exit([&] {
  3534. svr.stop();
  3535. thread.join();
  3536. ASSERT_FALSE(svr.is_running());
  3537. });
  3538. svr.wait_until_ready();
  3539. Client cli(HOST, PORT);
  3540. {
  3541. auto res = cli.Get("/hi");
  3542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3543. EXPECT_EQ(StatusCode::OK_200, res->status);
  3544. EXPECT_EQ("hi", res->body);
  3545. }
  3546. {
  3547. auto res = cli.Get("/user/john");
  3548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3549. EXPECT_EQ(StatusCode::OK_200, res->status);
  3550. EXPECT_EQ("john", res->body);
  3551. }
  3552. {
  3553. auto res = cli.Get("/user/invalid-user");
  3554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3555. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3556. EXPECT_EQ("error", res->body);
  3557. }
  3558. }
  3559. // The pre-request handler must run before the request body is read, so a
  3560. // rejected request never forces the server to buffer a (potentially large)
  3561. // body. Here the posted body is larger than the payload limit: if the body
  3562. // were read first the server would answer 413, but because the pre-request
  3563. // handler runs first it answers 403 and the body is never read.
  3564. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3565. Server svr;
  3566. svr.set_payload_max_length(8);
  3567. auto handler_ran = false;
  3568. svr.Post("/reject", [&](const Request &req, Response &res) {
  3569. handler_ran = true;
  3570. res.set_content(req.body, "text/plain");
  3571. });
  3572. svr.Post("/accept", [](const Request &req, Response &res) {
  3573. res.set_content(req.body, "text/plain");
  3574. });
  3575. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3576. if (req.matched_route == "/reject") {
  3577. res.status = StatusCode::Forbidden_403;
  3578. res.set_content("denied", "text/plain");
  3579. return Server::HandlerResponse::Handled;
  3580. }
  3581. return Server::HandlerResponse::Unhandled;
  3582. });
  3583. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3584. auto se = detail::scope_exit([&] {
  3585. svr.stop();
  3586. thread.join();
  3587. ASSERT_FALSE(svr.is_running());
  3588. });
  3589. svr.wait_until_ready();
  3590. Client cli(HOST, PORT);
  3591. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3592. // rejects with 403 before the body is read, so 413 is never reached.
  3593. {
  3594. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3596. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3597. EXPECT_EQ("denied", res->body);
  3598. EXPECT_FALSE(handler_ran);
  3599. }
  3600. // An approved route still reads the body and enforces the payload limit.
  3601. {
  3602. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3604. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3605. }
  3606. }
  3607. TEST(UserDataTest, BasicOperations) {
  3608. httplib::UserData ud;
  3609. // Initially empty
  3610. EXPECT_FALSE(ud.has("key"));
  3611. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3612. // set and get
  3613. ud.set("key", 42);
  3614. EXPECT_TRUE(ud.has("key"));
  3615. auto *p = ud.get<int>("key");
  3616. ASSERT_NE(nullptr, p);
  3617. EXPECT_EQ(42, *p);
  3618. // Type mismatch → nullptr
  3619. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3620. // Overwrite with different type
  3621. ud.set("key", std::string("hello"));
  3622. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3623. auto *s = ud.get<std::string>("key");
  3624. ASSERT_NE(nullptr, s);
  3625. EXPECT_EQ("hello", *s);
  3626. // erase
  3627. ud.erase("key");
  3628. EXPECT_FALSE(ud.has("key"));
  3629. // clear
  3630. ud.set("a", 1);
  3631. ud.set("b", 2);
  3632. ud.clear();
  3633. EXPECT_FALSE(ud.has("a"));
  3634. EXPECT_FALSE(ud.has("b"));
  3635. }
  3636. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3637. struct AuthCtx {
  3638. std::string user_id;
  3639. };
  3640. Server svr;
  3641. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3642. res.user_data.set("auth", AuthCtx{"alice"});
  3643. return Server::HandlerResponse::Unhandled;
  3644. });
  3645. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3646. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3647. ASSERT_NE(nullptr, ctx);
  3648. res.set_content("Hello " + ctx->user_id, "text/plain");
  3649. });
  3650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3651. auto se = detail::scope_exit([&] {
  3652. svr.stop();
  3653. thread.join();
  3654. ASSERT_FALSE(svr.is_running());
  3655. });
  3656. svr.wait_until_ready();
  3657. Client cli(HOST, PORT);
  3658. auto res = cli.Get("/me");
  3659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3660. EXPECT_EQ(StatusCode::OK_200, res->status);
  3661. EXPECT_EQ("Hello alice", res->body);
  3662. }
  3663. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3664. struct RoleCtx {
  3665. std::string role;
  3666. };
  3667. Server svr;
  3668. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3669. res.user_data.set("role", RoleCtx{"admin"});
  3670. return Server::HandlerResponse::Unhandled;
  3671. });
  3672. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3673. auto *ctx = res.user_data.get<RoleCtx>("role");
  3674. ASSERT_NE(nullptr, ctx);
  3675. res.set_content(ctx->role, "text/plain");
  3676. });
  3677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3678. auto se = detail::scope_exit([&] {
  3679. svr.stop();
  3680. thread.join();
  3681. ASSERT_FALSE(svr.is_running());
  3682. });
  3683. svr.wait_until_ready();
  3684. Client cli(HOST, PORT);
  3685. auto res = cli.Get("/role");
  3686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3687. EXPECT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ("admin", res->body);
  3689. }
  3690. TEST(InvalidFormatTest, StatusCode) {
  3691. Server svr;
  3692. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3693. res.set_content("Hello World!\n", "text/plain");
  3694. res.status = 9999; // Status should be a three-digit code...
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. {
  3704. Client cli(HOST, PORT);
  3705. auto res = cli.Get("/hi");
  3706. ASSERT_FALSE(res);
  3707. }
  3708. }
  3709. TEST(URLFragmentTest, WithFragment) {
  3710. Server svr;
  3711. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3712. EXPECT_TRUE(req.target == "/hi");
  3713. });
  3714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. {
  3722. Client cli(HOST, PORT);
  3723. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3724. EXPECT_TRUE(res);
  3725. EXPECT_EQ(StatusCode::OK_200, res->status);
  3726. res = cli.Get("/hi%23key1=val1=key2=val2");
  3727. EXPECT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. }
  3731. TEST(HeaderWriter, SetHeaderWriter) {
  3732. Server svr;
  3733. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3734. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3735. return detail::write_headers(strm, hdrs);
  3736. });
  3737. svr.Get("/hi", [](const Request &req, Response &res) {
  3738. auto it = req.headers.find("CustomClientHeader");
  3739. EXPECT_TRUE(it != req.headers.end());
  3740. EXPECT_EQ(it->second, "CustomClientValue");
  3741. res.set_content("Hello World!\n", "text/plain");
  3742. });
  3743. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3744. auto se = detail::scope_exit([&] {
  3745. svr.stop();
  3746. thread.join();
  3747. ASSERT_FALSE(svr.is_running());
  3748. });
  3749. svr.wait_until_ready();
  3750. {
  3751. Client cli(HOST, PORT);
  3752. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3753. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3754. return detail::write_headers(strm, hdrs);
  3755. });
  3756. auto res = cli.Get("/hi");
  3757. EXPECT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. auto it = res->headers.find("CustomServerHeader");
  3760. EXPECT_TRUE(it != res->headers.end());
  3761. EXPECT_EQ(it->second, "CustomServerValue");
  3762. }
  3763. }
  3764. class ServerTest : public ::testing::Test {
  3765. protected:
  3766. ServerTest()
  3767. : cli_(HOST, PORT)
  3768. #ifdef CPPHTTPLIB_SSL_ENABLED
  3769. ,
  3770. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3771. #endif
  3772. {
  3773. #ifdef CPPHTTPLIB_SSL_ENABLED
  3774. cli_.enable_server_certificate_verification(false);
  3775. #endif
  3776. // Allow LARGE_DATA (100MB) responses
  3777. cli_.set_payload_max_length(200 * 1024 * 1024);
  3778. }
  3779. virtual void SetUp() {
  3780. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3781. svr_.set_payload_max_length(200 * 1024 * 1024);
  3782. svr_.set_mount_point("/", "./www");
  3783. svr_.set_mount_point("/mount", "./www2");
  3784. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3785. svr_.Get("/hi",
  3786. [&](const Request & /*req*/, Response &res) {
  3787. res.set_content("Hello World!", "text/plain");
  3788. })
  3789. .Get("/file_content",
  3790. [&](const Request & /*req*/, Response &res) {
  3791. res.set_file_content("./www/dir/test.html");
  3792. })
  3793. .Get("/file_content_with_content_type",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. res.set_file_content("./www/file", "text/plain");
  3796. })
  3797. .Get("/invalid_file_content",
  3798. [&](const Request & /*req*/, Response &res) {
  3799. res.set_file_content("./www/dir/invalid_file_path");
  3800. })
  3801. .Get("/http_response_splitting",
  3802. [&](const Request & /*req*/, Response &res) {
  3803. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3804. EXPECT_EQ(0U, res.headers.size());
  3805. EXPECT_FALSE(res.has_header("a"));
  3806. res.set_header("a", "1\nSet-Cookie: a=1");
  3807. EXPECT_EQ(0U, res.headers.size());
  3808. EXPECT_FALSE(res.has_header("a"));
  3809. res.set_header("a", "1\rSet-Cookie: a=1");
  3810. EXPECT_EQ(0U, res.headers.size());
  3811. EXPECT_FALSE(res.has_header("a"));
  3812. res.set_header("a\r\nb", "0");
  3813. EXPECT_EQ(0U, res.headers.size());
  3814. EXPECT_FALSE(res.has_header("a"));
  3815. res.set_header("a\rb", "0");
  3816. EXPECT_EQ(0U, res.headers.size());
  3817. EXPECT_FALSE(res.has_header("a"));
  3818. res.set_header("a\nb", "0");
  3819. EXPECT_EQ(0U, res.headers.size());
  3820. EXPECT_FALSE(res.has_header("a"));
  3821. res.set_redirect("1\r\nSet-Cookie: a=1");
  3822. EXPECT_EQ(0U, res.headers.size());
  3823. EXPECT_FALSE(res.has_header("Location"));
  3824. })
  3825. .Get("/slow",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. std::this_thread::sleep_for(std::chrono::seconds(4));
  3828. res.set_content("slow", "text/plain");
  3829. })
  3830. #if 0
  3831. .Post("/slowpost",
  3832. [&](const Request & /*req*/, Response &res) {
  3833. std::this_thread::sleep_for(std::chrono::seconds(2));
  3834. res.set_content("slow", "text/plain");
  3835. })
  3836. #endif
  3837. .Get("/remote_addr",
  3838. [&](const Request &req, Response &res) {
  3839. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3840. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3841. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3842. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3843. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3844. #endif
  3845. res.set_content(req.remote_addr, "text/plain");
  3846. })
  3847. .Get("/local_addr",
  3848. [&](const Request &req, Response &res) {
  3849. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3850. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3851. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3852. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3853. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3854. #endif
  3855. auto local_addr = req.local_addr;
  3856. auto local_port = std::to_string(req.local_port);
  3857. res.set_content(local_addr.append(":").append(local_port),
  3858. "text/plain");
  3859. })
  3860. .Get("/endwith%",
  3861. [&](const Request & /*req*/, Response &res) {
  3862. res.set_content("Hello World!", "text/plain");
  3863. })
  3864. .Get("/a\\+\\+b",
  3865. [&](const Request &req, Response &res) {
  3866. ASSERT_TRUE(req.has_param("a +b"));
  3867. auto val = req.get_param_value("a +b");
  3868. res.set_content(val, "text/plain");
  3869. })
  3870. .Get("/", [&](const Request & /*req*/,
  3871. Response &res) { res.set_redirect("/hi"); })
  3872. .Post("/1",
  3873. [](const Request & /*req*/, Response &res) {
  3874. res.set_redirect("/2", StatusCode::SeeOther_303);
  3875. })
  3876. .Get("/2",
  3877. [](const Request & /*req*/, Response &res) {
  3878. res.set_content("redirected.", "text/plain");
  3879. res.status = StatusCode::OK_200;
  3880. })
  3881. .Post("/person",
  3882. [&](const Request &req, Response &res) {
  3883. if (req.has_param("name") && req.has_param("note")) {
  3884. persons_[req.get_param_value("name")] =
  3885. req.get_param_value("note");
  3886. } else {
  3887. res.status = StatusCode::BadRequest_400;
  3888. }
  3889. })
  3890. .Put("/person",
  3891. [&](const Request &req, Response &res) {
  3892. if (req.has_param("name") && req.has_param("note")) {
  3893. persons_[req.get_param_value("name")] =
  3894. req.get_param_value("note");
  3895. } else {
  3896. res.status = StatusCode::BadRequest_400;
  3897. }
  3898. })
  3899. .Get("/person/(.*)",
  3900. [&](const Request &req, Response &res) {
  3901. string name = req.matches[1];
  3902. if (persons_.find(name) != persons_.end()) {
  3903. auto note = persons_[name];
  3904. res.set_content(note, "text/plain");
  3905. } else {
  3906. res.status = StatusCode::NotFound_404;
  3907. }
  3908. })
  3909. .Delete("/person",
  3910. [&](const Request &req, Response &res) {
  3911. if (req.has_param("name")) {
  3912. string name = req.get_param_value("name");
  3913. if (persons_.find(name) != persons_.end()) {
  3914. persons_.erase(name);
  3915. res.set_content("DELETED", "text/plain");
  3916. } else {
  3917. res.status = StatusCode::NotFound_404;
  3918. }
  3919. } else {
  3920. res.status = StatusCode::BadRequest_400;
  3921. }
  3922. })
  3923. .Post("/x-www-form-urlencoded-json",
  3924. [&](const Request &req, Response &res) {
  3925. auto json = req.get_param_value("json");
  3926. ASSERT_EQ(JSON_DATA, json);
  3927. res.set_content(json, "appliation/json");
  3928. res.status = StatusCode::OK_200;
  3929. })
  3930. .Get("/streamed-chunked",
  3931. [&](const Request & /*req*/, Response &res) {
  3932. res.set_chunked_content_provider(
  3933. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3934. sink.os << "123";
  3935. sink.os << "456";
  3936. sink.os << "789";
  3937. sink.done();
  3938. return true;
  3939. });
  3940. })
  3941. .Get("/streamed-chunked-with-prohibited-trailer",
  3942. [&](const Request & /*req*/, Response &res) {
  3943. auto i = new int(0);
  3944. // Declare both a prohibited trailer (Content-Length) and an
  3945. // allowed one
  3946. res.set_header("Trailer", "Content-Length, X-Allowed");
  3947. res.set_chunked_content_provider(
  3948. "text/plain",
  3949. [i](size_t /*offset*/, DataSink &sink) {
  3950. switch (*i) {
  3951. case 0: sink.os << "123"; break;
  3952. case 1: sink.os << "456"; break;
  3953. case 2: sink.os << "789"; break;
  3954. case 3: {
  3955. sink.done_with_trailer(
  3956. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3957. } break;
  3958. }
  3959. (*i)++;
  3960. return true;
  3961. },
  3962. [i](bool success) {
  3963. EXPECT_TRUE(success);
  3964. delete i;
  3965. });
  3966. })
  3967. .Get("/streamed-chunked2",
  3968. [&](const Request & /*req*/, Response &res) {
  3969. auto i = new int(0);
  3970. res.set_chunked_content_provider(
  3971. "text/plain",
  3972. [i](size_t /*offset*/, DataSink &sink) {
  3973. switch (*i) {
  3974. case 0: sink.os << "123"; break;
  3975. case 1: sink.os << "456"; break;
  3976. case 2: sink.os << "789"; break;
  3977. case 3: sink.done(); break;
  3978. }
  3979. (*i)++;
  3980. return true;
  3981. },
  3982. [i](bool success) {
  3983. EXPECT_TRUE(success);
  3984. delete i;
  3985. });
  3986. })
  3987. .Get("/streamed-chunked-with-trailer",
  3988. [&](const Request & /*req*/, Response &res) {
  3989. auto i = new int(0);
  3990. res.set_header("Trailer", "Dummy1, Dummy2");
  3991. res.set_chunked_content_provider(
  3992. "text/plain",
  3993. [i](size_t /*offset*/, DataSink &sink) {
  3994. switch (*i) {
  3995. case 0: sink.os << "123"; break;
  3996. case 1: sink.os << "456"; break;
  3997. case 2: sink.os << "789"; break;
  3998. case 3: {
  3999. sink.done_with_trailer(
  4000. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4001. } break;
  4002. }
  4003. (*i)++;
  4004. return true;
  4005. },
  4006. [i](bool success) {
  4007. EXPECT_TRUE(success);
  4008. delete i;
  4009. });
  4010. })
  4011. .Get("/streamed",
  4012. [&](const Request & /*req*/, Response &res) {
  4013. res.set_content_provider(
  4014. 6, "text/plain",
  4015. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4016. sink.os << (offset < 3 ? "a" : "b");
  4017. return true;
  4018. });
  4019. })
  4020. .Get("/streamed-without-length",
  4021. [&](const Request & /*req*/, Response &res) {
  4022. auto data = new std::string("abcdefg");
  4023. res.set_content_provider(
  4024. "text/plain",
  4025. [data](size_t offset, DataSink &sink) {
  4026. if (offset < data->size()) {
  4027. sink.os << data->substr(offset);
  4028. }
  4029. sink.done();
  4030. return true;
  4031. },
  4032. [data](bool success) {
  4033. EXPECT_TRUE(success);
  4034. delete data;
  4035. });
  4036. })
  4037. .Get("/streamed-with-range",
  4038. [&](const Request &req, Response &res) {
  4039. auto data = new std::string("abcdefg");
  4040. // An explicit status keeps the server from picking the 206 it
  4041. // would otherwise choose for a ranged request, so the response
  4042. // is not a partial representation.
  4043. auto status = req.get_param_value("status");
  4044. if (status == "200") {
  4045. res.status = StatusCode::OK_200;
  4046. } else if (status == "403") {
  4047. res.status = StatusCode::Forbidden_403;
  4048. }
  4049. res.set_content_provider(
  4050. data->size(), "text/plain",
  4051. [data](size_t offset, size_t length, DataSink &sink) {
  4052. size_t DATA_CHUNK_SIZE = 4;
  4053. const auto &d = *data;
  4054. auto out_len =
  4055. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4056. auto ret =
  4057. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4058. EXPECT_TRUE(ret);
  4059. return true;
  4060. },
  4061. [data, &req](bool success) {
  4062. EXPECT_EQ(success, !req.has_param("error"));
  4063. delete data;
  4064. });
  4065. })
  4066. .Get("/streamed-cancel",
  4067. [&](const Request & /*req*/, Response &res) {
  4068. res.set_content_provider(
  4069. size_t(-1), "text/plain",
  4070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4071. sink.os << "data_chunk";
  4072. return true;
  4073. });
  4074. })
  4075. .Get("/regex-with-delimiter",
  4076. [&](const Request &req, Response & /*res*/) {
  4077. ASSERT_TRUE(req.has_param("key"));
  4078. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4079. })
  4080. .Get("/with-range",
  4081. [&](const Request & /*req*/, Response &res) {
  4082. res.set_content("abcdefg", "text/plain");
  4083. })
  4084. .Get("/test-start-time",
  4085. [&](const Request &req, Response & /*res*/) {
  4086. EXPECT_NE(req.start_time_,
  4087. std::chrono::steady_clock::time_point::min());
  4088. })
  4089. .Get("/with-range-customized-response",
  4090. [&](const Request & /*req*/, Response &res) {
  4091. res.status = StatusCode::BadRequest_400;
  4092. res.set_content(JSON_DATA, "application/json");
  4093. })
  4094. .Post("/chunked",
  4095. [&](const Request &req, Response & /*res*/) {
  4096. EXPECT_EQ(req.body, "dechunked post body");
  4097. })
  4098. .Post("/large-chunked",
  4099. [&](const Request &req, Response & /*res*/) {
  4100. std::string expected(6 * 30 * 1024u, 'a');
  4101. EXPECT_EQ(req.body, expected);
  4102. })
  4103. .Post("/multipart",
  4104. [&](const Request &req, Response & /*res*/) {
  4105. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4106. req.form.get_field_count("text2") +
  4107. req.form.get_field_count("file3") +
  4108. req.form.get_field_count("file4"));
  4109. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4110. req.form.get_file_count("file2"));
  4111. ASSERT_TRUE(!req.form.has_file("???"));
  4112. ASSERT_TRUE(!req.form.has_field("???"));
  4113. ASSERT_TRUE(req.body.empty());
  4114. {
  4115. const auto &text = req.form.get_field("text1");
  4116. EXPECT_EQ("text default", text);
  4117. }
  4118. {
  4119. const auto &text = req.form.get_field("text2");
  4120. EXPECT_EQ("aωb", text);
  4121. }
  4122. {
  4123. const auto &file = req.form.get_file("file1");
  4124. EXPECT_EQ("hello.txt", file.filename);
  4125. EXPECT_EQ("text/plain", file.content_type);
  4126. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4127. }
  4128. {
  4129. const auto &file = req.form.get_file("file2");
  4130. EXPECT_EQ("world.json", file.filename);
  4131. EXPECT_EQ("application/json", file.content_type);
  4132. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4133. }
  4134. {
  4135. const auto &text = req.form.get_field("file3");
  4136. EXPECT_EQ(0u, text.size());
  4137. }
  4138. {
  4139. const auto &text = req.form.get_field("file4");
  4140. EXPECT_EQ(0u, text.size());
  4141. }
  4142. })
  4143. .Post("/multipart/multi_file_values",
  4144. [&](const Request &req, Response & /*res*/) {
  4145. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4146. req.form.get_field_count("multi_text1"));
  4147. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4148. ASSERT_TRUE(!req.form.has_file("???"));
  4149. ASSERT_TRUE(!req.form.has_field("???"));
  4150. ASSERT_TRUE(req.body.empty());
  4151. {
  4152. const auto &text = req.form.get_field("text");
  4153. EXPECT_EQ("default text", text);
  4154. }
  4155. {
  4156. const auto &text1_values = req.form.get_fields("multi_text1");
  4157. EXPECT_EQ(2u, text1_values.size());
  4158. EXPECT_EQ("aaaaa", text1_values[0]);
  4159. EXPECT_EQ("bbbbb", text1_values[1]);
  4160. }
  4161. {
  4162. const auto &file1_values = req.form.get_files("multi_file1");
  4163. EXPECT_EQ(2u, file1_values.size());
  4164. auto file1 = file1_values[0];
  4165. EXPECT_EQ(file1.filename, "hello.txt");
  4166. EXPECT_EQ(file1.content_type, "text/plain");
  4167. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4168. auto file2 = file1_values[1];
  4169. EXPECT_EQ(file2.filename, "world.json");
  4170. EXPECT_EQ(file2.content_type, "application/json");
  4171. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4172. }
  4173. })
  4174. .Post("/empty",
  4175. [&](const Request &req, Response &res) {
  4176. EXPECT_EQ(req.body, "");
  4177. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4178. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4179. res.set_content("empty", "text/plain");
  4180. })
  4181. .Post("/empty-no-content-type",
  4182. [&](const Request &req, Response &res) {
  4183. EXPECT_EQ(req.body, "");
  4184. EXPECT_FALSE(req.has_header("Content-Type"));
  4185. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4186. res.set_content("empty-no-content-type", "text/plain");
  4187. })
  4188. .Post("/path-only",
  4189. [&](const Request &req, Response &res) {
  4190. EXPECT_EQ(req.body, "");
  4191. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4192. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4193. res.set_content("path-only", "text/plain");
  4194. })
  4195. .Post("/path-headers-only",
  4196. [&](const Request &req, Response &res) {
  4197. EXPECT_EQ(req.body, "");
  4198. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4199. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4200. EXPECT_EQ("world", req.get_header_value("hello"));
  4201. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4202. res.set_content("path-headers-only", "text/plain");
  4203. })
  4204. .Post("/post-large",
  4205. [&](const Request &req, Response &res) {
  4206. EXPECT_EQ(req.body, LARGE_DATA);
  4207. res.set_content(req.body, "text/plain");
  4208. })
  4209. .Post("/post-loopback",
  4210. [&](const Request &, Response &res,
  4211. ContentReader const &content_reader) {
  4212. std::string body;
  4213. content_reader([&](const char *data, size_t data_length) {
  4214. body.append(data, data_length);
  4215. return true;
  4216. });
  4217. res.set_content(body, "text/plain");
  4218. })
  4219. .Put("/put-loopback",
  4220. [&](const Request &, Response &res,
  4221. ContentReader const &content_reader) {
  4222. std::string body;
  4223. content_reader([&](const char *data, size_t data_length) {
  4224. body.append(data, data_length);
  4225. return true;
  4226. });
  4227. res.set_content(body, "text/plain");
  4228. })
  4229. .Patch("/patch-loopback",
  4230. [&](const Request &, Response &res,
  4231. ContentReader const &content_reader) {
  4232. std::string body;
  4233. content_reader([&](const char *data, size_t data_length) {
  4234. body.append(data, data_length);
  4235. return true;
  4236. });
  4237. res.set_content(body, "text/plain");
  4238. })
  4239. .Put("/empty-no-content-type",
  4240. [&](const Request &req, Response &res) {
  4241. EXPECT_EQ(req.body, "");
  4242. EXPECT_FALSE(req.has_header("Content-Type"));
  4243. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4244. res.set_content("empty-no-content-type", "text/plain");
  4245. })
  4246. .Put("/put",
  4247. [&](const Request &req, Response &res) {
  4248. EXPECT_EQ(req.body, "PUT");
  4249. res.set_content(req.body, "text/plain");
  4250. })
  4251. .Put("/put-large",
  4252. [&](const Request &req, Response &res) {
  4253. EXPECT_EQ(req.body, LARGE_DATA);
  4254. res.set_content(req.body, "text/plain");
  4255. })
  4256. .Patch("/patch",
  4257. [&](const Request &req, Response &res) {
  4258. EXPECT_EQ(req.body, "PATCH");
  4259. res.set_content(req.body, "text/plain");
  4260. })
  4261. .Delete("/delete",
  4262. [&](const Request & /*req*/, Response &res) {
  4263. res.set_content("DELETE", "text/plain");
  4264. })
  4265. .Delete("/delete-body",
  4266. [&](const Request &req, Response &res) {
  4267. EXPECT_EQ(req.body, "content");
  4268. res.set_content(req.body, "text/plain");
  4269. })
  4270. .Options(R"(\*)",
  4271. [&](const Request & /*req*/, Response &res) {
  4272. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4273. })
  4274. .Get("/request-target",
  4275. [&](const Request &req, Response & /*res*/) {
  4276. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4277. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4278. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4279. })
  4280. .Get("/long-query-value",
  4281. [&](const Request &req, Response & /*res*/) {
  4282. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4283. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4284. })
  4285. .Get("/too-long-query-value",
  4286. [&](const Request &req, Response & /*res*/) {
  4287. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4288. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4289. })
  4290. .Get("/array-param",
  4291. [&](const Request &req, Response & /*res*/) {
  4292. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4293. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4294. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4295. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4296. })
  4297. .Get("/array-param-values",
  4298. [&](const Request &req, Response & /*res*/) {
  4299. auto values = req.get_param_values("array");
  4300. EXPECT_EQ(3u, values.size());
  4301. EXPECT_EQ("value1", values[0]);
  4302. EXPECT_EQ("value2", values[1]);
  4303. EXPECT_EQ("value3", values[2]);
  4304. auto empty = req.get_param_values("nonexistent");
  4305. EXPECT_TRUE(empty.empty());
  4306. })
  4307. .Post("/validate-no-multiple-headers",
  4308. [&](const Request &req, Response & /*res*/) {
  4309. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4310. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4311. })
  4312. .Post("/content_receiver",
  4313. [&](const Request &req, Response &res,
  4314. const ContentReader &content_reader) {
  4315. if (req.is_multipart_form_data()) {
  4316. std::vector<FormData> items;
  4317. content_reader(
  4318. [&](const FormData &file) {
  4319. items.push_back(file);
  4320. return true;
  4321. },
  4322. [&](const char *data, size_t data_length) {
  4323. items.back().content.append(data, data_length);
  4324. return true;
  4325. });
  4326. EXPECT_EQ(5u, items.size());
  4327. {
  4328. const auto &file = get_file_value(items, "text1");
  4329. EXPECT_TRUE(file.filename.empty());
  4330. EXPECT_EQ("text default", file.content);
  4331. }
  4332. {
  4333. const auto &file = get_file_value(items, "text2");
  4334. EXPECT_TRUE(file.filename.empty());
  4335. EXPECT_EQ("aωb", file.content);
  4336. }
  4337. {
  4338. const auto &file = get_file_value(items, "file1");
  4339. EXPECT_EQ("hello.txt", file.filename);
  4340. EXPECT_EQ("text/plain", file.content_type);
  4341. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4342. }
  4343. {
  4344. const auto &file = get_file_value(items, "file2");
  4345. EXPECT_EQ("world.json", file.filename);
  4346. EXPECT_EQ("application/json", file.content_type);
  4347. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4348. }
  4349. {
  4350. const auto &file = get_file_value(items, "file3");
  4351. EXPECT_TRUE(file.filename.empty());
  4352. EXPECT_EQ("application/octet-stream", file.content_type);
  4353. EXPECT_EQ(0u, file.content.size());
  4354. }
  4355. } else {
  4356. std::string body;
  4357. content_reader([&](const char *data, size_t data_length) {
  4358. EXPECT_EQ(7U, data_length);
  4359. body.append(data, data_length);
  4360. return true;
  4361. });
  4362. EXPECT_EQ(body, "content");
  4363. res.set_content(body, "text/plain");
  4364. }
  4365. })
  4366. .Put("/content_receiver",
  4367. [&](const Request & /*req*/, Response &res,
  4368. const ContentReader &content_reader) {
  4369. std::string body;
  4370. content_reader([&](const char *data, size_t data_length) {
  4371. body.append(data, data_length);
  4372. return true;
  4373. });
  4374. EXPECT_EQ(body, "content");
  4375. res.set_content(body, "text/plain");
  4376. })
  4377. .Patch("/content_receiver",
  4378. [&](const Request & /*req*/, Response &res,
  4379. const ContentReader &content_reader) {
  4380. std::string body;
  4381. content_reader([&](const char *data, size_t data_length) {
  4382. body.append(data, data_length);
  4383. return true;
  4384. });
  4385. EXPECT_EQ(body, "content");
  4386. res.set_content(body, "text/plain");
  4387. })
  4388. .Post("/query-string-and-body",
  4389. [&](const Request &req, Response & /*res*/) {
  4390. ASSERT_TRUE(req.has_param("key"));
  4391. EXPECT_EQ(req.get_param_value("key"), "value");
  4392. EXPECT_EQ(req.body, "content");
  4393. })
  4394. .Get("/last-request",
  4395. [&](const Request &req, Response & /*res*/) {
  4396. EXPECT_EQ("close", req.get_header_value("Connection"));
  4397. })
  4398. .Get(R"(/redirect/(\d+))",
  4399. [&](const Request &req, Response &res) {
  4400. auto num = std::stoi(req.matches[1]) + 1;
  4401. std::string url = "/redirect/" + std::to_string(num);
  4402. res.set_redirect(url);
  4403. })
  4404. .Post("/binary",
  4405. [&](const Request &req, Response &res) {
  4406. EXPECT_EQ(4U, req.body.size());
  4407. EXPECT_EQ("application/octet-stream",
  4408. req.get_header_value("Content-Type"));
  4409. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4410. res.set_content(req.body, "application/octet-stream");
  4411. })
  4412. .Put("/binary",
  4413. [&](const Request &req, Response &res) {
  4414. EXPECT_EQ(4U, req.body.size());
  4415. EXPECT_EQ("application/octet-stream",
  4416. req.get_header_value("Content-Type"));
  4417. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4418. res.set_content(req.body, "application/octet-stream");
  4419. })
  4420. .Patch("/binary",
  4421. [&](const Request &req, Response &res) {
  4422. EXPECT_EQ(4U, req.body.size());
  4423. EXPECT_EQ("application/octet-stream",
  4424. req.get_header_value("Content-Type"));
  4425. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4426. res.set_content(req.body, "application/octet-stream");
  4427. })
  4428. .Delete("/binary",
  4429. [&](const Request &req, Response &res) {
  4430. EXPECT_EQ(4U, req.body.size());
  4431. EXPECT_EQ("application/octet-stream",
  4432. req.get_header_value("Content-Type"));
  4433. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4434. res.set_content(req.body, "application/octet-stream");
  4435. })
  4436. .Get("/issue1772",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. res.status = 401;
  4439. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4440. })
  4441. .Delete("/issue609",
  4442. [](const httplib::Request &, httplib::Response &res,
  4443. const httplib::ContentReader &) {
  4444. res.set_content("ok", "text/plain");
  4445. })
  4446. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4447. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4448. .Get("/compress",
  4449. [&](const Request & /*req*/, Response &res) {
  4450. res.set_content(
  4451. "12345678901234567890123456789012345678901234567890123456789"
  4452. "01234567890123456789012345678901234567890",
  4453. "text/plain");
  4454. })
  4455. .Get("/compress-with-charset",
  4456. [&](const Request & /*req*/, Response &res) {
  4457. res.set_content(
  4458. "12345678901234567890123456789012345678901234567890123456789"
  4459. "01234567890123456789012345678901234567890",
  4460. "application/json; charset=utf-8");
  4461. })
  4462. .Get("/nocompress",
  4463. [&](const Request & /*req*/, Response &res) {
  4464. res.set_content(
  4465. "12345678901234567890123456789012345678901234567890123456789"
  4466. "01234567890123456789012345678901234567890",
  4467. "application/octet-stream");
  4468. })
  4469. .Post("/compress-multipart",
  4470. [&](const Request &req, Response & /*res*/) {
  4471. EXPECT_EQ(2u, req.form.fields.size());
  4472. ASSERT_TRUE(!req.form.has_field("???"));
  4473. {
  4474. const auto &text = req.form.get_field("key1");
  4475. EXPECT_EQ("test", text);
  4476. }
  4477. {
  4478. const auto &text = req.form.get_field("key2");
  4479. EXPECT_EQ("--abcdefg123", text);
  4480. }
  4481. })
  4482. #endif
  4483. ;
  4484. persons_["john"] = "programmer";
  4485. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4486. svr_.wait_until_ready();
  4487. }
  4488. virtual void TearDown() {
  4489. svr_.stop();
  4490. if (!request_threads_.empty()) {
  4491. std::this_thread::sleep_for(std::chrono::seconds(1));
  4492. for (auto &t : request_threads_) {
  4493. t.join();
  4494. }
  4495. }
  4496. t_.join();
  4497. }
  4498. map<string, string> persons_;
  4499. #ifdef CPPHTTPLIB_SSL_ENABLED
  4500. SSLClient cli_;
  4501. SSLServer svr_;
  4502. #else
  4503. Client cli_;
  4504. Server svr_;
  4505. #endif
  4506. thread t_;
  4507. std::vector<thread> request_threads_;
  4508. };
  4509. TEST_F(ServerTest, GetMethod200) {
  4510. auto res = cli_.Get("/hi");
  4511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4512. EXPECT_EQ("HTTP/1.1", res->version);
  4513. EXPECT_EQ(StatusCode::OK_200, res->status);
  4514. EXPECT_EQ("OK", res->reason);
  4515. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4516. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4517. EXPECT_EQ("Hello World!", res->body);
  4518. }
  4519. TEST_F(ServerTest, GetEmptyFile) {
  4520. auto res = cli_.Get("/empty_file");
  4521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4524. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4525. EXPECT_EQ("", res->body);
  4526. }
  4527. TEST_F(ServerTest, GetFileContent) {
  4528. auto res = cli_.Get("/file_content");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4532. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4533. EXPECT_EQ("test.html", res->body);
  4534. }
  4535. TEST_F(ServerTest, GetFileContentWithRange) {
  4536. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4539. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4540. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4541. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4542. EXPECT_EQ("est", res->body);
  4543. }
  4544. TEST_F(ServerTest, GetFileContentWithContentType) {
  4545. auto res = cli_.Get("/file_content_with_content_type");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4549. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4550. EXPECT_EQ("file\n", res->body);
  4551. }
  4552. TEST_F(ServerTest, GetInvalidFileContent) {
  4553. auto res = cli_.Get("/invalid_file_content");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4556. }
  4557. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4558. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4560. EXPECT_EQ("HTTP/1.1", res->version);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4563. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4564. EXPECT_EQ("Hello World!", res->body);
  4565. }
  4566. TEST_F(ServerTest, GetMethod302) {
  4567. auto res = cli_.Get("/");
  4568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4569. EXPECT_EQ(StatusCode::Found_302, res->status);
  4570. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4571. }
  4572. TEST_F(ServerTest, GetMethod302Redirect) {
  4573. cli_.set_follow_location(true);
  4574. auto res = cli_.Get("/");
  4575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ("Hello World!", res->body);
  4578. EXPECT_EQ("/hi", res->location);
  4579. }
  4580. TEST_F(ServerTest, GetMethod404) {
  4581. auto res = cli_.Get("/invalid");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4584. }
  4585. TEST_F(ServerTest, HeadMethod200) {
  4586. auto res = cli_.Head("/hi");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4590. EXPECT_TRUE(res->body.empty());
  4591. }
  4592. TEST_F(ServerTest, HeadMethod200Static) {
  4593. auto res = cli_.Head("/mount/dir/index.html");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4597. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4598. EXPECT_TRUE(res->body.empty());
  4599. }
  4600. TEST_F(ServerTest, HeadMethod404) {
  4601. auto res = cli_.Head("/invalid");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4604. EXPECT_TRUE(res->body.empty());
  4605. }
  4606. TEST_F(ServerTest, GetMethodPersonJohn) {
  4607. auto res = cli_.Get("/person/john");
  4608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4611. EXPECT_EQ("programmer", res->body);
  4612. }
  4613. TEST_F(ServerTest, PostMethod1) {
  4614. auto res = cli_.Get("/person/john1");
  4615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4617. res = cli_.Post("/person", "name=john1&note=coder",
  4618. "application/x-www-form-urlencoded");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. ASSERT_EQ(StatusCode::OK_200, res->status);
  4621. res = cli_.Get("/person/john1");
  4622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4623. ASSERT_EQ(StatusCode::OK_200, res->status);
  4624. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4625. ASSERT_EQ("coder", res->body);
  4626. }
  4627. TEST_F(ServerTest, PostMethod2) {
  4628. auto res = cli_.Get("/person/john2");
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4631. Params params;
  4632. params.emplace("name", "john2");
  4633. params.emplace("note", "coder");
  4634. res = cli_.Post("/person", params);
  4635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4636. ASSERT_EQ(StatusCode::OK_200, res->status);
  4637. res = cli_.Get("/person/john2");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. ASSERT_EQ(StatusCode::OK_200, res->status);
  4640. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4641. ASSERT_EQ("coder", res->body);
  4642. }
  4643. TEST_F(ServerTest, PutMethod3) {
  4644. auto res = cli_.Get("/person/john3");
  4645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4646. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4647. Params params;
  4648. params.emplace("name", "john3");
  4649. params.emplace("note", "coder");
  4650. res = cli_.Put("/person", params);
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. ASSERT_EQ(StatusCode::OK_200, res->status);
  4653. res = cli_.Get("/person/john3");
  4654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4655. ASSERT_EQ(StatusCode::OK_200, res->status);
  4656. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4657. ASSERT_EQ("coder", res->body);
  4658. }
  4659. TEST_F(ServerTest, DeleteMethod1) {
  4660. auto res = cli_.Get("/person/john4");
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4663. Params params;
  4664. params.emplace("name", "john4");
  4665. params.emplace("note", "coder");
  4666. res = cli_.Post("/person", params);
  4667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4668. ASSERT_EQ(StatusCode::OK_200, res->status);
  4669. res = cli_.Get("/person/john4");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. ASSERT_EQ(StatusCode::OK_200, res->status);
  4672. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4673. ASSERT_EQ("coder", res->body);
  4674. Params delete_params;
  4675. delete_params.emplace("name", "john4");
  4676. res = cli_.Delete("/person", delete_params);
  4677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4678. ASSERT_EQ(StatusCode::OK_200, res->status);
  4679. ASSERT_EQ("DELETED", res->body);
  4680. res = cli_.Get("/person/john4");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4683. }
  4684. TEST_F(ServerTest, DeleteMethod2) {
  4685. auto res = cli_.Get("/person/john5");
  4686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4687. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4688. Params params;
  4689. params.emplace("name", "john5");
  4690. params.emplace("note", "developer");
  4691. res = cli_.Post("/person", params);
  4692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4693. ASSERT_EQ(StatusCode::OK_200, res->status);
  4694. res = cli_.Get("/person/john5");
  4695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4696. ASSERT_EQ(StatusCode::OK_200, res->status);
  4697. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4698. ASSERT_EQ("developer", res->body);
  4699. Params delete_params;
  4700. delete_params.emplace("name", "john5");
  4701. Headers headers;
  4702. headers.emplace("Custom-Header", "test-value");
  4703. res = cli_.Delete("/person", headers, delete_params);
  4704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4705. ASSERT_EQ(StatusCode::OK_200, res->status);
  4706. ASSERT_EQ("DELETED", res->body);
  4707. res = cli_.Get("/person/john5");
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4710. }
  4711. TEST_F(ServerTest, DeleteMethod3) {
  4712. auto res = cli_.Get("/person/john6");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4715. Params params;
  4716. params.emplace("name", "john6");
  4717. params.emplace("note", "tester");
  4718. res = cli_.Post("/person", params);
  4719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4720. ASSERT_EQ(StatusCode::OK_200, res->status);
  4721. res = cli_.Get("/person/john6");
  4722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4723. ASSERT_EQ(StatusCode::OK_200, res->status);
  4724. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4725. ASSERT_EQ("tester", res->body);
  4726. Params delete_params;
  4727. delete_params.emplace("name", "john6");
  4728. Headers headers;
  4729. headers.emplace("Custom-Header", "test-value");
  4730. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4732. ASSERT_EQ(StatusCode::OK_200, res->status);
  4733. ASSERT_EQ("DELETED", res->body);
  4734. res = cli_.Get("/person/john6");
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4737. }
  4738. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4739. Params params;
  4740. params.emplace("json", JSON_DATA);
  4741. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. ASSERT_EQ(StatusCode::OK_200, res->status);
  4744. ASSERT_EQ(JSON_DATA, res->body);
  4745. }
  4746. TEST_F(ServerTest, PostEmptyContent) {
  4747. auto res = cli_.Post("/empty", "", "text/plain");
  4748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4749. ASSERT_EQ(StatusCode::OK_200, res->status);
  4750. ASSERT_EQ("empty", res->body);
  4751. }
  4752. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4753. auto res = cli_.Post("/empty-no-content-type");
  4754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4755. ASSERT_EQ(StatusCode::OK_200, res->status);
  4756. ASSERT_EQ("empty-no-content-type", res->body);
  4757. }
  4758. TEST_F(ServerTest, PostPathOnly) {
  4759. auto res = cli_.Post("/path-only");
  4760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4761. ASSERT_EQ(StatusCode::OK_200, res->status);
  4762. ASSERT_EQ("path-only", res->body);
  4763. }
  4764. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4765. auto res = cli_.Post("/path-headers-only",
  4766. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4768. ASSERT_EQ(StatusCode::OK_200, res->status);
  4769. ASSERT_EQ("path-headers-only", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostLarge) {
  4772. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4774. ASSERT_EQ(StatusCode::OK_200, res->status);
  4775. EXPECT_EQ(LARGE_DATA, res->body);
  4776. }
  4777. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4778. auto res = cli_.Put("/empty-no-content-type");
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. ASSERT_EQ(StatusCode::OK_200, res->status);
  4781. ASSERT_EQ("empty-no-content-type", res->body);
  4782. }
  4783. TEST_F(ServerTest, GetMethodDir) {
  4784. auto res = cli_.Get("/dir/");
  4785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4786. EXPECT_EQ(StatusCode::OK_200, res->status);
  4787. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4788. auto body = R"(<html>
  4789. <head>
  4790. </head>
  4791. <body>
  4792. <a href="/dir/test.html">Test</a>
  4793. <a href="/hi">hi</a>
  4794. </body>
  4795. </html>
  4796. )";
  4797. EXPECT_EQ(body, res->body);
  4798. }
  4799. TEST_F(ServerTest, GetMethodDirTest) {
  4800. auto res = cli_.Get("/dir/test.html");
  4801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4804. EXPECT_EQ("test.html", res->body);
  4805. }
  4806. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4807. auto res = cli_.Get("/dir/../dir/test.html");
  4808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4811. EXPECT_EQ("test.html", res->body);
  4812. }
  4813. TEST_F(ServerTest, GetMethodInvalidPath) {
  4814. auto res = cli_.Get("/dir/../test.html");
  4815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4817. }
  4818. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4819. auto res = cli_.Get("/../www/dir/test.html");
  4820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4822. }
  4823. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4824. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4827. }
  4828. TEST_F(ServerTest, GetMethodDirMountTest) {
  4829. auto res = cli_.Get("/mount/dir/test.html");
  4830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4831. EXPECT_EQ(StatusCode::OK_200, res->status);
  4832. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4833. EXPECT_EQ("test.html", res->body);
  4834. }
  4835. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4836. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4838. EXPECT_EQ(StatusCode::OK_200, res->status);
  4839. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4840. EXPECT_EQ("test.html", res->body);
  4841. }
  4842. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4843. auto res = cli_.Get("/mount/dir/../test.html");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4846. }
  4847. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4848. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4851. }
  4852. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4853. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4856. }
  4857. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4858. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4861. }
  4862. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4863. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4865. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4866. }
  4867. TEST_F(ServerTest, PostMethod303) {
  4868. auto res = cli_.Post("/1", "body", "text/plain");
  4869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4870. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4871. EXPECT_EQ("/2", res->get_header_value("Location"));
  4872. }
  4873. TEST_F(ServerTest, PostMethod303Redirect) {
  4874. cli_.set_follow_location(true);
  4875. auto res = cli_.Post("/1", "body", "text/plain");
  4876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ("redirected.", res->body);
  4879. EXPECT_EQ("/2", res->location);
  4880. }
  4881. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4882. auto res = cli_.Get("/dir/test.abcde");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::OK_200, res->status);
  4885. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4886. EXPECT_EQ("abcde", res->body);
  4887. }
  4888. TEST_F(ServerTest, StaticFileRange) {
  4889. auto res =
  4890. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4893. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4894. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4895. EXPECT_EQ(true, res->has_header("Content-Range"));
  4896. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4897. EXPECT_EQ(std::string("cd"), res->body);
  4898. }
  4899. TEST_F(ServerTest, StaticFileRanges) {
  4900. auto res = cli_.Get("/dir/test.abcde",
  4901. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4904. EXPECT_TRUE(
  4905. res->get_header_value("Content-Type")
  4906. .find(
  4907. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4908. 0);
  4909. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4910. }
  4911. TEST_F(ServerTest, StaticFileRangeHead) {
  4912. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4914. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4915. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4916. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4917. EXPECT_EQ(true, res->has_header("Content-Range"));
  4918. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4919. }
  4920. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4921. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4924. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4925. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4926. EXPECT_EQ(true, res->has_header("Content-Range"));
  4927. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4928. res->get_header_value("Content-Range"));
  4929. EXPECT_EQ("LAST\n", res->body);
  4930. }
  4931. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4932. auto res =
  4933. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4935. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4937. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4938. EXPECT_EQ(true, res->has_header("Content-Range"));
  4939. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4940. }
  4941. TEST_F(ServerTest, StaticFileBigFile) {
  4942. auto res = cli_.Get("/dir/1MB.txt");
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4947. }
  4948. TEST_F(ServerTest, InvalidBaseDirMount) {
  4949. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4950. }
  4951. TEST_F(ServerTest, Binary) {
  4952. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4953. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4954. "application/octet-stream");
  4955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4956. ASSERT_EQ(StatusCode::OK_200, res->status);
  4957. ASSERT_EQ(4U, res->body.size());
  4958. res = cli_.Put("/binary", binary.data(), binary.size(),
  4959. "application/octet-stream");
  4960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4961. ASSERT_EQ(StatusCode::OK_200, res->status);
  4962. ASSERT_EQ(4U, res->body.size());
  4963. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4964. "application/octet-stream");
  4965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4966. ASSERT_EQ(StatusCode::OK_200, res->status);
  4967. ASSERT_EQ(4U, res->body.size());
  4968. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4969. "application/octet-stream");
  4970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4971. ASSERT_EQ(StatusCode::OK_200, res->status);
  4972. ASSERT_EQ(4U, res->body.size());
  4973. }
  4974. TEST_F(ServerTest, BinaryString) {
  4975. auto binary = std::string("\x00\x01\x02\x03", 4);
  4976. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4978. ASSERT_EQ(StatusCode::OK_200, res->status);
  4979. ASSERT_EQ(4U, res->body.size());
  4980. res = cli_.Put("/binary", binary, "application/octet-stream");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. ASSERT_EQ(StatusCode::OK_200, res->status);
  4983. ASSERT_EQ(4U, res->body.size());
  4984. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. ASSERT_EQ(StatusCode::OK_200, res->status);
  4987. ASSERT_EQ(4U, res->body.size());
  4988. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. }
  4993. TEST_F(ServerTest, EmptyRequest) {
  4994. auto res = cli_.Get("");
  4995. ASSERT_TRUE(!res);
  4996. EXPECT_EQ(Error::Connection, res.error());
  4997. }
  4998. TEST_F(ServerTest, LongRequest) {
  4999. std::string request;
  5000. for (size_t i = 0; i < 545; i++) {
  5001. request += "/TooLongRequest";
  5002. }
  5003. request += "OK";
  5004. auto res = cli_.Get(request.c_str());
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5007. }
  5008. TEST_F(ServerTest, TooLongRequest) {
  5009. std::string request;
  5010. for (size_t i = 0; i < 546; i++) {
  5011. request += "/TooLongRequest";
  5012. }
  5013. request += "_NG";
  5014. auto start = std::chrono::high_resolution_clock::now();
  5015. cli_.set_keep_alive(true);
  5016. auto res = cli_.Get(request.c_str());
  5017. auto end = std::chrono::high_resolution_clock::now();
  5018. auto elapsed =
  5019. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5020. .count();
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5023. EXPECT_LE(elapsed, 1000);
  5024. EXPECT_EQ("close", res->get_header_value("Connection"));
  5025. EXPECT_FALSE(cli_.is_socket_open());
  5026. }
  5027. TEST_F(ServerTest, AlmostTooLongRequest) {
  5028. // test for #2046 - URI length check shouldn't include other content on req
  5029. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5030. // leading /, space, HTTP/1.1)
  5031. std::string request =
  5032. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5033. auto res = cli_.Get(request.c_str());
  5034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5036. }
  5037. TEST_F(ServerTest, LongHeader) {
  5038. Request req;
  5039. req.method = "GET";
  5040. req.path = "/hi";
  5041. std::string host_and_port;
  5042. host_and_port += HOST;
  5043. host_and_port += ":";
  5044. host_and_port += std::to_string(PORT);
  5045. req.headers.emplace("Host", host_and_port.c_str());
  5046. req.headers.emplace("Accept", "*/*");
  5047. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5048. req.headers.emplace(
  5049. "Header-Name",
  5050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@");
  5079. auto res = std::make_shared<Response>();
  5080. auto error = Error::Success;
  5081. auto ret = cli_.send(req, *res, error);
  5082. ASSERT_TRUE(ret);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, LongQueryValue) {
  5086. auto start = std::chrono::high_resolution_clock::now();
  5087. cli_.set_keep_alive(true);
  5088. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5089. auto end = std::chrono::high_resolution_clock::now();
  5090. auto elapsed =
  5091. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5092. .count();
  5093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5094. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5095. EXPECT_LE(elapsed, 1000);
  5096. EXPECT_EQ("close", res->get_header_value("Connection"));
  5097. EXPECT_FALSE(cli_.is_socket_open());
  5098. }
  5099. TEST_F(ServerTest, TooLongQueryValue) {
  5100. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5101. ASSERT_FALSE(res);
  5102. EXPECT_EQ(Error::Read, res.error());
  5103. }
  5104. TEST_F(ServerTest, TooLongHeader) {
  5105. Request req;
  5106. req.method = "GET";
  5107. req.path = "/hi";
  5108. std::string host_and_port;
  5109. host_and_port += HOST;
  5110. host_and_port += ":";
  5111. host_and_port += std::to_string(PORT);
  5112. req.headers.emplace("Host", host_and_port.c_str());
  5113. req.headers.emplace("Accept", "*/*");
  5114. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5115. req.headers.emplace(
  5116. "Header-Name",
  5117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@");
  5146. auto res = std::make_shared<Response>();
  5147. auto error = Error::Success;
  5148. auto ret = cli_.send(req, *res, error);
  5149. ASSERT_TRUE(ret);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. }
  5152. TEST_F(ServerTest, HeaderCountAtLimit) {
  5153. // Test with headers just under the 100 limit
  5154. httplib::Headers headers;
  5155. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5156. // This should keep us just under the 100 header limit
  5157. for (int i = 0; i < 95; i++) {
  5158. std::string name = "X-Test-Header-" + std::to_string(i);
  5159. std::string value = "value" + std::to_string(i);
  5160. headers.emplace(name, value);
  5161. }
  5162. // This should work fine as we're under the limit
  5163. auto res = cli_.Get("/hi", headers);
  5164. EXPECT_TRUE(res);
  5165. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5166. }
  5167. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5168. // Test with many headers to exceed the 100 limit
  5169. httplib::Headers headers;
  5170. // Add 150 headers to definitely exceed the 100 limit
  5171. for (int i = 0; i < 150; i++) {
  5172. std::string name = "X-Test-Header-" + std::to_string(i);
  5173. std::string value = "value" + std::to_string(i);
  5174. headers.emplace(name, value);
  5175. }
  5176. // This should fail due to exceeding header count limit
  5177. cli_.set_keep_alive(true);
  5178. auto res = cli_.Get("/hi", headers);
  5179. // The server should respond with 400 Bad Request
  5180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5182. EXPECT_EQ("close", res->get_header_value("Connection"));
  5183. EXPECT_FALSE(cli_.is_socket_open());
  5184. }
  5185. TEST_F(ServerTest, PercentEncoding) {
  5186. auto res = cli_.Get("/e%6edwith%");
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::OK_200, res->status);
  5189. }
  5190. TEST_F(ServerTest, PercentEncodingUnicode) {
  5191. auto res = cli_.Get("/e%u006edwith%");
  5192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5193. EXPECT_EQ(StatusCode::OK_200, res->status);
  5194. }
  5195. TEST_F(ServerTest, InvalidPercentEncoding) {
  5196. auto res = cli_.Get("/%endwith%");
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5199. }
  5200. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5201. auto res = cli_.Get("/%uendwith%");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5204. }
  5205. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5206. auto res = cli_.Get("/hello?aaa=bbb%");
  5207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5208. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5209. }
  5210. TEST_F(ServerTest, PlusSignEncoding) {
  5211. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5213. EXPECT_EQ(StatusCode::OK_200, res->status);
  5214. EXPECT_EQ("a +b", res->body);
  5215. }
  5216. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5217. // This test simulates a potential DoS attack using many headers
  5218. // to verify our security fix prevents memory exhaustion
  5219. httplib::Headers attack_headers;
  5220. // Attempt to add many headers like an attacker would (200 headers to far
  5221. // exceed limit)
  5222. for (int i = 0; i < 200; i++) {
  5223. std::string name = "X-Attack-Header-" + std::to_string(i);
  5224. std::string value = "attack_payload_" + std::to_string(i);
  5225. attack_headers.emplace(name, value);
  5226. }
  5227. // Try to POST with excessive headers
  5228. cli_.set_keep_alive(true);
  5229. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5230. // Should either fail or return 400 Bad Request due to security limit
  5231. if (res) {
  5232. // If we get a response, it should be 400 Bad Request
  5233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5234. EXPECT_EQ("close", res->get_header_value("Connection"));
  5235. }
  5236. EXPECT_FALSE(cli_.is_socket_open());
  5237. }
  5238. TEST_F(ServerTest, MultipartFormData) {
  5239. UploadFormDataItems items = {
  5240. {"text1", "text default", "", ""},
  5241. {"text2", "aωb", "", ""},
  5242. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5243. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5244. {"file3", "", "", "application/octet-stream"},
  5245. {"file4", "", "", " application/json tmp-string "}};
  5246. auto res = cli_.Post("/multipart", items);
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. EXPECT_EQ(StatusCode::OK_200, res->status);
  5249. }
  5250. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5251. UploadFormDataItems items = {
  5252. {"text", "default text", "", ""},
  5253. {"multi_text1", "aaaaa", "", ""},
  5254. {"multi_text1", "bbbbb", "", ""},
  5255. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5256. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5257. "application/json"},
  5258. };
  5259. auto res = cli_.Post("/multipart/multi_file_values", items);
  5260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. }
  5263. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5264. auto res = cli_.Get("/hi");
  5265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5268. EXPECT_EQ("Hello World!", res->body);
  5269. }
  5270. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5271. Request req;
  5272. req.method = "POST";
  5273. req.path = "/chunked";
  5274. std::string host_and_port;
  5275. host_and_port += HOST;
  5276. host_and_port += ":";
  5277. host_and_port += std::to_string(PORT);
  5278. req.headers.emplace("Host", host_and_port.c_str());
  5279. req.headers.emplace("Accept", "*/*");
  5280. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5281. req.headers.emplace("Content-Type", "text/plain");
  5282. req.headers.emplace("Content-Length", "0");
  5283. req.headers.emplace(
  5284. "Transfer-Encoding",
  5285. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5286. // Client does not chunk, so make a chunked body manually.
  5287. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5288. auto res = std::make_shared<Response>();
  5289. auto error = Error::Success;
  5290. auto ret = cli_.send(req, *res, error);
  5291. ASSERT_TRUE(ret);
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. }
  5294. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5295. // rather than treat them as valid lengths.
  5296. template <typename ClientT>
  5297. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5298. Request req;
  5299. req.method = "POST";
  5300. req.path = "/chunked";
  5301. std::string host_and_port;
  5302. host_and_port += HOST;
  5303. host_and_port += ":";
  5304. host_and_port += std::to_string(PORT);
  5305. req.headers.emplace("Host", host_and_port.c_str());
  5306. req.headers.emplace("Content-Length", "0");
  5307. req.headers.emplace("Transfer-Encoding", "chunked");
  5308. req.body = body;
  5309. auto res = std::make_shared<Response>();
  5310. auto error = Error::Success;
  5311. ASSERT_TRUE(cli.send(req, *res, error));
  5312. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5313. }
  5314. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5315. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5316. }
  5317. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5318. expect_chunked_body_rejected(
  5319. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5320. }
  5321. TEST_F(ServerTest, GetStreamed2) {
  5322. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5325. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5326. EXPECT_EQ(true, res->has_header("Content-Range"));
  5327. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5328. EXPECT_EQ(std::string("ab"), res->body);
  5329. }
  5330. TEST_F(ServerTest, GetStreamed) {
  5331. auto res = cli_.Get("/streamed");
  5332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5335. EXPECT_EQ(std::string("aaabbb"), res->body);
  5336. }
  5337. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5338. auto res = cli_.Get("/streamed-without-length",
  5339. Headers{make_range_header({{0, -1}})});
  5340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. EXPECT_EQ(false, res->has_header("Content-Length"));
  5343. EXPECT_EQ(false, res->has_header("Content-Range"));
  5344. EXPECT_EQ(std::string("abcdefg"), res->body);
  5345. }
  5346. TEST_F(ServerTest, GetStreamedWithRange1) {
  5347. auto res =
  5348. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5351. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5352. EXPECT_EQ(true, res->has_header("Content-Range"));
  5353. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5354. EXPECT_EQ(std::string("def"), res->body);
  5355. }
  5356. TEST_F(ServerTest, GetStreamedWithRange2) {
  5357. auto res =
  5358. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5361. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5362. EXPECT_EQ(true, res->has_header("Content-Range"));
  5363. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5364. EXPECT_EQ(std::string("bcdefg"), res->body);
  5365. }
  5366. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5367. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5370. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5371. EXPECT_EQ(true, res->has_header("Content-Range"));
  5372. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5373. EXPECT_EQ(std::string("efg"), res->body);
  5374. }
  5375. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5376. auto res =
  5377. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5380. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ(false, res->has_header("Content-Range"));
  5382. EXPECT_EQ(0U, res->body.size());
  5383. }
  5384. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5385. // Only a 206 is served as a partial representation. Under any other status
  5386. // `apply_ranges()` reported the full content length, so the body must match
  5387. // that header, and the content provider must never be asked for an offset
  5388. // outside the representation.
  5389. auto check = [&](int status, const char *range) {
  5390. auto path =
  5391. std::string("/streamed-with-range?status=") + std::to_string(status);
  5392. auto ctx = path + " Range: " + range;
  5393. auto res = cli_.Get(path, Headers{{"Range", range}});
  5394. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5395. EXPECT_EQ(status, res->status) << ctx;
  5396. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5398. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5399. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5400. };
  5401. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5402. check(403, "bytes=3-5");
  5403. // The offset is far past the representation.
  5404. check(403, "bytes=100000-100200");
  5405. // `first_pos` is still -1 here, and the bounds asserts in
  5406. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5407. check(403, "bytes=-3");
  5408. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5409. // multipart branch would have written one that is empty.
  5410. check(403, "bytes=1-2, 4-5");
  5411. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5412. // covers the whole representation.
  5413. check(200, "bytes=3-5");
  5414. check(200, "bytes=1-2, 4-5");
  5415. }
  5416. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5417. auto res =
  5418. cli_.Get("/streamed-with-range",
  5419. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5420. "92233720368547758079223372036854775807"}});
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5423. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5424. EXPECT_EQ(false, res->has_header("Content-Range"));
  5425. EXPECT_EQ(0U, res->body.size());
  5426. }
  5427. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5428. auto res = cli_.Get(
  5429. "/with-range",
  5430. Headers{{"Range",
  5431. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5432. {"Accept-Encoding", ""}});
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5435. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5436. EXPECT_EQ(true, res->has_header("Content-Range"));
  5437. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5438. EXPECT_EQ(std::string("abcdefg"), res->body);
  5439. }
  5440. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5441. auto res = cli_.Get("/with-range", Headers{
  5442. {"Range", "bytes=0-"},
  5443. {"Accept-Encoding", ""},
  5444. });
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5447. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5448. EXPECT_EQ(true, res->has_header("Content-Range"));
  5449. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5450. EXPECT_EQ(std::string("abcdefg"), res->body);
  5451. }
  5452. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5453. auto res = cli_.Get("/streamed-with-range",
  5454. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5457. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5458. EXPECT_EQ(false, res->has_header("Content-Range"));
  5459. EXPECT_EQ(267U, res->body.size());
  5460. // Check that both range contents are present
  5461. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5462. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5463. // Check that Content-Range headers are present for both ranges
  5464. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5465. std::string::npos);
  5466. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5467. std::string::npos);
  5468. }
  5469. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5470. Ranges ranges;
  5471. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5472. ranges.emplace_back(0, -1);
  5473. }
  5474. auto res = cli_.Get("/streamed-with-range?error",
  5475. Headers{{make_range_header(ranges)}});
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5478. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5479. EXPECT_EQ(false, res->has_header("Content-Range"));
  5480. EXPECT_EQ(0U, res->body.size());
  5481. }
  5482. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5483. auto res = cli_.Get("/streamed-with-range",
  5484. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5487. EXPECT_EQ(5U, res->body.size());
  5488. // Check that overlapping ranges are coalesced into a single range
  5489. EXPECT_EQ("bcdef", res->body);
  5490. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5491. // Should be single range, not multipart
  5492. EXPECT_TRUE(res->has_header("Content-Range"));
  5493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5494. }
  5495. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5496. auto res = cli_.Get("/streamed-with-range",
  5497. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5500. EXPECT_EQ(268U, res->body.size());
  5501. // Check that both range contents are present
  5502. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5503. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5504. // Check that Content-Range headers are present for both ranges
  5505. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5506. std::string::npos);
  5507. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5508. std::string::npos);
  5509. }
  5510. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5511. auto res = cli_.Get("/streamed-with-range",
  5512. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5514. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5515. EXPECT_EQ(269U, res->body.size());
  5516. // Check that both duplicate range contents are present
  5517. size_t first_abc = res->body.find("abc\r\n");
  5518. EXPECT_TRUE(first_abc != std::string::npos);
  5519. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5520. EXPECT_TRUE(second_abc != std::string::npos);
  5521. // Check that Content-Range headers are present for both ranges
  5522. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5523. EXPECT_TRUE(first_range != std::string::npos);
  5524. size_t second_range =
  5525. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5526. EXPECT_TRUE(second_range != std::string::npos);
  5527. }
  5528. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5529. auto res =
  5530. cli_.Get("/streamed-with-range?error",
  5531. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5534. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ(false, res->has_header("Content-Range"));
  5536. EXPECT_EQ(0U, res->body.size());
  5537. }
  5538. TEST_F(ServerTest, GetStreamedEndless) {
  5539. uint64_t offset = 0;
  5540. auto res = cli_.Get("/streamed-cancel",
  5541. [&](const char * /*data*/, uint64_t data_length) {
  5542. if (offset < 100) {
  5543. offset += data_length;
  5544. return true;
  5545. }
  5546. return false;
  5547. });
  5548. ASSERT_TRUE(!res);
  5549. EXPECT_EQ(Error::Canceled, res.error());
  5550. }
  5551. TEST_F(ServerTest, ClientStop) {
  5552. std::atomic_size_t count{4};
  5553. std::vector<std::thread> threads;
  5554. for (auto i = count.load(); i != 0; --i) {
  5555. threads.emplace_back([&]() {
  5556. auto res = cli_.Get("/streamed-cancel",
  5557. [&](const char *, uint64_t) { return true; });
  5558. --count;
  5559. ASSERT_TRUE(!res);
  5560. EXPECT_TRUE(res.error() == Error::Canceled ||
  5561. res.error() == Error::Read || res.error() == Error::Write);
  5562. });
  5563. }
  5564. std::this_thread::sleep_for(std::chrono::seconds(2));
  5565. while (count != 0) {
  5566. cli_.stop();
  5567. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5568. }
  5569. for (auto &t : threads) {
  5570. t.join();
  5571. }
  5572. }
  5573. TEST_F(ServerTest, GetWithRange1) {
  5574. auto res = cli_.Get("/with-range", Headers{
  5575. make_range_header({{3, 5}}),
  5576. {"Accept-Encoding", ""},
  5577. });
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5580. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5581. EXPECT_EQ(true, res->has_header("Content-Range"));
  5582. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5583. EXPECT_EQ(std::string("def"), res->body);
  5584. }
  5585. TEST_F(ServerTest, GetWithRange2) {
  5586. auto res = cli_.Get("/with-range", Headers{
  5587. make_range_header({{1, -1}}),
  5588. {"Accept-Encoding", ""},
  5589. });
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5592. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5593. EXPECT_EQ(true, res->has_header("Content-Range"));
  5594. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5595. EXPECT_EQ(std::string("bcdefg"), res->body);
  5596. }
  5597. TEST_F(ServerTest, GetWithRange3) {
  5598. auto res = cli_.Get("/with-range", Headers{
  5599. make_range_header({{0, 0}}),
  5600. {"Accept-Encoding", ""},
  5601. });
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5604. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5605. EXPECT_EQ(true, res->has_header("Content-Range"));
  5606. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5607. EXPECT_EQ(std::string("a"), res->body);
  5608. }
  5609. TEST_F(ServerTest, GetWithRange4) {
  5610. auto res = cli_.Get("/with-range", Headers{
  5611. make_range_header({{-1, 2}}),
  5612. {"Accept-Encoding", ""},
  5613. });
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5616. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5617. EXPECT_EQ(true, res->has_header("Content-Range"));
  5618. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5619. EXPECT_EQ(std::string("fg"), res->body);
  5620. }
  5621. TEST_F(ServerTest, GetWithRange5) {
  5622. auto res = cli_.Get("/with-range", Headers{
  5623. make_range_header({{0, 5}}),
  5624. {"Accept-Encoding", ""},
  5625. });
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5628. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5629. EXPECT_EQ(true, res->has_header("Content-Range"));
  5630. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5631. EXPECT_EQ(std::string("abcdef"), res->body);
  5632. }
  5633. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5634. auto res =
  5635. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5638. }
  5639. TEST_F(ServerTest, GetWithRangeMultipart) {
  5640. auto res =
  5641. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5644. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5645. EXPECT_EQ(false, res->has_header("Content-Range"));
  5646. EXPECT_EQ(267U, res->body.size());
  5647. }
  5648. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5649. auto res = cli_.Get("/with-range",
  5650. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5653. }
  5654. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5655. auto res = cli_.Get("/with-range-customized-response",
  5656. Headers{{make_range_header({{1, 2}})}});
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5659. EXPECT_EQ(true, res->has_header("Content-Length"));
  5660. EXPECT_EQ(false, res->has_header("Content-Range"));
  5661. EXPECT_EQ(JSON_DATA, res->body);
  5662. }
  5663. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5664. auto res = cli_.Get("/with-range-customized-response",
  5665. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5668. EXPECT_EQ(true, res->has_header("Content-Length"));
  5669. EXPECT_EQ(false, res->has_header("Content-Range"));
  5670. EXPECT_EQ(JSON_DATA, res->body);
  5671. }
  5672. TEST_F(ServerTest, Issue1772) {
  5673. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5676. }
  5677. TEST_F(ServerTest, Issue609) {
  5678. auto res = cli_.Delete("/issue609");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ(std::string("ok"), res->body);
  5682. }
  5683. TEST_F(ServerTest, GetStreamedChunked) {
  5684. auto res = cli_.Get("/streamed-chunked");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. EXPECT_EQ(StatusCode::OK_200, res->status);
  5687. EXPECT_EQ(std::string("123456789"), res->body);
  5688. }
  5689. TEST_F(ServerTest, GetStreamedChunked2) {
  5690. auto res = cli_.Get("/streamed-chunked2");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. EXPECT_EQ(StatusCode::OK_200, res->status);
  5693. EXPECT_EQ(std::string("123456789"), res->body);
  5694. }
  5695. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5696. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. EXPECT_EQ(StatusCode::OK_200, res->status);
  5699. EXPECT_EQ(std::string("123456789"), res->body);
  5700. EXPECT_TRUE(res->has_header("Trailer"));
  5701. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5702. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5703. // Trailers are now stored separately from headers (security fix)
  5704. EXPECT_EQ(2U, res->trailers.size());
  5705. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5706. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5707. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5708. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5709. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5710. // Verify trailers are NOT in headers (security verification)
  5711. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5712. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5713. }
  5714. TEST_F(ServerTest, LargeChunkedPost) {
  5715. Request req;
  5716. req.method = "POST";
  5717. req.path = "/large-chunked";
  5718. std::string host_and_port;
  5719. host_and_port += HOST;
  5720. host_and_port += ":";
  5721. host_and_port += std::to_string(PORT);
  5722. req.headers.emplace("Host", host_and_port.c_str());
  5723. req.headers.emplace("Accept", "*/*");
  5724. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5725. req.headers.emplace("Content-Type", "text/plain");
  5726. req.headers.emplace("Content-Length", "0");
  5727. req.headers.emplace("Transfer-Encoding", "chunked");
  5728. std::string long_string(30 * 1024u, 'a');
  5729. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5730. // Attempt to make a large enough post to exceed OS buffers, to test that
  5731. // the server handles short reads if the full chunk data isn't available.
  5732. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5733. auto res = std::make_shared<Response>();
  5734. auto error = Error::Success;
  5735. auto ret = cli_.send(req, *res, error);
  5736. ASSERT_TRUE(ret);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. }
  5739. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5740. auto res = cli_.Get("/remote_addr");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5745. }
  5746. TEST_F(ServerTest, GetMethodLocalAddr) {
  5747. auto res = cli_.Get("/local_addr");
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. EXPECT_EQ(StatusCode::OK_200, res->status);
  5750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5751. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5752. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5753. }
  5754. TEST_F(ServerTest, HTTPResponseSplitting) {
  5755. auto res = cli_.Get("/http_response_splitting");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. }
  5759. TEST_F(ServerTest, SlowRequest) {
  5760. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5761. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5762. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5763. }
  5764. #if 0
  5765. TEST_F(ServerTest, SlowPost) {
  5766. char buffer[64 * 1024];
  5767. memset(buffer, 0x42, sizeof(buffer));
  5768. auto res = cli_.Post(
  5769. "/slowpost", 64 * 1024 * 1024,
  5770. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5771. auto ret = sink.write(buffer, sizeof(buffer));
  5772. EXPECT_TRUE(ret);
  5773. return true;
  5774. },
  5775. "text/plain");
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, SlowPostFail) {
  5780. char buffer[64 * 1024];
  5781. memset(buffer, 0x42, sizeof(buffer));
  5782. cli_.set_write_timeout(std::chrono::seconds(0));
  5783. auto res = cli_.Post(
  5784. "/slowpost", 64 * 1024 * 1024,
  5785. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5786. sink.write(buffer, sizeof(buffer));
  5787. return true;
  5788. },
  5789. "text/plain");
  5790. ASSERT_TRUE(!res);
  5791. EXPECT_EQ(Error::Write, res.error());
  5792. }
  5793. #endif
  5794. TEST_F(ServerTest, Put) {
  5795. auto res = cli_.Put("/put", "PUT", "text/plain");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ("PUT", res->body);
  5799. }
  5800. TEST_F(ServerTest, PutWithContentProvider) {
  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, PostWithContentProviderAbort) {
  5813. auto res = cli_.Post(
  5814. "/post", 42,
  5815. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5816. return false;
  5817. },
  5818. "text/plain");
  5819. ASSERT_TRUE(!res);
  5820. EXPECT_EQ(Error::Canceled, res.error());
  5821. }
  5822. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5823. auto res = cli_.Put(
  5824. "/put",
  5825. [](size_t /*offset*/, DataSink &sink) {
  5826. sink.os << "PUT";
  5827. sink.done();
  5828. return true;
  5829. },
  5830. "text/plain");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. EXPECT_EQ("PUT", res->body);
  5834. }
  5835. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5836. auto res = cli_.Post(
  5837. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5838. "text/plain");
  5839. ASSERT_TRUE(!res);
  5840. EXPECT_EQ(Error::Canceled, res.error());
  5841. }
  5842. TEST_F(ServerTest, PostLoopBack) {
  5843. std::string body;
  5844. auto res = cli_.Post(
  5845. "/post-loopback", 9,
  5846. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5847. EXPECT_EQ(9u, length);
  5848. sink.write("123", 3);
  5849. sink.write("456", 3);
  5850. sink.write("789", 3);
  5851. return true;
  5852. },
  5853. "text/plain",
  5854. [&body](const char *data, size_t data_length) {
  5855. body.append(data, data_length);
  5856. return true;
  5857. });
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("123456789", body);
  5861. }
  5862. TEST_F(ServerTest, PutLoopBack) {
  5863. std::string body;
  5864. auto res = cli_.Put(
  5865. "/put-loopback", 9,
  5866. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5867. EXPECT_EQ(9u, length);
  5868. sink.write("123", 3);
  5869. sink.write("456", 3);
  5870. sink.write("789", 3);
  5871. return true;
  5872. },
  5873. "text/plain",
  5874. [&body](const char *data, size_t data_length) {
  5875. body.append(data, data_length);
  5876. return true;
  5877. });
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::OK_200, res->status);
  5880. EXPECT_EQ("123456789", body);
  5881. }
  5882. TEST_F(ServerTest, PatchLoopBack) {
  5883. std::string body;
  5884. auto res = cli_.Patch(
  5885. "/patch-loopback", 9,
  5886. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5887. EXPECT_EQ(9u, length);
  5888. sink.write("123", 3);
  5889. sink.write("456", 3);
  5890. sink.write("789", 3);
  5891. return true;
  5892. },
  5893. "text/plain",
  5894. [&body](const char *data, size_t data_length) {
  5895. body.append(data, data_length);
  5896. return true;
  5897. });
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. EXPECT_EQ(StatusCode::OK_200, res->status);
  5900. EXPECT_EQ("123456789", body);
  5901. }
  5902. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5903. std::string body;
  5904. auto res = cli_.Post(
  5905. "/post-loopback",
  5906. [](size_t /*offset*/, DataSink &sink) {
  5907. sink.write("123", 3);
  5908. sink.write("456", 3);
  5909. sink.write("789", 3);
  5910. sink.done();
  5911. return true;
  5912. },
  5913. "text/plain",
  5914. [&body](const char *data, size_t data_length) {
  5915. body.append(data, data_length);
  5916. return true;
  5917. });
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("123456789", body);
  5921. }
  5922. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5923. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5924. cli_.set_compress(true);
  5925. auto res = cli_.Put(
  5926. "/put", 3,
  5927. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5928. sink.os << "PUT";
  5929. return true;
  5930. },
  5931. "text/plain");
  5932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5933. EXPECT_EQ(StatusCode::OK_200, res->status);
  5934. EXPECT_EQ("PUT", res->body);
  5935. }
  5936. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5937. cli_.set_compress(true);
  5938. auto res = cli_.Post(
  5939. "/post", 42,
  5940. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5941. return false;
  5942. },
  5943. "text/plain");
  5944. ASSERT_TRUE(!res);
  5945. EXPECT_EQ(Error::Canceled, res.error());
  5946. }
  5947. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5948. cli_.set_compress(true);
  5949. auto res = cli_.Put(
  5950. "/put",
  5951. [](size_t /*offset*/, DataSink &sink) {
  5952. sink.os << "PUT";
  5953. sink.done();
  5954. return true;
  5955. },
  5956. "text/plain");
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("PUT", res->body);
  5960. }
  5961. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5962. cli_.set_compress(true);
  5963. auto res = cli_.Post(
  5964. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5965. "text/plain");
  5966. ASSERT_TRUE(!res);
  5967. EXPECT_EQ(Error::Canceled, res.error());
  5968. }
  5969. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5970. cli_.set_compress(true);
  5971. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ(LARGE_DATA, res->body);
  5975. }
  5976. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5977. #ifdef CPPHTTPLIB_SSL_ENABLED
  5978. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5979. Client cli(s.c_str());
  5980. cli.enable_server_certificate_verification(false);
  5981. #else
  5982. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5983. Client cli(s.c_str());
  5984. #endif
  5985. cli.set_compress(true);
  5986. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::OK_200, res->status);
  5989. EXPECT_EQ(LARGE_DATA, res->body);
  5990. // The compressed size should be less than a 10th of the original. May vary
  5991. // depending on the zlib library.
  5992. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5993. static_cast<uint64_t>(10 * 1024 * 1024));
  5994. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5995. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5996. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5997. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5998. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5999. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6000. #endif
  6001. }
  6002. TEST_F(ServerTest, PutContentWithDeflate) {
  6003. cli_.set_compress(false);
  6004. Headers headers;
  6005. headers.emplace("Content-Encoding", "deflate");
  6006. // PUT in deflate format:
  6007. auto res = cli_.Put("/put", headers,
  6008. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("PUT", res->body);
  6012. }
  6013. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6014. Headers headers;
  6015. headers.emplace("Accept-Encoding", "gzip, deflate");
  6016. auto res = cli_.Get("/streamed-chunked", headers);
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ(std::string("123456789"), res->body);
  6020. }
  6021. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6022. Headers headers;
  6023. headers.emplace("Accept-Encoding", "gzip, deflate");
  6024. auto res = cli_.Get("/streamed-chunked2", headers);
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. EXPECT_EQ(std::string("123456789"), res->body);
  6028. }
  6029. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6030. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::OK_200, res->status);
  6033. }
  6034. TEST(GzipDecompressor, ChunkedDecompression) {
  6035. std::string data;
  6036. for (size_t i = 0; i < 32 * 1024; ++i) {
  6037. data.push_back(static_cast<char>('a' + i % 26));
  6038. }
  6039. std::string compressed_data;
  6040. {
  6041. httplib::detail::gzip_compressor compressor;
  6042. bool result = compressor.compress(
  6043. data.data(), data.size(),
  6044. /*last=*/true,
  6045. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6046. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6047. compressed_data_size);
  6048. return true;
  6049. });
  6050. ASSERT_TRUE(result);
  6051. }
  6052. std::string decompressed_data;
  6053. {
  6054. httplib::detail::gzip_decompressor decompressor;
  6055. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6056. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6057. size_t chunk_size = 130;
  6058. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6059. chunk_begin += chunk_size) {
  6060. size_t current_chunk_size =
  6061. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6062. bool result = decompressor.decompress(
  6063. compressed_data.data() + chunk_begin, current_chunk_size,
  6064. [&](const char *decompressed_data_chunk,
  6065. size_t decompressed_data_chunk_size) {
  6066. decompressed_data.insert(decompressed_data.size(),
  6067. decompressed_data_chunk,
  6068. decompressed_data_chunk_size);
  6069. return true;
  6070. });
  6071. ASSERT_TRUE(result);
  6072. }
  6073. }
  6074. ASSERT_EQ(data, decompressed_data);
  6075. }
  6076. TEST(GzipDecompressor, DeflateDecompression) {
  6077. std::string original_text = "Raw deflate without gzip";
  6078. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6079. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6080. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6081. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6082. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6083. std::string decompressed_data;
  6084. {
  6085. httplib::detail::gzip_decompressor decompressor;
  6086. bool result = decompressor.decompress(
  6087. compressed_data.data(), compressed_data.size(),
  6088. [&](const char *decompressed_data_chunk,
  6089. size_t decompressed_data_chunk_size) {
  6090. decompressed_data.insert(decompressed_data.size(),
  6091. decompressed_data_chunk,
  6092. decompressed_data_chunk_size);
  6093. return true;
  6094. });
  6095. ASSERT_TRUE(result);
  6096. }
  6097. ASSERT_EQ(original_text, decompressed_data);
  6098. }
  6099. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6100. std::string original_text = "Raw deflate without gzip";
  6101. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6102. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6103. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6104. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6105. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6106. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6107. std::string decompressed_data;
  6108. {
  6109. httplib::detail::gzip_decompressor decompressor;
  6110. bool result = decompressor.decompress(
  6111. compressed_data.data(), compressed_data.size(),
  6112. [&](const char *decompressed_data_chunk,
  6113. size_t decompressed_data_chunk_size) {
  6114. decompressed_data.insert(decompressed_data.size(),
  6115. decompressed_data_chunk,
  6116. decompressed_data_chunk_size);
  6117. return true;
  6118. });
  6119. ASSERT_TRUE(result);
  6120. }
  6121. ASSERT_EQ(original_text, decompressed_data);
  6122. }
  6123. #endif
  6124. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6125. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6126. Headers headers;
  6127. headers.emplace("Accept-Encoding", "br");
  6128. auto res = cli_.Get("/streamed-chunked", headers);
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. EXPECT_EQ(StatusCode::OK_200, res->status);
  6131. EXPECT_EQ(std::string("123456789"), res->body);
  6132. }
  6133. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6134. Headers headers;
  6135. headers.emplace("Accept-Encoding", "br");
  6136. auto res = cli_.Get("/streamed-chunked2", headers);
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::OK_200, res->status);
  6139. EXPECT_EQ(std::string("123456789"), res->body);
  6140. }
  6141. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6142. cli_.set_compress(true);
  6143. auto res = cli_.Put(
  6144. "/put", 3,
  6145. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6146. sink.os << "PUT";
  6147. return true;
  6148. },
  6149. "text/plain");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. EXPECT_EQ("PUT", res->body);
  6153. }
  6154. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6155. cli_.set_compress(true);
  6156. auto res = cli_.Put(
  6157. "/put",
  6158. [](size_t /*offset*/, DataSink &sink) {
  6159. sink.os << "PUT";
  6160. sink.done();
  6161. return true;
  6162. },
  6163. "text/plain");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. EXPECT_EQ(StatusCode::OK_200, res->status);
  6166. EXPECT_EQ("PUT", res->body);
  6167. }
  6168. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6169. cli_.set_compress(true);
  6170. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6172. EXPECT_EQ(StatusCode::OK_200, res->status);
  6173. EXPECT_EQ(LARGE_DATA, res->body);
  6174. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6175. }
  6176. #endif
  6177. TEST_F(ServerTest, Patch) {
  6178. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6180. EXPECT_EQ(StatusCode::OK_200, res->status);
  6181. EXPECT_EQ("PATCH", res->body);
  6182. }
  6183. TEST_F(ServerTest, Delete) {
  6184. auto res = cli_.Delete("/delete");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::OK_200, res->status);
  6187. EXPECT_EQ("DELETE", res->body);
  6188. }
  6189. TEST_F(ServerTest, DeleteContentReceiver) {
  6190. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. EXPECT_EQ(StatusCode::OK_200, res->status);
  6193. EXPECT_EQ("content", res->body);
  6194. }
  6195. TEST_F(ServerTest, Options) {
  6196. auto res = cli_.Options("*");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6200. EXPECT_TRUE(res->body.empty());
  6201. }
  6202. TEST_F(ServerTest, URL) {
  6203. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. }
  6207. TEST_F(ServerTest, ArrayParam) {
  6208. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::OK_200, res->status);
  6211. }
  6212. TEST_F(ServerTest, ArrayParamValues) {
  6213. auto res =
  6214. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. EXPECT_EQ(StatusCode::OK_200, res->status);
  6217. }
  6218. TEST_F(ServerTest, NoMultipleHeaders) {
  6219. Headers headers = {{"Content-Length", "5"}};
  6220. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6221. "text/plain");
  6222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6223. EXPECT_EQ(StatusCode::OK_200, res->status);
  6224. }
  6225. TEST_F(ServerTest, PostContentReceiver) {
  6226. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. ASSERT_EQ(StatusCode::OK_200, res->status);
  6229. ASSERT_EQ("content", res->body);
  6230. }
  6231. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6232. UploadFormDataItems items = {
  6233. {"text1", "text default", "", ""},
  6234. {"text2", "aωb", "", ""},
  6235. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6236. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6237. {"file3", "", "", "application/octet-stream"},
  6238. };
  6239. auto res = cli_.Post("/content_receiver", items);
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. }
  6243. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6244. UploadFormDataItems items = {
  6245. {"text1", "text default", "", ""},
  6246. {"text2", "aωb", "", ""},
  6247. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6248. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6249. {"file3", "", "", "application/octet-stream"},
  6250. };
  6251. auto boundary = std::string("+++++");
  6252. std::string body;
  6253. for (const auto &item : items) {
  6254. body += "--" + boundary + "\r\n";
  6255. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6256. if (!item.filename.empty()) {
  6257. body += "; filename=\"" + item.filename + "\"";
  6258. }
  6259. body += "\r\n";
  6260. if (!item.content_type.empty()) {
  6261. body += "Content-Type: " + item.content_type + "\r\n";
  6262. }
  6263. body += "\r\n";
  6264. body += item.content + "\r\n";
  6265. }
  6266. body += "--" + boundary + "--\r\n";
  6267. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6268. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6270. EXPECT_EQ(StatusCode::OK_200, res->status);
  6271. }
  6272. TEST(MultipartFormDataTest, FieldEscaping) {
  6273. Server svr;
  6274. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6275. const ContentReader &content_reader) {
  6276. ASSERT_TRUE(req.is_multipart_form_data());
  6277. std::vector<FormData> received;
  6278. content_reader(
  6279. [&](const FormData &file) {
  6280. received.push_back(file);
  6281. return true;
  6282. },
  6283. [&](const char *data, size_t data_length) {
  6284. received.back().content.append(data, data_length);
  6285. return true;
  6286. });
  6287. // '"', CR and LF in names and filenames are escaped following the
  6288. // WHATWG HTML standard, so each part still parses as a single part
  6289. // with no injected headers. Content types get CR/LF escaped too,
  6290. // while '"' (legal there, e.g. quoted charset) is preserved.
  6291. ASSERT_EQ(4U, received.size());
  6292. EXPECT_EQ("na%22me", received[0].name);
  6293. EXPECT_EQ("quoted name", received[0].content);
  6294. EXPECT_EQ("file", received[1].name);
  6295. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6296. received[1].filename);
  6297. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6298. EXPECT_EQ("injected", received[1].content);
  6299. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6300. EXPECT_EQ("my%22file.txt", received[2].filename);
  6301. EXPECT_EQ("cr lf name", received[2].content);
  6302. EXPECT_EQ("typed", received[3].name);
  6303. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6304. received[3].content_type);
  6305. EXPECT_EQ("typed content", received[3].content);
  6306. });
  6307. auto port = svr.bind_to_any_port("localhost");
  6308. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6309. auto se = detail::scope_exit([&] {
  6310. svr.stop();
  6311. t.join();
  6312. ASSERT_FALSE(svr.is_running());
  6313. });
  6314. svr.wait_until_ready();
  6315. Client cli("localhost", port);
  6316. UploadFormDataItems items = {
  6317. {"na\"me", "quoted name", "", ""},
  6318. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6319. "application/octet-stream"},
  6320. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6321. {"typed", "typed content", "",
  6322. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6323. };
  6324. auto res = cli.Post("/post", items);
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. }
  6328. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6329. const UploadFormDataItems items = {
  6330. {"name1", "Content 1", "", ""},
  6331. {"name2", "Content 2", "file2.txt", "text/plain"},
  6332. };
  6333. Server svr;
  6334. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6335. const ContentReader &content_reader) {
  6336. ASSERT_TRUE(req.is_multipart_form_data());
  6337. std::vector<FormData> received;
  6338. content_reader(
  6339. [&](const FormData &file) {
  6340. received.push_back(file);
  6341. return true;
  6342. },
  6343. [&](const char *data, size_t data_length) {
  6344. received.back().content.append(data, data_length);
  6345. return true;
  6346. });
  6347. ASSERT_EQ(2U, received.size());
  6348. EXPECT_EQ("name1", received[0].name);
  6349. EXPECT_EQ("Content 1", received[0].content);
  6350. EXPECT_EQ("name2", received[1].name);
  6351. EXPECT_EQ("Content 2", received[1].content);
  6352. EXPECT_EQ("file2.txt", received[1].filename);
  6353. EXPECT_EQ("text/plain", received[1].content_type);
  6354. });
  6355. auto port = svr.bind_to_any_port("localhost");
  6356. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6357. auto se = detail::scope_exit([&] {
  6358. svr.stop();
  6359. t.join();
  6360. ASSERT_FALSE(svr.is_running());
  6361. });
  6362. svr.wait_until_ready();
  6363. Client cli("localhost", port);
  6364. // Whole-body serialization with a generated boundary
  6365. {
  6366. MultipartFormDataWriter writer;
  6367. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6368. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6369. writer.content_type());
  6370. auto body = writer.serialize(items);
  6371. EXPECT_EQ(body.size(), writer.content_length(items));
  6372. auto res = cli.Post("/post", body, writer.content_type());
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. }
  6376. // Per-part framing with a custom boundary via a content provider
  6377. {
  6378. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6379. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6380. MultipartFormDataWriter writer("custom-boundary_123");
  6381. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6382. std::string body;
  6383. for (const auto &item : items) {
  6384. body += writer.item_begin(item);
  6385. body += item.content;
  6386. body += MultipartFormDataWriter::item_end();
  6387. }
  6388. body += writer.finish();
  6389. EXPECT_EQ(body.size(), writer.content_length(items));
  6390. auto res = cli.Post(
  6391. "/post", body.size(),
  6392. [&](size_t offset, size_t length, DataSink &sink) {
  6393. sink.write(body.data() + offset, length);
  6394. return true;
  6395. },
  6396. writer.content_type());
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ(StatusCode::OK_200, res->status);
  6399. }
  6400. }
  6401. TEST_F(ServerTest, PostContentReceiverGzip) {
  6402. cli_.set_compress(true);
  6403. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("content", res->body);
  6407. }
  6408. TEST_F(ServerTest, PutContentReceiver) {
  6409. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. ASSERT_EQ("content", res->body);
  6413. }
  6414. TEST_F(ServerTest, PatchContentReceiver) {
  6415. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. ASSERT_EQ(StatusCode::OK_200, res->status);
  6418. ASSERT_EQ("content", res->body);
  6419. }
  6420. template <typename ClientType>
  6421. void TestWithHeadersAndContentReceiver(
  6422. ClientType &cli,
  6423. std::function<Result(ClientType &, const std::string &, const Headers &,
  6424. const std::string &, const std::string &,
  6425. ContentReceiver, DownloadProgress)>
  6426. request_func) {
  6427. Headers headers;
  6428. headers.emplace("X-Custom-Header", "test-value");
  6429. std::string received_body;
  6430. auto res = request_func(
  6431. cli, "/content_receiver", headers, "content", "application/json",
  6432. [&](const char *data, size_t data_length) {
  6433. received_body.append(data, data_length);
  6434. return true;
  6435. },
  6436. nullptr);
  6437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6438. EXPECT_EQ(StatusCode::OK_200, res->status);
  6439. EXPECT_EQ("content", received_body);
  6440. }
  6441. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6442. #ifdef CPPHTTPLIB_SSL_ENABLED
  6443. using ClientT = SSLClient;
  6444. #else
  6445. using ClientT = Client;
  6446. #endif
  6447. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  6451. return cli.Post(path, headers, body, content_type, receiver, progress);
  6452. });
  6453. }
  6454. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6455. #ifdef CPPHTTPLIB_SSL_ENABLED
  6456. using ClientT = SSLClient;
  6457. #else
  6458. using ClientT = Client;
  6459. #endif
  6460. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  6464. return cli.Put(path, headers, body, content_type, receiver, progress);
  6465. });
  6466. }
  6467. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6468. #ifdef CPPHTTPLIB_SSL_ENABLED
  6469. using ClientT = SSLClient;
  6470. #else
  6471. using ClientT = Client;
  6472. #endif
  6473. TestWithHeadersAndContentReceiver<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, DownloadProgress progress) {
  6477. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6478. });
  6479. }
  6480. template <typename ClientType>
  6481. void TestWithHeadersAndContentReceiverWithProgress(
  6482. ClientType &cli,
  6483. std::function<Result(ClientType &, const std::string &, const Headers &,
  6484. const std::string &, const std::string &,
  6485. ContentReceiver, DownloadProgress)>
  6486. request_func) {
  6487. Headers headers;
  6488. headers.emplace("X-Test-Header", "progress-test");
  6489. std::string received_body;
  6490. auto progress_called = false;
  6491. auto res = request_func(
  6492. cli, "/content_receiver", headers, "content", "text/plain",
  6493. [&](const char *data, size_t data_length) {
  6494. received_body.append(data, data_length);
  6495. return true;
  6496. },
  6497. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6498. progress_called = true;
  6499. return true;
  6500. });
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. EXPECT_EQ(StatusCode::OK_200, res->status);
  6503. EXPECT_EQ("content", received_body);
  6504. EXPECT_TRUE(progress_called);
  6505. }
  6506. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6507. #ifdef CPPHTTPLIB_SSL_ENABLED
  6508. using ClientT = SSLClient;
  6509. #else
  6510. using ClientT = Client;
  6511. #endif
  6512. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6513. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6514. const std::string &body, const std::string &content_type,
  6515. ContentReceiver receiver, DownloadProgress progress) {
  6516. return cli.Post(path, headers, body, content_type, receiver, progress);
  6517. });
  6518. }
  6519. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6520. #ifdef CPPHTTPLIB_SSL_ENABLED
  6521. using ClientT = SSLClient;
  6522. #else
  6523. using ClientT = Client;
  6524. #endif
  6525. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6526. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6527. const std::string &body, const std::string &content_type,
  6528. ContentReceiver receiver, DownloadProgress progress) {
  6529. return cli.Put(path, headers, body, content_type, receiver, progress);
  6530. });
  6531. }
  6532. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6533. #ifdef CPPHTTPLIB_SSL_ENABLED
  6534. using ClientT = SSLClient;
  6535. #else
  6536. using ClientT = Client;
  6537. #endif
  6538. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6539. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6540. const std::string &body, const std::string &content_type,
  6541. ContentReceiver receiver, DownloadProgress progress) {
  6542. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6543. });
  6544. }
  6545. template <typename ClientType>
  6546. void TestWithHeadersAndContentReceiverError(
  6547. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6548. const Headers &, const std::string &,
  6549. const std::string &, ContentReceiver)>
  6550. request_func) {
  6551. Headers headers;
  6552. headers.emplace("X-Error-Test", "true");
  6553. std::string received_body;
  6554. auto receiver_failed = false;
  6555. auto res =
  6556. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6557. [&](const char *data, size_t data_length) {
  6558. received_body.append(data, data_length);
  6559. receiver_failed = true;
  6560. return false;
  6561. });
  6562. ASSERT_FALSE(res);
  6563. EXPECT_TRUE(receiver_failed);
  6564. }
  6565. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6566. #ifdef CPPHTTPLIB_SSL_ENABLED
  6567. using ClientT = SSLClient;
  6568. #else
  6569. using ClientT = Client;
  6570. #endif
  6571. TestWithHeadersAndContentReceiverError<ClientT>(
  6572. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6573. const std::string &body, const std::string &content_type,
  6574. ContentReceiver receiver) {
  6575. return cli.Post(path, headers, body, content_type, receiver);
  6576. });
  6577. }
  6578. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6579. #ifdef CPPHTTPLIB_SSL_ENABLED
  6580. using ClientT = SSLClient;
  6581. #else
  6582. using ClientT = Client;
  6583. #endif
  6584. TestWithHeadersAndContentReceiverError<ClientT>(
  6585. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6586. const std::string &body, const std::string &content_type,
  6587. ContentReceiver receiver) {
  6588. return cli.Put(path, headers, body, content_type, receiver);
  6589. });
  6590. }
  6591. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6592. #ifdef CPPHTTPLIB_SSL_ENABLED
  6593. using ClientT = SSLClient;
  6594. #else
  6595. using ClientT = Client;
  6596. #endif
  6597. TestWithHeadersAndContentReceiverError<ClientT>(
  6598. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6599. const std::string &body, const std::string &content_type,
  6600. ContentReceiver receiver) {
  6601. return cli.Patch(path, headers, body, content_type, receiver);
  6602. });
  6603. }
  6604. TEST_F(ServerTest, PostQueryStringAndBody) {
  6605. auto res =
  6606. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. ASSERT_EQ(StatusCode::OK_200, res->status);
  6609. }
  6610. TEST_F(ServerTest, HTTP2Magic) {
  6611. Request req;
  6612. req.method = "PRI";
  6613. req.path = "*";
  6614. req.body = "SM";
  6615. auto res = std::make_shared<Response>();
  6616. auto error = Error::Success;
  6617. auto ret = cli_.send(req, *res, error);
  6618. ASSERT_TRUE(ret);
  6619. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6620. }
  6621. TEST_F(ServerTest, KeepAlive) {
  6622. auto res = cli_.Get("/hi");
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. EXPECT_EQ(StatusCode::OK_200, res->status);
  6625. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6626. EXPECT_EQ("Hello World!", res->body);
  6627. res = cli_.Get("/hi");
  6628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6629. EXPECT_EQ(StatusCode::OK_200, res->status);
  6630. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6631. EXPECT_EQ("Hello World!", res->body);
  6632. res = cli_.Get("/hi");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6636. EXPECT_EQ("Hello World!", res->body);
  6637. res = cli_.Get("/not-exist");
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6640. res = cli_.Post("/empty", "", "text/plain");
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. EXPECT_EQ(StatusCode::OK_200, res->status);
  6643. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6644. EXPECT_EQ("empty", res->body);
  6645. EXPECT_EQ("close", res->get_header_value("Connection"));
  6646. res = cli_.Post(
  6647. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6648. "text/plain");
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6652. EXPECT_EQ("empty", res->body);
  6653. cli_.set_keep_alive(false);
  6654. res = cli_.Get("/last-request");
  6655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. EXPECT_EQ("close", res->get_header_value("Connection"));
  6658. }
  6659. TEST_F(ServerTest, TooManyRedirect) {
  6660. cli_.set_follow_location(true);
  6661. auto res = cli_.Get("/redirect/0");
  6662. ASSERT_TRUE(!res);
  6663. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6664. }
  6665. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6666. Request req;
  6667. req.method = "FOOBAR";
  6668. req.path = "/hi";
  6669. cli_.set_keep_alive(true);
  6670. auto res = cli_.send(req);
  6671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6672. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6673. EXPECT_EQ("close", res->get_header_value("Connection"));
  6674. EXPECT_FALSE(cli_.is_socket_open());
  6675. }
  6676. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6677. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6678. TEST_F(ServerTest, Gzip) {
  6679. Headers headers;
  6680. headers.emplace("Accept-Encoding", "gzip, deflate");
  6681. auto res = cli_.Get("/compress", headers);
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6684. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6685. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6686. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6687. "7890123456789012345678901234567890",
  6688. res->body);
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. }
  6691. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6692. Headers headers;
  6693. headers.emplace("Accept-Encoding", "gzip, deflate");
  6694. auto res = cli_.Get("/compress-with-charset", headers);
  6695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6697. EXPECT_EQ("application/json; charset=utf-8",
  6698. res->get_header_value("Content-Type"));
  6699. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6700. "7890123456789012345678901234567890",
  6701. res->body);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. }
  6704. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6705. Headers headers;
  6706. headers.emplace("Accept-Encoding", "");
  6707. auto res = cli_.Get("/compress", headers);
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6711. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6712. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6713. "7890123456789012345678901234567890",
  6714. res->body);
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. }
  6717. TEST_F(ServerTest, GzipWithContentReceiver) {
  6718. Headers headers;
  6719. headers.emplace("Accept-Encoding", "gzip, deflate");
  6720. std::string body;
  6721. auto res = cli_.Get("/compress", headers,
  6722. [&](const char *data, uint64_t data_length) {
  6723. EXPECT_EQ(100U, data_length);
  6724. body.append(data, data_length);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6730. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6731. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6732. "7890123456789012345678901234567890",
  6733. body);
  6734. EXPECT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6737. Headers headers;
  6738. headers.emplace("Accept-Encoding", "gzip, deflate");
  6739. cli_.set_decompress(false);
  6740. auto res = cli_.Get("/compress", headers);
  6741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6744. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6745. EXPECT_EQ(33U, res->body.size());
  6746. EXPECT_EQ(StatusCode::OK_200, res->status);
  6747. }
  6748. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6749. Headers headers;
  6750. headers.emplace("Accept-Encoding", "");
  6751. std::string body;
  6752. auto res = cli_.Get("/compress", headers,
  6753. [&](const char *data, uint64_t data_length) {
  6754. EXPECT_EQ(100U, data_length);
  6755. body.append(data, data_length);
  6756. return true;
  6757. });
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6761. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6762. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6763. "7890123456789012345678901234567890",
  6764. body);
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. }
  6767. TEST_F(ServerTest, NoGzip) {
  6768. Headers headers;
  6769. headers.emplace("Accept-Encoding", "gzip, deflate");
  6770. auto res = cli_.Get("/nocompress", headers);
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6773. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6774. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6775. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6776. "7890123456789012345678901234567890",
  6777. res->body);
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. }
  6780. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6781. Headers headers;
  6782. headers.emplace("Accept-Encoding", "gzip, deflate");
  6783. std::string body;
  6784. auto res = cli_.Get("/nocompress", headers,
  6785. [&](const char *data, uint64_t data_length) {
  6786. EXPECT_EQ(100U, data_length);
  6787. body.append(data, data_length);
  6788. return true;
  6789. });
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6792. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6793. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6795. "7890123456789012345678901234567890",
  6796. body);
  6797. EXPECT_EQ(StatusCode::OK_200, res->status);
  6798. }
  6799. TEST_F(ServerTest, MultipartFormDataGzip) {
  6800. UploadFormDataItems items = {
  6801. {"key1", "test", "", ""},
  6802. {"key2", "--abcdefg123", "", ""},
  6803. };
  6804. cli_.set_compress(true);
  6805. auto res = cli_.Post("/compress-multipart", items);
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. }
  6809. #endif
  6810. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6811. TEST_F(ServerTest, Brotli) {
  6812. Headers headers;
  6813. headers.emplace("Accept-Encoding", "br");
  6814. auto res = cli_.Get("/compress", headers);
  6815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6816. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6817. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6818. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6819. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6820. "7890123456789012345678901234567890",
  6821. res->body);
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. }
  6824. #endif
  6825. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6826. TEST_F(ServerTest, Zstd) {
  6827. Headers headers;
  6828. headers.emplace("Accept-Encoding", "zstd");
  6829. auto res = cli_.Get("/compress", headers);
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6832. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6833. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6834. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6835. "7890123456789012345678901234567890",
  6836. res->body);
  6837. EXPECT_EQ(StatusCode::OK_200, res->status);
  6838. }
  6839. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6840. Headers headers;
  6841. headers.emplace("Accept-Encoding", "");
  6842. auto res = cli_.Get("/compress", headers);
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6847. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6848. "7890123456789012345678901234567890",
  6849. res->body);
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. }
  6852. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6853. Headers headers;
  6854. headers.emplace("Accept-Encoding", "zstd");
  6855. std::string body;
  6856. auto res = cli_.Get("/compress", headers,
  6857. [&](const char *data, uint64_t data_length) {
  6858. EXPECT_EQ(100U, data_length);
  6859. body.append(data, data_length);
  6860. return true;
  6861. });
  6862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6863. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6865. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6866. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6867. "7890123456789012345678901234567890",
  6868. body);
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. }
  6871. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6872. Headers headers;
  6873. headers.emplace("Accept-Encoding", "zstd");
  6874. cli_.set_decompress(false);
  6875. auto res = cli_.Get("/compress", headers);
  6876. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6877. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6878. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6879. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6883. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(StatusCode::OK_200, res->status);
  6885. ASSERT_EQ(26U, res->body.size());
  6886. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6887. 0);
  6888. }
  6889. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6890. Headers headers;
  6891. headers.emplace("Accept-Encoding", "");
  6892. std::string body;
  6893. auto res = cli_.Get("/compress", headers,
  6894. [&](const char *data, uint64_t data_length) {
  6895. EXPECT_EQ(100U, data_length);
  6896. body.append(data, data_length);
  6897. return true;
  6898. });
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6902. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6903. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6904. "7890123456789012345678901234567890",
  6905. body);
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. TEST_F(ServerTest, NoZstd) {
  6909. Headers headers;
  6910. headers.emplace("Accept-Encoding", "zstd");
  6911. auto res = cli_.Get("/nocompress", headers);
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6914. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6915. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6916. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6917. "7890123456789012345678901234567890",
  6918. res->body);
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. }
  6921. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6922. Headers headers;
  6923. headers.emplace("Accept-Encoding", "zstd");
  6924. std::string body;
  6925. auto res = cli_.Get("/nocompress", headers,
  6926. [&](const char *data, uint64_t data_length) {
  6927. EXPECT_EQ(100U, data_length);
  6928. body.append(data, data_length);
  6929. return true;
  6930. });
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6933. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6934. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6936. "7890123456789012345678901234567890",
  6937. body);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. }
  6940. // TODO: How to enable zstd ??
  6941. TEST_F(ServerTest, MultipartFormDataZstd) {
  6942. UploadFormDataItems items = {
  6943. {"key1", "test", "", ""},
  6944. {"key2", "--abcdefg123", "", ""},
  6945. };
  6946. Headers headers;
  6947. headers.emplace("Accept-Encoding", "zstd");
  6948. cli_.set_compress(true);
  6949. auto res = cli_.Post("/compress-multipart", headers, items);
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(StatusCode::OK_200, res->status);
  6952. }
  6953. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6954. Headers headers;
  6955. headers.emplace("Accept-Encoding", "zstd");
  6956. cli_.set_compress(true);
  6957. auto res = cli_.Put(
  6958. "/put", headers, 3,
  6959. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6960. sink.os << "PUT";
  6961. return true;
  6962. },
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. EXPECT_EQ("PUT", res->body);
  6967. }
  6968. // Pre-compression logging tests
  6969. TEST_F(ServerTest, PreCompressionLogging) {
  6970. // Test data for compression (matches the actual /compress endpoint content)
  6971. const std::string test_content =
  6972. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6973. "3456789012345678901234567890";
  6974. // Variables to capture logging data
  6975. std::string pre_compression_body;
  6976. std::string pre_compression_content_type;
  6977. std::string pre_compression_content_encoding;
  6978. std::string post_compression_body;
  6979. std::string post_compression_content_type;
  6980. std::string post_compression_content_encoding;
  6981. // Set up pre-compression logger
  6982. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6983. const Response &res) {
  6984. pre_compression_body = res.body;
  6985. pre_compression_content_type = res.get_header_value("Content-Type");
  6986. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6987. });
  6988. // Set up post-compression logger
  6989. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6990. post_compression_body = res.body;
  6991. post_compression_content_type = res.get_header_value("Content-Type");
  6992. post_compression_content_encoding =
  6993. res.get_header_value("Content-Encoding");
  6994. });
  6995. // Test with gzip compression
  6996. Headers headers;
  6997. headers.emplace("Accept-Encoding", "gzip");
  6998. auto res = cli_.Get("/compress", headers);
  6999. // Verify response was compressed
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. EXPECT_EQ(StatusCode::OK_200, res->status);
  7002. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7003. // Verify pre-compression logger captured uncompressed content
  7004. EXPECT_EQ(test_content, pre_compression_body);
  7005. EXPECT_EQ("text/plain", pre_compression_content_type);
  7006. EXPECT_TRUE(pre_compression_content_encoding
  7007. .empty()); // No encoding header before compression
  7008. // Verify post-compression logger captured compressed content
  7009. EXPECT_NE(test_content,
  7010. post_compression_body); // Should be different after compression
  7011. EXPECT_EQ("text/plain", post_compression_content_type);
  7012. EXPECT_EQ("gzip", post_compression_content_encoding);
  7013. // Verify compressed content is smaller
  7014. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7015. }
  7016. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7017. const std::string test_content =
  7018. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7019. "3456789012345678901234567890";
  7020. std::string pre_compression_body;
  7021. std::string post_compression_body;
  7022. svr_.set_pre_compression_logger(
  7023. [&](const Request & /*req*/, const Response &res) {
  7024. pre_compression_body = res.body;
  7025. });
  7026. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7027. post_compression_body = res.body;
  7028. });
  7029. Headers headers;
  7030. headers.emplace("Accept-Encoding", "br");
  7031. auto res = cli_.Get("/compress", headers);
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. EXPECT_EQ(StatusCode::OK_200, res->status);
  7034. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7035. // Verify pre-compression content is uncompressed
  7036. EXPECT_EQ(test_content, pre_compression_body);
  7037. // Verify post-compression content is compressed
  7038. EXPECT_NE(test_content, post_compression_body);
  7039. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7040. }
  7041. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7042. const std::string test_content =
  7043. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7044. "3456789012345678901234567890";
  7045. std::string pre_compression_body;
  7046. std::string post_compression_body;
  7047. svr_.set_pre_compression_logger(
  7048. [&](const Request & /*req*/, const Response &res) {
  7049. pre_compression_body = res.body;
  7050. });
  7051. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7052. post_compression_body = res.body;
  7053. });
  7054. // Request without compression (use /nocompress endpoint)
  7055. Headers headers;
  7056. auto res = cli_.Get("/nocompress", headers);
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7060. // Pre-compression logger should not be called when no compression is applied
  7061. EXPECT_TRUE(
  7062. pre_compression_body.empty()); // Pre-compression logger not called
  7063. EXPECT_EQ(
  7064. test_content,
  7065. post_compression_body); // Post-compression logger captures final content
  7066. }
  7067. TEST_F(ServerTest, LoggerSeesContentLength) {
  7068. size_t logged_content_length = 0;
  7069. std::string logged_content_length_header;
  7070. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7071. logged_content_length = res.content_length_;
  7072. logged_content_length_header = res.get_header_value("Content-Length");
  7073. });
  7074. auto res = cli_.Get("/nocompress");
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::OK_200, res->status);
  7077. EXPECT_EQ(res->body.size(), logged_content_length);
  7078. EXPECT_EQ(std::to_string(logged_content_length),
  7079. logged_content_length_header);
  7080. }
  7081. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7082. const std::string test_content =
  7083. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7084. "3456789012345678901234567890";
  7085. std::string pre_compression_body;
  7086. bool pre_logger_called = false;
  7087. // Set only pre-compression logger
  7088. svr_.set_pre_compression_logger(
  7089. [&](const Request & /*req*/, const Response &res) {
  7090. pre_compression_body = res.body;
  7091. pre_logger_called = true;
  7092. });
  7093. Headers headers;
  7094. headers.emplace("Accept-Encoding", "gzip");
  7095. auto res = cli_.Get("/compress", headers);
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::OK_200, res->status);
  7098. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7099. // Verify pre-compression logger was called
  7100. EXPECT_TRUE(pre_logger_called);
  7101. EXPECT_EQ(test_content, pre_compression_body);
  7102. }
  7103. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7104. {
  7105. // Test with Expect: 100-continue header - success case
  7106. // Server returns 100 Continue, client sends body, server returns 200 OK
  7107. Request req;
  7108. req.method = "POST";
  7109. req.path = "/post-large";
  7110. req.set_header("Expect", "100-continue");
  7111. req.body = LARGE_DATA;
  7112. Response res;
  7113. auto error = Error::Success;
  7114. cli_.set_keep_alive(true);
  7115. auto ret = cli_.send(req, res, error);
  7116. EXPECT_TRUE(ret);
  7117. EXPECT_EQ(StatusCode::OK_200, res.status);
  7118. EXPECT_EQ(LARGE_DATA, res.body);
  7119. }
  7120. {
  7121. // Test with Expect: 100-continue header - error case
  7122. // Client should not send the body when server returns an error
  7123. Request req;
  7124. req.method = "POST";
  7125. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7126. req.set_header("Expect", "100-continue");
  7127. req.body = LARGE_DATA;
  7128. Response res;
  7129. auto error = Error::Success;
  7130. auto start = std::chrono::high_resolution_clock::now();
  7131. cli_.set_keep_alive(true);
  7132. auto ret = cli_.send(req, res, error);
  7133. auto end = std::chrono::high_resolution_clock::now();
  7134. auto elapsed =
  7135. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7136. .count();
  7137. // With Expect: 100-continue, request completes successfully but with error
  7138. EXPECT_TRUE(ret);
  7139. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7140. EXPECT_EQ("close", res.get_header_value("Connection"));
  7141. EXPECT_FALSE(cli_.is_socket_open());
  7142. EXPECT_LE(elapsed, 2000);
  7143. }
  7144. {
  7145. // Send an extra GET request to ensure error recovery without hanging
  7146. Request req;
  7147. req.method = "GET";
  7148. req.path = "/hi";
  7149. auto start = std::chrono::high_resolution_clock::now();
  7150. auto res = cli_.send(req);
  7151. auto end = std::chrono::high_resolution_clock::now();
  7152. auto elapsed =
  7153. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7154. .count();
  7155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7156. EXPECT_EQ(StatusCode::OK_200, res->status);
  7157. EXPECT_EQ("Hello World!", res->body);
  7158. EXPECT_LE(elapsed, 500);
  7159. }
  7160. }
  7161. TEST(ZstdDecompressor, ChunkedDecompression) {
  7162. std::string data;
  7163. for (size_t i = 0; i < 32 * 1024; ++i) {
  7164. data.push_back(static_cast<char>('a' + i % 26));
  7165. }
  7166. std::string compressed_data;
  7167. {
  7168. httplib::detail::zstd_compressor compressor;
  7169. bool result = compressor.compress(
  7170. data.data(), data.size(),
  7171. /*last=*/true,
  7172. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7173. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7174. compressed_data_size);
  7175. return true;
  7176. });
  7177. ASSERT_TRUE(result);
  7178. }
  7179. std::string decompressed_data;
  7180. {
  7181. httplib::detail::zstd_decompressor decompressor;
  7182. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7183. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7184. size_t chunk_size = 130;
  7185. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7186. chunk_begin += chunk_size) {
  7187. size_t current_chunk_size =
  7188. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7189. bool result = decompressor.decompress(
  7190. compressed_data.data() + chunk_begin, current_chunk_size,
  7191. [&](const char *decompressed_data_chunk,
  7192. size_t decompressed_data_chunk_size) {
  7193. decompressed_data.insert(decompressed_data.size(),
  7194. decompressed_data_chunk,
  7195. decompressed_data_chunk_size);
  7196. return true;
  7197. });
  7198. ASSERT_TRUE(result);
  7199. }
  7200. }
  7201. ASSERT_EQ(data, decompressed_data);
  7202. }
  7203. TEST(ZstdDecompressor, Decompress) {
  7204. std::string original_text = "Compressed with ZSTD";
  7205. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7206. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7207. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7208. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7209. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7210. std::string decompressed_data;
  7211. {
  7212. httplib::detail::zstd_decompressor decompressor;
  7213. bool result = decompressor.decompress(
  7214. compressed_data.data(), compressed_data.size(),
  7215. [&](const char *decompressed_data_chunk,
  7216. size_t decompressed_data_chunk_size) {
  7217. decompressed_data.insert(decompressed_data.size(),
  7218. decompressed_data_chunk,
  7219. decompressed_data_chunk_size);
  7220. return true;
  7221. });
  7222. ASSERT_TRUE(result);
  7223. }
  7224. ASSERT_EQ(original_text, decompressed_data);
  7225. }
  7226. #endif
  7227. // Sends a raw request to a server listening at HOST:PORT.
  7228. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7229. std::string *resp = nullptr) {
  7230. auto error = Error::Success;
  7231. auto client_sock = detail::create_client_socket(
  7232. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  7233. /*connection_timeout_sec=*/5, 0,
  7234. /*read_timeout_sec=*/5, 0,
  7235. /*write_timeout_sec=*/5, 0, std::string(), error);
  7236. if (client_sock == INVALID_SOCKET) { return false; }
  7237. auto ret = detail::process_client_socket(
  7238. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7239. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7240. if (req.size() !=
  7241. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7242. return false;
  7243. }
  7244. char buf[512];
  7245. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7246. while (line_reader.getline()) {
  7247. if (resp) { *resp += line_reader.ptr(); }
  7248. }
  7249. return true;
  7250. });
  7251. detail::close_socket(client_sock);
  7252. return ret;
  7253. }
  7254. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7255. Server svr;
  7256. std::string header_value;
  7257. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7258. header_value = req.get_header_value("foo");
  7259. res.set_content("ok", "text/plain");
  7260. });
  7261. thread t = thread([&] { svr.listen(HOST, PORT); });
  7262. auto se = detail::scope_exit([&] {
  7263. svr.stop();
  7264. t.join();
  7265. ASSERT_FALSE(svr.is_running());
  7266. });
  7267. svr.wait_until_ready();
  7268. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7269. // like characters are not treated the same - use vertical tab and escape.
  7270. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7271. "foo: \t \v bar \x1B\t \r\n"
  7272. "Connection: close\r\n"
  7273. "\r\n";
  7274. std::string res;
  7275. ASSERT_TRUE(send_request(5, req, &res));
  7276. EXPECT_EQ(header_value, "");
  7277. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7278. }
  7279. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7280. Server svr;
  7281. std::string received;
  7282. svr.Get("/order", [&](const Request &req, Response &res) {
  7283. received = entries_to_string(req.headers);
  7284. res.set_content("ok", "text/plain");
  7285. });
  7286. thread t = thread([&] { svr.listen(HOST, PORT); });
  7287. auto se = detail::scope_exit([&] {
  7288. svr.stop();
  7289. t.join();
  7290. ASSERT_FALSE(svr.is_running());
  7291. });
  7292. svr.wait_until_ready();
  7293. const std::string req = "GET /order HTTP/1.1\r\n"
  7294. "X-First: 1\r\n"
  7295. "X-Dup: a\r\n"
  7296. "X-Second: 2\r\n"
  7297. "X-Dup: b\r\n"
  7298. "Connection: close\r\n"
  7299. "\r\n";
  7300. std::string res;
  7301. ASSERT_TRUE(send_request(5, req, &res));
  7302. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7303. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7304. }
  7305. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7306. Server svr;
  7307. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7308. res.set_header("Set-Cookie", "first=1");
  7309. res.set_header("X-Between", "y");
  7310. res.set_header("Set-Cookie", "second=2");
  7311. res.set_content("ok", "text/plain");
  7312. });
  7313. thread t = thread([&] { svr.listen(HOST, PORT); });
  7314. auto se = detail::scope_exit([&] {
  7315. svr.stop();
  7316. t.join();
  7317. ASSERT_FALSE(svr.is_running());
  7318. });
  7319. svr.wait_until_ready();
  7320. Client cli(HOST, PORT);
  7321. auto res = cli.Get("/cookies");
  7322. ASSERT_TRUE(res);
  7323. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7324. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7325. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7326. }
  7327. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7328. Server svr;
  7329. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7330. auto i = new int(0);
  7331. res.set_header("Trailer", "X-Safe, X-Reflected");
  7332. res.set_chunked_content_provider(
  7333. "text/plain",
  7334. [i](size_t /*offset*/, DataSink &sink) {
  7335. if (*i == 0) {
  7336. sink.os << "body";
  7337. } else {
  7338. Headers trailer;
  7339. // A valid trailer that must survive.
  7340. trailer.emplace("X-Safe", "safe");
  7341. // Attacker-controlled value carrying CR/LF (response splitting).
  7342. trailer.emplace("X-Reflected",
  7343. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7344. // Attacker-controlled name carrying CR/LF.
  7345. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7346. sink.done_with_trailer(trailer);
  7347. }
  7348. (*i)++;
  7349. return true;
  7350. },
  7351. [i](bool /*success*/) { delete i; });
  7352. });
  7353. thread t = thread([&] { svr.listen(HOST, PORT); });
  7354. auto se = detail::scope_exit([&] {
  7355. svr.stop();
  7356. t.join();
  7357. ASSERT_FALSE(svr.is_running());
  7358. });
  7359. svr.wait_until_ready();
  7360. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7361. "Host: " + HOST +
  7362. "\r\n"
  7363. "Connection: close\r\n"
  7364. "\r\n";
  7365. std::string res;
  7366. ASSERT_TRUE(send_request(5, req, &res));
  7367. // The injected fields must not appear anywhere in the raw response.
  7368. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7369. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7370. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7371. // Invalid trailers are dropped entirely, matching set_header().
  7372. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7373. // The valid trailer still passes through.
  7374. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7375. }
  7376. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7377. Server svr;
  7378. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7379. // res.headers is a public field an application can populate directly,
  7380. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7381. // A valid header that must survive.
  7382. res.headers.emplace("X-Safe", "safe");
  7383. // Attacker-controlled value carrying CR/LF (response splitting).
  7384. res.headers.emplace("X-Reflected",
  7385. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7386. // Attacker-controlled name carrying CR/LF.
  7387. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7388. res.set_content("body", "text/plain");
  7389. });
  7390. thread t = thread([&] { svr.listen(HOST, PORT); });
  7391. auto se = detail::scope_exit([&] {
  7392. svr.stop();
  7393. t.join();
  7394. ASSERT_FALSE(svr.is_running());
  7395. });
  7396. svr.wait_until_ready();
  7397. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7398. "Host: " + HOST +
  7399. "\r\n"
  7400. "Connection: close\r\n"
  7401. "\r\n";
  7402. std::string res;
  7403. ASSERT_TRUE(send_request(5, req, &res));
  7404. // The injected fields must not appear anywhere in the raw response.
  7405. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7406. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7407. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7408. // Invalid headers are dropped entirely, matching set_header().
  7409. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7410. // The valid header still passes through.
  7411. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7412. }
  7413. // Forward declaration: in split builds split.py strips `inline` and moves the
  7414. // definition into httplib.cc, so detail::write_request_line is not visible from
  7415. // the public httplib.h. Re-declaring it here lets the tests link against the
  7416. // symbol in both header-only and split builds.
  7417. namespace httplib {
  7418. namespace detail {
  7419. ssize_t write_request_line(Stream &strm, const std::string &method,
  7420. const std::string &path);
  7421. } // namespace detail
  7422. } // namespace httplib
  7423. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7424. // A well-formed target is written verbatim.
  7425. {
  7426. detail::BufferStream strm;
  7427. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7428. EXPECT_GT(n, 0);
  7429. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7430. }
  7431. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7432. // otherwise it splits the request line and injects a header or a whole
  7433. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7434. // when path encoding is disabled.
  7435. const std::string evil_targets[] = {
  7436. "/a\r\nInjected: pwned",
  7437. "/a\rInjected",
  7438. "/a\nInjected",
  7439. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7440. };
  7441. for (const auto &evil : evil_targets) {
  7442. detail::BufferStream strm;
  7443. auto n = detail::write_request_line(strm, "GET", evil);
  7444. EXPECT_LT(n, 0);
  7445. EXPECT_TRUE(strm.get_buffer().empty());
  7446. }
  7447. }
  7448. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7449. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7450. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7451. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7452. // client must fail cleanly with Error::Write instead of putting a
  7453. // request-line-less, header-injecting request on the wire.
  7454. Server svr;
  7455. svr.Get("/a", [](const Request &, Response &res) {
  7456. res.set_content("ok", "text/plain");
  7457. });
  7458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7459. auto se = detail::scope_exit([&] {
  7460. svr.stop();
  7461. thread.join();
  7462. ASSERT_FALSE(svr.is_running());
  7463. });
  7464. svr.wait_until_ready();
  7465. {
  7466. Client cli(HOST, PORT);
  7467. cli.set_path_encode(false);
  7468. // The request is rejected before anything is written, so the connection
  7469. // stays silent and the subsequent response read would otherwise block for
  7470. // the full default read timeout. Shorten it -- the assertion is on the
  7471. // error, not the timeout.
  7472. cli.set_read_timeout(1, 0);
  7473. auto res = cli.Get("/a\r\nInjected: pwned");
  7474. EXPECT_FALSE(res);
  7475. EXPECT_EQ(Error::Write, res.error());
  7476. }
  7477. }
  7478. // Sends a raw request and verifies that there isn't a crash or exception.
  7479. static void test_raw_request(const std::string &req,
  7480. std::string *out = nullptr) {
  7481. Server svr;
  7482. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7483. res.set_content("ok", "text/plain");
  7484. });
  7485. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7486. res.set_content("ok", "text/plain");
  7487. });
  7488. svr.Get("/header_field_value_check",
  7489. [&](const Request & /*req*/, Response &res) {
  7490. res.set_content("ok", "text/plain");
  7491. });
  7492. // Server read timeout must be longer than the client read timeout for the
  7493. // bug to reproduce, probably to force the server to process a request
  7494. // without a trailing blank line.
  7495. const time_t client_read_timeout_sec = 1;
  7496. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7497. bool listen_thread_ok = false;
  7498. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7499. auto se = detail::scope_exit([&] {
  7500. svr.stop();
  7501. t.join();
  7502. ASSERT_FALSE(svr.is_running());
  7503. EXPECT_TRUE(listen_thread_ok);
  7504. });
  7505. svr.wait_until_ready();
  7506. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7507. }
  7508. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7509. // A certain header line causes an exception if the header property is parsed
  7510. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7511. test_raw_request(
  7512. "GET /hi HTTP/1.1\r\n"
  7513. " : "
  7514. " "
  7515. " ");
  7516. }
  7517. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7518. // A certain header line causes an exception if the header property *name* is
  7519. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7520. // greedy matcher and requires backtracking when there are a lot of ":"
  7521. // characters.
  7522. // This occurs with libc++ but not libstdc++.
  7523. test_raw_request(
  7524. "GET /hi HTTP/1.1\r\n"
  7525. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7526. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7527. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7528. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7529. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7530. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7531. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7532. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7533. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7534. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7535. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7536. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7537. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7538. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7539. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7540. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7541. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7542. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7543. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7544. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7545. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7546. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7547. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7548. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7549. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7550. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7551. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7552. "&&&%%%");
  7553. }
  7554. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7555. // Make sure this doesn't crash the server.
  7556. // In a previous version of the header line regex, the "\r" rendered the line
  7557. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7558. // a new position where the leading white space ended and the field value
  7559. // began.
  7560. // The crash occurs with libc++ but not libstdc++.
  7561. test_raw_request("GET /hi HTTP/1.1\r\n"
  7562. "a:" +
  7563. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7564. "\r\n"
  7565. "\r\n");
  7566. }
  7567. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7568. std::string out;
  7569. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7570. "Content-Type: text/plain\r\n"
  7571. "Transfer-Encoding: chunked\r\n"
  7572. "\r\n"
  7573. "nothex\r\n",
  7574. &out);
  7575. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7576. }
  7577. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7578. std::string out;
  7579. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7580. "Content-Type: text/plain\r\n"
  7581. "Transfer-Encoding: chunked\r\n"
  7582. "\r\n"
  7583. "3\r\n"
  7584. "xyz\r\n"
  7585. "NaN\r\n",
  7586. &out);
  7587. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7588. }
  7589. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7590. std::string out;
  7591. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7592. "Content-Type: text/plain\r\n"
  7593. "Transfer-Encoding: chunked\r\n"
  7594. "\r\n"
  7595. // Length is too large for 64 bits.
  7596. "1ffffffffffffffff\r\n"
  7597. "xyz\r\n",
  7598. &out);
  7599. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7600. }
  7601. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7602. test_raw_request("GET /hi HTTP/1.1\r\n"
  7603. "Content-Type: text/plain\r\n\r");
  7604. }
  7605. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7606. std::string out;
  7607. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7609. }
  7610. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7611. Server svr;
  7612. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7613. EXPECT_TRUE(!req.remote_addr.empty());
  7614. });
  7615. thread t = thread([&] { svr.listen(HOST, PORT); });
  7616. auto se = detail::scope_exit([&] {
  7617. svr.stop();
  7618. t.join();
  7619. ASSERT_FALSE(svr.is_running());
  7620. });
  7621. svr.wait_until_ready();
  7622. // Send an invalid request line to trigger Bad Request
  7623. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7624. std::string out;
  7625. ASSERT_TRUE(send_request(5, bad_req, &out));
  7626. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7627. }
  7628. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7629. std::string out;
  7630. std::string request(
  7631. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7632. test_raw_request(request, &out);
  7633. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7634. }
  7635. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7636. std::string out;
  7637. std::string request(
  7638. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7639. test_raw_request(request, &out);
  7640. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7641. }
  7642. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7643. std::string out;
  7644. std::string request(
  7645. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7646. test_raw_request(request, &out);
  7647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7648. }
  7649. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7650. std::string out;
  7651. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7652. "Test: \r\n\r\n",
  7653. &out);
  7654. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7655. }
  7656. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7657. Server svr;
  7658. std::string x_custom;
  7659. std::string cookie;
  7660. std::string xff;
  7661. std::string x_unicode;
  7662. std::string x_iis;
  7663. svr.Get("/check", [&](const Request &req, Response &res) {
  7664. x_custom = req.get_header_value("X-Custom");
  7665. cookie = req.get_header_value("Cookie");
  7666. xff = req.get_header_value("X-Forwarded-For");
  7667. x_unicode = req.get_header_value("X-Unicode");
  7668. x_iis = req.get_header_value("X-IIS");
  7669. res.set_content("ok", "text/plain");
  7670. });
  7671. thread t = thread([&] { svr.listen(HOST, PORT); });
  7672. auto se = detail::scope_exit([&] {
  7673. svr.stop();
  7674. t.join();
  7675. ASSERT_FALSE(svr.is_running());
  7676. });
  7677. svr.wait_until_ready();
  7678. const std::string req = "GET /check HTTP/1.1\r\n"
  7679. "Host: localhost\r\n"
  7680. "X-Custom: a%0D%0AInjected: b\r\n"
  7681. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7682. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7683. "X-Unicode: %E3%81%82\r\n"
  7684. "X-IIS: %u00E9\r\n"
  7685. "Connection: close\r\n"
  7686. "\r\n";
  7687. std::string res;
  7688. ASSERT_TRUE(send_request(5, req, &res));
  7689. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7690. // Every value must be returned verbatim (wire form), with no decoding.
  7691. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7692. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7693. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7694. EXPECT_EQ("%E3%81%82", x_unicode);
  7695. EXPECT_EQ("%u00E9", x_iis);
  7696. }
  7697. // Applications that previously relied on automatic percent-decoding can
  7698. // reproduce the old behavior by explicitly calling decode_path_component()
  7699. // or, for RFC 3986 conformance, decode_uri_component().
  7700. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7701. Server svr;
  7702. std::string decoded;
  7703. svr.Get("/check", [&](const Request &req, Response &res) {
  7704. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7705. res.set_content("ok", "text/plain");
  7706. });
  7707. thread t = thread([&] { svr.listen(HOST, PORT); });
  7708. auto se = detail::scope_exit([&] {
  7709. svr.stop();
  7710. t.join();
  7711. ASSERT_FALSE(svr.is_running());
  7712. });
  7713. svr.wait_until_ready();
  7714. const std::string req = "GET /check HTTP/1.1\r\n"
  7715. "Host: localhost\r\n"
  7716. "X-Custom: hello%20world\r\n"
  7717. "Connection: close\r\n"
  7718. "\r\n";
  7719. std::string res;
  7720. ASSERT_TRUE(send_request(5, req, &res));
  7721. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7722. EXPECT_EQ("hello world", decoded);
  7723. }
  7724. // Regression test for #2033. Browsers send Referer values that include
  7725. // percent-encoded characters such as %0A inside the URL. Decoding the
  7726. // header value would either trip the post-decode CR/LF/NUL guard (the
  7727. // original bug, returning 400) or, after that guard was relaxed, silently
  7728. // store a literal LF — both unacceptable. The wire form must round-trip.
  7729. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7730. Server svr;
  7731. std::string referer;
  7732. svr.Get("/check", [&](const Request &req, Response &res) {
  7733. referer = req.get_header_value("Referer");
  7734. res.set_content("ok", "text/plain");
  7735. });
  7736. thread t = thread([&] { svr.listen(HOST, PORT); });
  7737. auto se = detail::scope_exit([&] {
  7738. svr.stop();
  7739. t.join();
  7740. ASSERT_FALSE(svr.is_running());
  7741. });
  7742. svr.wait_until_ready();
  7743. const std::string req = "GET /check HTTP/1.1\r\n"
  7744. "Host: localhost\r\n"
  7745. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7746. "Connection: close\r\n"
  7747. "\r\n";
  7748. std::string res;
  7749. ASSERT_TRUE(send_request(5, req, &res));
  7750. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7751. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7752. }
  7753. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7754. Server svr;
  7755. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7756. res.set_header("Cache-Control", "no-cache");
  7757. res.set_chunked_content_provider(
  7758. "text/event-stream", [](size_t offset, DataSink &sink) {
  7759. std::string s = "data:";
  7760. s += std::to_string(offset);
  7761. s += "\n\n";
  7762. auto ret = sink.write(s.data(), s.size());
  7763. EXPECT_TRUE(ret);
  7764. std::this_thread::sleep_for(std::chrono::seconds(1));
  7765. return true;
  7766. });
  7767. });
  7768. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7769. svr.wait_until_ready();
  7770. Client client(HOST, PORT);
  7771. const Headers headers = {{"Accept", "text/event-stream"}};
  7772. auto get_thread = std::thread([&client, &headers]() {
  7773. auto res = client.Get(
  7774. "/events", headers,
  7775. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7776. });
  7777. auto se = detail::scope_exit([&] {
  7778. svr.stop();
  7779. get_thread.join();
  7780. listen_thread.join();
  7781. ASSERT_FALSE(svr.is_running());
  7782. });
  7783. // Give GET time to get a few messages.
  7784. std::this_thread::sleep_for(std::chrono::seconds(2));
  7785. }
  7786. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7787. httplib::Server svr;
  7788. svr.Post("/hi",
  7789. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7790. res.status = StatusCode::OK_200;
  7791. });
  7792. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7793. svr.wait_until_ready();
  7794. Client cli(HOST, PORT);
  7795. auto res = cli.Post("/hi", "data", "text/plain");
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. svr.stop();
  7799. thread.join();
  7800. ASSERT_FALSE(svr.is_running());
  7801. res = cli.Post("/hi", "data", "text/plain");
  7802. ASSERT_FALSE(res);
  7803. }
  7804. TEST(ServerStopTest, ListenFailure) {
  7805. Server svr;
  7806. auto t = thread([&]() {
  7807. auto ret = svr.listen("????", PORT);
  7808. EXPECT_FALSE(ret);
  7809. });
  7810. svr.wait_until_ready();
  7811. svr.stop();
  7812. t.join();
  7813. }
  7814. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7815. TEST(ServerStopTest, Decommision) {
  7816. Server svr;
  7817. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7818. for (int i = 0; i < 4; i++) {
  7819. auto is_even = !(i % 2);
  7820. std::thread t{[&] {
  7821. try {
  7822. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7823. if (is_even) {
  7824. throw std::runtime_error("Some thing that happens to go wrong.");
  7825. }
  7826. svr.listen(HOST, PORT);
  7827. } catch (...) { svr.decommission(); }
  7828. }};
  7829. svr.wait_until_ready();
  7830. // Server is up
  7831. {
  7832. Client cli(HOST, PORT);
  7833. auto res = cli.Get("/hi");
  7834. if (is_even) {
  7835. EXPECT_FALSE(res);
  7836. } else {
  7837. EXPECT_TRUE(res);
  7838. EXPECT_EQ("hi...", res->body);
  7839. }
  7840. }
  7841. svr.stop();
  7842. t.join();
  7843. // Server is down...
  7844. {
  7845. Client cli(HOST, PORT);
  7846. auto res = cli.Get("/hi");
  7847. EXPECT_FALSE(res);
  7848. }
  7849. }
  7850. }
  7851. #endif
  7852. // Helper function for string body upload progress tests
  7853. template <typename SetupHandler, typename ClientCall>
  7854. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7855. ClientCall &&client_call,
  7856. const string &body) {
  7857. Server svr;
  7858. setup_handler(svr);
  7859. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7860. auto se = detail::scope_exit([&] {
  7861. svr.stop();
  7862. t.join();
  7863. });
  7864. svr.wait_until_ready();
  7865. Client cli(HOST, PORT);
  7866. vector<uint64_t> progress_values;
  7867. bool progress_called = false;
  7868. auto res =
  7869. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7870. progress_values.push_back(current);
  7871. progress_called = true;
  7872. return true;
  7873. });
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(200, res->status);
  7876. EXPECT_TRUE(progress_called);
  7877. }
  7878. TEST(UploadProgressTest, PostStringBodyBasic) {
  7879. TestStringBodyUploadProgress(
  7880. [](Server &svr) {
  7881. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7882. res.set_content("received", "text/plain");
  7883. });
  7884. },
  7885. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7886. return cli.Post("/test", body, "text/plain", progress_callback);
  7887. },
  7888. "test data for upload progress");
  7889. }
  7890. TEST(UploadProgressTest, PutStringBodyBasic) {
  7891. TestStringBodyUploadProgress(
  7892. [](Server &svr) {
  7893. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7894. res.set_content("put received", "text/plain");
  7895. });
  7896. },
  7897. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7898. return cli.Put("/test", body, "text/plain", progress_callback);
  7899. },
  7900. "put test data for upload progress");
  7901. }
  7902. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7903. TestStringBodyUploadProgress(
  7904. [](Server &svr) {
  7905. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7906. res.set_content("patch received", "text/plain");
  7907. });
  7908. },
  7909. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7910. return cli.Patch("/test", body, "text/plain", progress_callback);
  7911. },
  7912. "patch test data for upload progress");
  7913. }
  7914. // Helper function for content provider upload progress tests
  7915. template <typename SetupHandler, typename ClientCall>
  7916. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7917. ClientCall &&client_call) {
  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. auto res =
  7929. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7930. progress_values.push_back(current);
  7931. return true;
  7932. });
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(200, res->status);
  7935. EXPECT_FALSE(progress_values.empty());
  7936. }
  7937. TEST(UploadProgressTest, PostContentProviderProgress) {
  7938. TestContentProviderUploadProgress(
  7939. [](Server &svr) {
  7940. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7941. res.set_content("provider received", "text/plain");
  7942. });
  7943. },
  7944. [](Client &cli, UploadProgress progress_callback) {
  7945. return cli.Post(
  7946. "/test", 10,
  7947. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7948. sink.os << "test data";
  7949. return true;
  7950. },
  7951. "text/plain", progress_callback);
  7952. });
  7953. }
  7954. // Helper function for multipart upload progress tests
  7955. template <typename SetupHandler, typename ClientCall>
  7956. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7957. ClientCall &&client_call,
  7958. const string &endpoint) {
  7959. Server svr;
  7960. setup_handler(svr);
  7961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7962. auto se = detail::scope_exit([&] {
  7963. svr.stop();
  7964. t.join();
  7965. });
  7966. svr.wait_until_ready();
  7967. Client cli(HOST, PORT);
  7968. vector<uint64_t> progress_values;
  7969. UploadFormDataItems items = {
  7970. {"field1", "value1", "", ""},
  7971. {"field2", "longer value for progress tracking test", "", ""},
  7972. {"file1", "file content data for upload progress", "test.txt",
  7973. "text/plain"}};
  7974. auto res = client_call(cli, endpoint, items,
  7975. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7976. progress_values.push_back(current);
  7977. return true;
  7978. });
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(200, res->status);
  7981. EXPECT_FALSE(progress_values.empty());
  7982. }
  7983. TEST(UploadProgressTest, PostMultipartProgress) {
  7984. TestMultipartUploadProgress(
  7985. [](Server &svr) {
  7986. svr.Post("/multipart", [](const Request &req, Response &res) {
  7987. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7988. res.set_content("multipart received", "text/plain");
  7989. });
  7990. },
  7991. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7992. UploadProgress progress_callback) {
  7993. return cli.Post(endpoint, items, progress_callback);
  7994. },
  7995. "/multipart");
  7996. }
  7997. // Helper function for basic download progress tests
  7998. template <typename SetupHandler, typename ClientCall>
  7999. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8000. ClientCall &&client_call, const string &endpoint,
  8001. size_t expected_content_size) {
  8002. Server svr;
  8003. setup_handler(svr);
  8004. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8005. auto se = detail::scope_exit([&] {
  8006. svr.stop();
  8007. t.join();
  8008. });
  8009. svr.wait_until_ready();
  8010. Client cli(HOST, PORT);
  8011. vector<uint64_t> progress_values;
  8012. auto res = client_call(cli, endpoint,
  8013. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8014. progress_values.push_back(current);
  8015. return true;
  8016. });
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(200, res->status);
  8019. EXPECT_FALSE(progress_values.empty());
  8020. EXPECT_EQ(expected_content_size, res->body.size());
  8021. }
  8022. TEST(DownloadProgressTest, GetBasic) {
  8023. TestBasicDownloadProgress(
  8024. [](Server &svr) {
  8025. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8026. string content(1000, 'D');
  8027. res.set_content(content, "text/plain");
  8028. });
  8029. },
  8030. [](Client &cli, const string &endpoint,
  8031. DownloadProgress progress_callback) {
  8032. return cli.Get(endpoint, progress_callback);
  8033. },
  8034. "/download", 1000u);
  8035. }
  8036. // Helper function for content receiver download progress tests
  8037. template <typename SetupHandler, typename ClientCall>
  8038. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8039. ClientCall &&client_call,
  8040. const string &endpoint,
  8041. size_t expected_content_size) {
  8042. Server svr;
  8043. setup_handler(svr);
  8044. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8045. auto se = detail::scope_exit([&] {
  8046. svr.stop();
  8047. t.join();
  8048. });
  8049. svr.wait_until_ready();
  8050. Client cli(HOST, PORT);
  8051. vector<uint64_t> progress_values;
  8052. string received_body;
  8053. auto res = client_call(
  8054. cli, endpoint,
  8055. [&](const char *data, size_t data_length) -> bool {
  8056. received_body.append(data, data_length);
  8057. return true;
  8058. },
  8059. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8060. progress_values.push_back(current);
  8061. return true;
  8062. });
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(200, res->status);
  8065. EXPECT_FALSE(progress_values.empty());
  8066. EXPECT_EQ(expected_content_size, received_body.size());
  8067. EXPECT_TRUE(res->body.empty());
  8068. }
  8069. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8070. TestContentReceiverDownloadProgress(
  8071. [](Server &svr) {
  8072. svr.Get("/download-receiver",
  8073. [](const Request & /*req*/, Response &res) {
  8074. string content(2000, 'R');
  8075. res.set_content(content, "text/plain");
  8076. });
  8077. },
  8078. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8079. DownloadProgress progress_callback) {
  8080. return cli.Get(endpoint, content_receiver, progress_callback);
  8081. },
  8082. "/download-receiver", 2000u);
  8083. }
  8084. TEST(StreamingTest, NoContentLengthStreaming) {
  8085. Server svr;
  8086. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8087. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8088. if (offset < 6) {
  8089. sink.os << (offset < 3 ? "a" : "b");
  8090. } else {
  8091. sink.done();
  8092. }
  8093. return true;
  8094. });
  8095. });
  8096. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8097. auto listen_se = detail::scope_exit([&] {
  8098. svr.stop();
  8099. listen_thread.join();
  8100. ASSERT_FALSE(svr.is_running());
  8101. });
  8102. svr.wait_until_ready();
  8103. Client client(HOST, PORT);
  8104. auto get_thread = std::thread([&client]() {
  8105. std::string s;
  8106. auto res =
  8107. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8108. s += std::string(data, len);
  8109. return true;
  8110. });
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("aaabbb", s);
  8114. });
  8115. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8116. // Give GET time to get a few messages.
  8117. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8118. }
  8119. TEST(MountTest, Unmount) {
  8120. Server svr;
  8121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8122. auto se = detail::scope_exit([&] {
  8123. svr.stop();
  8124. listen_thread.join();
  8125. ASSERT_FALSE(svr.is_running());
  8126. });
  8127. svr.wait_until_ready();
  8128. Client cli("localhost", PORT);
  8129. svr.set_mount_point("/mount2", "./www2");
  8130. auto res = cli.Get("/");
  8131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8132. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8133. res = cli.Get("/mount2/dir/test.html");
  8134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. svr.set_mount_point("/", "./www");
  8137. res = cli.Get("/dir/");
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. svr.remove_mount_point("/");
  8141. res = cli.Get("/dir/");
  8142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8144. svr.remove_mount_point("/mount2");
  8145. res = cli.Get("/mount2/dir/test.html");
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8148. }
  8149. TEST(MountTest, Redicect) {
  8150. Server svr;
  8151. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8152. auto se = detail::scope_exit([&] {
  8153. svr.stop();
  8154. listen_thread.join();
  8155. ASSERT_FALSE(svr.is_running());
  8156. });
  8157. svr.set_mount_point("/", "./www");
  8158. svr.wait_until_ready();
  8159. Client cli("localhost", PORT);
  8160. auto res = cli.Get("/dir/");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. res = cli.Get("/dir");
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8166. res = cli.Get("/file");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. res = cli.Get("/file/");
  8170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8171. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8172. cli.set_follow_location(true);
  8173. res = cli.Get("/dir");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. TEST(MountTest, MultibytesPathName) {
  8178. Server svr;
  8179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8180. auto se = detail::scope_exit([&] {
  8181. svr.stop();
  8182. listen_thread.join();
  8183. ASSERT_FALSE(svr.is_running());
  8184. });
  8185. svr.set_mount_point("/", "./www");
  8186. svr.wait_until_ready();
  8187. Client cli("localhost", PORT);
  8188. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8192. }
  8193. #ifdef _WIN32
  8194. // Issue #2435: mmap::open() must succeed even when another handle holds
  8195. // the file open for writing (e.g. an active log file).
  8196. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8197. const char *path = "mmap_concurrent_writer_test.txt";
  8198. const char *content = "hello";
  8199. {
  8200. std::ofstream f(path, std::ios::binary);
  8201. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8202. }
  8203. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8204. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8205. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8206. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8207. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8208. detail::mmap m(path);
  8209. ASSERT_TRUE(m.is_open());
  8210. EXPECT_EQ(strlen(content), m.size());
  8211. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8212. }
  8213. #endif
  8214. #ifndef _WIN32
  8215. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8216. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8217. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8218. TEST(MmapTest, FailedMappingIsNotOpen) {
  8219. const char *path = "./mmap_failed_mapping_test_dir";
  8220. ASSERT_EQ(0, ::mkdir(path, 0755));
  8221. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8222. detail::mmap m(path);
  8223. EXPECT_FALSE(m.is_open());
  8224. EXPECT_EQ(0U, m.size());
  8225. EXPECT_NE(static_cast<const void *>(m.data()),
  8226. static_cast<const void *>(MAP_FAILED));
  8227. }
  8228. #endif
  8229. TEST(KeepAliveTest, ReadTimeout) {
  8230. Server svr;
  8231. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8232. std::this_thread::sleep_for(std::chrono::seconds(2));
  8233. res.set_content("a", "text/plain");
  8234. });
  8235. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8236. res.set_content("b", "text/plain");
  8237. });
  8238. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8239. auto se = detail::scope_exit([&] {
  8240. svr.stop();
  8241. listen_thread.join();
  8242. ASSERT_FALSE(svr.is_running());
  8243. });
  8244. svr.wait_until_ready();
  8245. Client cli("localhost", PORT);
  8246. cli.set_keep_alive(true);
  8247. cli.set_read_timeout(std::chrono::seconds(1));
  8248. auto resa = cli.Get("/a");
  8249. ASSERT_FALSE(resa);
  8250. EXPECT_EQ(Error::Read, resa.error());
  8251. auto resb = cli.Get("/b");
  8252. ASSERT_TRUE(resb);
  8253. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8254. EXPECT_EQ("b", resb->body);
  8255. }
  8256. TEST(KeepAliveTest, MaxCount) {
  8257. size_t keep_alive_max_count = 3;
  8258. Server svr;
  8259. svr.set_keep_alive_max_count(keep_alive_max_count);
  8260. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8261. res.set_content("Hello World!", "text/plain");
  8262. });
  8263. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8264. auto se = detail::scope_exit([&] {
  8265. svr.stop();
  8266. listen_thread.join();
  8267. ASSERT_FALSE(svr.is_running());
  8268. });
  8269. svr.wait_until_ready();
  8270. Client cli(HOST, PORT);
  8271. cli.set_keep_alive(true);
  8272. for (size_t i = 0; i < 5; i++) {
  8273. auto result = cli.Get("/hi");
  8274. ASSERT_TRUE(result);
  8275. EXPECT_EQ(StatusCode::OK_200, result->status);
  8276. if (i == keep_alive_max_count - 1) {
  8277. EXPECT_EQ("close", result->get_header_value("Connection"));
  8278. } else {
  8279. EXPECT_FALSE(result->has_header("Connection"));
  8280. }
  8281. }
  8282. }
  8283. TEST(KeepAliveTest, Issue1041) {
  8284. Server svr;
  8285. svr.set_keep_alive_timeout(3);
  8286. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8287. res.set_content("Hello World!", "text/plain");
  8288. });
  8289. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8290. auto se = detail::scope_exit([&] {
  8291. svr.stop();
  8292. listen_thread.join();
  8293. ASSERT_FALSE(svr.is_running());
  8294. });
  8295. svr.wait_until_ready();
  8296. Client cli(HOST, PORT);
  8297. cli.set_keep_alive(true);
  8298. auto result = cli.Get("/hi");
  8299. ASSERT_TRUE(result);
  8300. EXPECT_EQ(StatusCode::OK_200, result->status);
  8301. std::this_thread::sleep_for(std::chrono::seconds(5));
  8302. result = cli.Get("/hi");
  8303. ASSERT_TRUE(result);
  8304. EXPECT_EQ(StatusCode::OK_200, result->status);
  8305. }
  8306. TEST(KeepAliveTest, Issue1959) {
  8307. Server svr;
  8308. svr.set_keep_alive_timeout(5);
  8309. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8310. res.set_content("a", "text/plain");
  8311. });
  8312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8313. auto se = detail::scope_exit([&] {
  8314. if (!svr.is_running()) return;
  8315. svr.stop();
  8316. listen_thread.join();
  8317. ASSERT_FALSE(svr.is_running());
  8318. });
  8319. svr.wait_until_ready();
  8320. Client cli("localhost", PORT);
  8321. cli.set_keep_alive(true);
  8322. using namespace std::chrono;
  8323. auto start = steady_clock::now();
  8324. cli.Get("/a");
  8325. svr.stop();
  8326. listen_thread.join();
  8327. auto end = steady_clock::now();
  8328. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8329. EXPECT_LT(elapsed, 5000);
  8330. }
  8331. #ifdef CPPHTTPLIB_SSL_ENABLED
  8332. TEST(KeepAliveTest, SSLClientReconnection) {
  8333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. ASSERT_TRUE(svr.is_valid());
  8335. svr.set_keep_alive_timeout(1);
  8336. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8337. res.set_content("Hello World!", "text/plain");
  8338. });
  8339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8340. auto se = detail::scope_exit([&] {
  8341. svr.stop();
  8342. listen_thread.join();
  8343. ASSERT_FALSE(svr.is_running());
  8344. });
  8345. svr.wait_until_ready();
  8346. SSLClient cli(HOST, PORT);
  8347. cli.enable_server_certificate_verification(false);
  8348. cli.set_keep_alive(true);
  8349. auto result = cli.Get("/hi");
  8350. ASSERT_TRUE(result);
  8351. EXPECT_EQ(StatusCode::OK_200, result->status);
  8352. result = cli.Get("/hi");
  8353. ASSERT_TRUE(result);
  8354. EXPECT_EQ(StatusCode::OK_200, result->status);
  8355. std::this_thread::sleep_for(std::chrono::seconds(2));
  8356. // Recoonect
  8357. result = cli.Get("/hi");
  8358. ASSERT_TRUE(result);
  8359. EXPECT_EQ(StatusCode::OK_200, result->status);
  8360. result = cli.Get("/hi");
  8361. ASSERT_TRUE(result);
  8362. EXPECT_EQ(StatusCode::OK_200, result->status);
  8363. }
  8364. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8366. ASSERT_TRUE(svr.is_valid());
  8367. svr.set_keep_alive_timeout(1);
  8368. std::string content = "reconnect";
  8369. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8370. res.set_content("Hello World!", "text/plain");
  8371. });
  8372. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8373. auto se = detail::scope_exit([&] {
  8374. svr.stop();
  8375. listen_thread.join();
  8376. ASSERT_FALSE(svr.is_running());
  8377. });
  8378. svr.wait_until_ready();
  8379. SSLClient cli(HOST, PORT);
  8380. cli.enable_server_certificate_verification(false);
  8381. cli.set_keep_alive(true);
  8382. auto result = cli.Post(
  8383. "/hi", content.size(),
  8384. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8385. sink.write(content.c_str(), content.size());
  8386. return true;
  8387. },
  8388. "text/plain");
  8389. ASSERT_TRUE(result);
  8390. EXPECT_EQ(200, result->status);
  8391. std::this_thread::sleep_for(std::chrono::seconds(2));
  8392. // Recoonect
  8393. result = cli.Post(
  8394. "/hi", content.size(),
  8395. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8396. sink.write(content.c_str(), content.size());
  8397. return true;
  8398. },
  8399. "text/plain");
  8400. ASSERT_TRUE(result);
  8401. EXPECT_EQ(200, result->status);
  8402. result = cli.Post(
  8403. "/hi", content.size(),
  8404. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8405. sink.write(content.c_str(), content.size());
  8406. return true;
  8407. },
  8408. "text/plain");
  8409. ASSERT_TRUE(result);
  8410. EXPECT_EQ(200, result->status);
  8411. }
  8412. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8413. using namespace httplib::tls;
  8414. {
  8415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8416. ASSERT_TRUE(svr.is_valid());
  8417. svr.Get("/sni", [&](const Request &req, Response &res) {
  8418. std::string expected = req.sni();
  8419. EXPECT_EQ(expected, req.get_param_value("expected"));
  8420. res.set_content("ok", "text/plain");
  8421. });
  8422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8423. auto se = detail::scope_exit([&] {
  8424. svr.stop();
  8425. listen_thread.join();
  8426. ASSERT_FALSE(svr.is_running());
  8427. });
  8428. svr.wait_until_ready();
  8429. {
  8430. SSLClient cli("localhost", PORT);
  8431. cli.enable_server_certificate_verification(false);
  8432. auto res = cli.Get("/sni?expected=localhost");
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. }
  8435. {
  8436. SSLClient cli("::1", PORT);
  8437. cli.enable_server_certificate_verification(false);
  8438. auto res = cli.Get("/sni?expected=");
  8439. // NOTE: This may fail if the server is listening on IPv4 only
  8440. // (e.g., when localhost resolves to 127.0.0.1 only)
  8441. if (res) {
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. } else {
  8444. EXPECT_EQ(Error::Connection, res.error());
  8445. }
  8446. }
  8447. }
  8448. }
  8449. #endif
  8450. TEST(ClientProblemDetectionTest, ContentProvider) {
  8451. Server svr;
  8452. size_t content_length = 1024 * 1024;
  8453. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8454. res.set_content_provider(
  8455. content_length, "text/plain",
  8456. [&](size_t offset, size_t length, DataSink &sink) {
  8457. auto out_len = std::min(length, static_cast<size_t>(1024));
  8458. std::string out(out_len, '@');
  8459. sink.write(out.data(), out_len);
  8460. return offset < 4096;
  8461. },
  8462. [](bool success) { ASSERT_FALSE(success); });
  8463. });
  8464. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8465. res.set_content_provider(
  8466. 0, "text/plain",
  8467. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8468. EXPECT_TRUE(false);
  8469. return true;
  8470. },
  8471. [](bool success) { ASSERT_FALSE(success); });
  8472. });
  8473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8474. auto se = detail::scope_exit([&] {
  8475. svr.stop();
  8476. listen_thread.join();
  8477. ASSERT_FALSE(svr.is_running());
  8478. });
  8479. svr.wait_until_ready();
  8480. Client cli("localhost", PORT);
  8481. {
  8482. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8483. size_t /*data_length*/) { return false; });
  8484. ASSERT_FALSE(res);
  8485. }
  8486. {
  8487. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8488. size_t /*data_length*/) { return false; });
  8489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8490. }
  8491. }
  8492. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8493. Server svr;
  8494. svr.set_error_handler([](Request const &, Response &res) -> void {
  8495. res.set_chunked_content_provider(
  8496. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8497. sink.os << "hello";
  8498. sink.os << "world";
  8499. sink.done();
  8500. return true;
  8501. });
  8502. });
  8503. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8504. auto se = detail::scope_exit([&] {
  8505. svr.stop();
  8506. listen_thread.join();
  8507. ASSERT_FALSE(svr.is_running());
  8508. });
  8509. svr.wait_until_ready();
  8510. Client cli("localhost", PORT);
  8511. auto res = cli.Get("/");
  8512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8514. EXPECT_EQ("helloworld", res->body);
  8515. }
  8516. TEST(LongPollingTest, ClientCloseDetection) {
  8517. Server svr;
  8518. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8519. res.set_chunked_content_provider(
  8520. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8521. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8522. sink.os << "hello";
  8523. auto count = 10;
  8524. while (count > 0 && sink.is_writable()) {
  8525. this_thread::sleep_for(chrono::milliseconds(10));
  8526. count--;
  8527. }
  8528. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8529. return true;
  8530. });
  8531. });
  8532. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8533. auto se = detail::scope_exit([&] {
  8534. svr.stop();
  8535. listen_thread.join();
  8536. ASSERT_FALSE(svr.is_running());
  8537. });
  8538. svr.wait_until_ready();
  8539. Client cli("localhost", PORT);
  8540. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8541. EXPECT_EQ("hello", string(data, data_length));
  8542. return false; // close the socket immediately.
  8543. });
  8544. ASSERT_FALSE(res);
  8545. }
  8546. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8547. Server svr;
  8548. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8549. res.set_chunked_content_provider(
  8550. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8551. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8552. sink.os << "hello";
  8553. EXPECT_TRUE(sink.os.good());
  8554. // Wait for the client to close the connection
  8555. auto count = 10;
  8556. while (count > 0 && sink.is_writable()) {
  8557. this_thread::sleep_for(chrono::milliseconds(10));
  8558. count--;
  8559. }
  8560. // After client disconnect, write repeatedly until the socket
  8561. // write actually fails (small writes may be absorbed by the
  8562. // kernel buffer)
  8563. std::string chunk(1024, 'x');
  8564. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8565. sink.os << chunk;
  8566. }
  8567. EXPECT_TRUE(sink.os.fail());
  8568. return true;
  8569. });
  8570. });
  8571. auto port = svr.bind_to_any_port("localhost");
  8572. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8573. auto se = detail::scope_exit([&] {
  8574. svr.stop();
  8575. listen_thread.join();
  8576. ASSERT_FALSE(svr.is_running());
  8577. });
  8578. svr.wait_until_ready();
  8579. Client cli("localhost", port);
  8580. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8581. EXPECT_EQ("hello", string(data, data_length));
  8582. return false; // close the socket immediately.
  8583. });
  8584. ASSERT_FALSE(res);
  8585. }
  8586. TEST(GetWithParametersTest, GetWithParameters) {
  8587. Server svr;
  8588. svr.Get("/", [&](const Request &req, Response &) {
  8589. EXPECT_EQ("world", req.get_param_value("hello"));
  8590. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8591. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8592. });
  8593. svr.Get("/params", [&](const Request &req, Response &) {
  8594. EXPECT_EQ("world", req.get_param_value("hello"));
  8595. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8596. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8597. });
  8598. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8599. EXPECT_EQ("resource-id", req.matches[1]);
  8600. EXPECT_EQ("foo", req.get_param_value("param1"));
  8601. EXPECT_EQ("bar", req.get_param_value("param2"));
  8602. });
  8603. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8604. EXPECT_EQ("user-id", req.path_params.at("id"));
  8605. EXPECT_EQ("foo", req.get_param_value("param1"));
  8606. EXPECT_EQ("bar", req.get_param_value("param2"));
  8607. });
  8608. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8609. auto se = detail::scope_exit([&] {
  8610. svr.stop();
  8611. listen_thread.join();
  8612. ASSERT_FALSE(svr.is_running());
  8613. });
  8614. svr.wait_until_ready();
  8615. {
  8616. Client cli(HOST, PORT);
  8617. Params params;
  8618. params.emplace("hello", "world");
  8619. params.emplace("hello2", "world2");
  8620. params.emplace("hello3", "world3");
  8621. auto res = cli.Get("/", params, Headers{});
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. {
  8626. Client cli(HOST, PORT);
  8627. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8629. EXPECT_EQ(StatusCode::OK_200, res->status);
  8630. }
  8631. {
  8632. Client cli(HOST, PORT);
  8633. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. {
  8638. Client cli(HOST, PORT);
  8639. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. }
  8643. }
  8644. TEST(GetWithParametersTest, GetWithParameters2) {
  8645. Server svr;
  8646. svr.Get("/", [&](const Request &req, Response &res) {
  8647. auto text = req.get_param_value("hello");
  8648. res.set_content(text, "text/plain");
  8649. });
  8650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8651. auto se = detail::scope_exit([&] {
  8652. svr.stop();
  8653. listen_thread.join();
  8654. ASSERT_FALSE(svr.is_running());
  8655. });
  8656. svr.wait_until_ready();
  8657. Client cli("localhost", PORT);
  8658. Params params;
  8659. params.emplace("hello", "world");
  8660. std::string body;
  8661. auto res = cli.Get("/", params, Headers{},
  8662. [&](const char *data, size_t data_length) {
  8663. body.append(data, data_length);
  8664. return true;
  8665. });
  8666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8667. EXPECT_EQ(StatusCode::OK_200, res->status);
  8668. EXPECT_EQ("world", body);
  8669. }
  8670. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8671. Server svr;
  8672. svr.Get("/search", [&](const Request &req, Response &res) {
  8673. auto q = req.get_param_value("q");
  8674. res.set_content(q, "text/plain");
  8675. });
  8676. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8677. auto se = detail::scope_exit([&] {
  8678. svr.stop();
  8679. listen_thread.join();
  8680. ASSERT_FALSE(svr.is_running());
  8681. });
  8682. svr.wait_until_ready();
  8683. Client cli("localhost", PORT);
  8684. // Verify that Get(path, params) works without requiring Headers argument
  8685. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::OK_200, res->status);
  8688. EXPECT_EQ("cpp-httplib", res->body);
  8689. }
  8690. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8691. auto host = "httpbingo.org";
  8692. auto path = std::string{"/range/32"};
  8693. #ifdef CPPHTTPLIB_SSL_ENABLED
  8694. SSLClient cli(host);
  8695. #else
  8696. Client cli(host);
  8697. #endif
  8698. cli.set_default_headers({make_range_header({{1, 10}})});
  8699. cli.set_connection_timeout(5);
  8700. {
  8701. auto res = cli.Get(path);
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ("bcdefghijk", res->body);
  8704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8705. }
  8706. {
  8707. auto res = cli.Get(path);
  8708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8709. EXPECT_EQ("bcdefghijk", res->body);
  8710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8711. }
  8712. }
  8713. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8714. Server svr;
  8715. svr.set_default_headers({{"Hello", "World"}});
  8716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8717. res.set_content("ok", "text/plain");
  8718. });
  8719. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8720. auto se = detail::scope_exit([&] {
  8721. svr.stop();
  8722. listen_thread.join();
  8723. ASSERT_FALSE(svr.is_running());
  8724. });
  8725. svr.wait_until_ready();
  8726. Client cli("localhost", PORT);
  8727. auto res = cli.Get("/");
  8728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8729. EXPECT_EQ(StatusCode::OK_200, res->status);
  8730. EXPECT_EQ("ok", res->body);
  8731. EXPECT_EQ("World", res->get_header_value("Hello"));
  8732. }
  8733. #ifdef CPPHTTPLIB_SSL_ENABLED
  8734. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8736. ASSERT_TRUE(svr.is_valid());
  8737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8738. std::this_thread::sleep_for(std::chrono::seconds(2));
  8739. res.set_content("a", "text/plain");
  8740. });
  8741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8742. res.set_content("b", "text/plain");
  8743. });
  8744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8745. auto se = detail::scope_exit([&] {
  8746. svr.stop();
  8747. listen_thread.join();
  8748. ASSERT_FALSE(svr.is_running());
  8749. });
  8750. svr.wait_until_ready();
  8751. SSLClient cli("localhost", PORT);
  8752. cli.enable_server_certificate_verification(false);
  8753. cli.set_keep_alive(true);
  8754. cli.set_read_timeout(std::chrono::seconds(1));
  8755. auto resa = cli.Get("/a");
  8756. ASSERT_TRUE(!resa);
  8757. EXPECT_EQ(Error::Read, resa.error());
  8758. auto resb = cli.Get("/b");
  8759. ASSERT_TRUE(resb);
  8760. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8761. EXPECT_EQ("b", resb->body);
  8762. }
  8763. #endif
  8764. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8765. protected:
  8766. ServerTestWithAI_PASSIVE()
  8767. : cli_(HOST, PORT)
  8768. #ifdef CPPHTTPLIB_SSL_ENABLED
  8769. ,
  8770. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8771. #endif
  8772. {
  8773. #ifdef CPPHTTPLIB_SSL_ENABLED
  8774. cli_.enable_server_certificate_verification(false);
  8775. #endif
  8776. }
  8777. virtual void SetUp() {
  8778. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8779. res.set_content("Hello World!", "text/plain");
  8780. });
  8781. t_ = thread(
  8782. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8783. svr_.wait_until_ready();
  8784. }
  8785. virtual void TearDown() {
  8786. svr_.stop();
  8787. t_.join();
  8788. }
  8789. #ifdef CPPHTTPLIB_SSL_ENABLED
  8790. SSLClient cli_;
  8791. SSLServer svr_;
  8792. #else
  8793. Client cli_;
  8794. Server svr_;
  8795. #endif
  8796. thread t_;
  8797. };
  8798. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8799. auto res = cli_.Get("/hi");
  8800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8801. EXPECT_EQ(StatusCode::OK_200, res->status);
  8802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8803. EXPECT_EQ("Hello World!", res->body);
  8804. }
  8805. class ServerUpDownTest : public ::testing::Test {
  8806. protected:
  8807. ServerUpDownTest() : cli_(HOST, PORT) {}
  8808. virtual void SetUp() {
  8809. t_ = thread([&]() {
  8810. svr_.bind_to_any_port(HOST);
  8811. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8812. ASSERT_TRUE(svr_.listen_after_bind());
  8813. });
  8814. svr_.wait_until_ready();
  8815. }
  8816. virtual void TearDown() {
  8817. svr_.stop();
  8818. t_.join();
  8819. }
  8820. Client cli_;
  8821. Server svr_;
  8822. thread t_;
  8823. };
  8824. TEST_F(ServerUpDownTest, QuickStartStop) {
  8825. // Should not crash, especially when run with
  8826. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8827. }
  8828. class PayloadMaxLengthTest : public ::testing::Test {
  8829. protected:
  8830. PayloadMaxLengthTest()
  8831. : cli_(HOST, PORT)
  8832. #ifdef CPPHTTPLIB_SSL_ENABLED
  8833. ,
  8834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8835. #endif
  8836. {
  8837. #ifdef CPPHTTPLIB_SSL_ENABLED
  8838. cli_.enable_server_certificate_verification(false);
  8839. #endif
  8840. }
  8841. virtual void SetUp() {
  8842. svr_.set_payload_max_length(8);
  8843. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8844. res.set_content("test", "text/plain");
  8845. });
  8846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8847. svr_.wait_until_ready();
  8848. }
  8849. virtual void TearDown() {
  8850. svr_.stop();
  8851. t_.join();
  8852. }
  8853. #ifdef CPPHTTPLIB_SSL_ENABLED
  8854. SSLClient cli_;
  8855. SSLServer svr_;
  8856. #else
  8857. Client cli_;
  8858. Server svr_;
  8859. #endif
  8860. thread t_;
  8861. };
  8862. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8863. auto res = cli_.Post("/test", "123456789", "text/plain");
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8866. res = cli_.Post("/test", "12345678", "text/plain");
  8867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8868. EXPECT_EQ(StatusCode::OK_200, res->status);
  8869. }
  8870. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8871. // Test chunked encoding with payload exceeding the 8-byte limit
  8872. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8873. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8875. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8876. }
  8877. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8878. // Test chunked encoding with payload within the 8-byte limit
  8879. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8880. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8882. EXPECT_EQ(StatusCode::OK_200, res->status);
  8883. }
  8884. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8885. // Test using send_request to send chunked data exceeding payload limit
  8886. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8887. "Host: " +
  8888. std::string(HOST) + ":" + std::to_string(PORT) +
  8889. "\r\n"
  8890. "Transfer-Encoding: chunked\r\n"
  8891. "Connection: close\r\n"
  8892. "\r\n"
  8893. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8894. "0123456789\r\n"
  8895. "0\r\n" // End chunk
  8896. "\r\n";
  8897. std::string response;
  8898. bool result = send_request(1, chunked_request, &response);
  8899. if (!result) {
  8900. // If send_request fails, it might be because the server closed the
  8901. // connection due to payload limit enforcement, which is acceptable
  8902. SUCCEED()
  8903. << "Server rejected oversized chunked request (connection closed)";
  8904. } else {
  8905. // If we got a response, check if it's an error response or connection was
  8906. // closed early Short response length indicates connection was closed due to
  8907. // payload limit
  8908. if (response.length() <= 10) {
  8909. SUCCEED() << "Server closed connection for oversized chunked request";
  8910. } else {
  8911. // Check for error status codes
  8912. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8913. response.find("Payload Too Large") != std::string::npos ||
  8914. response.find("400") != std::string::npos);
  8915. }
  8916. }
  8917. }
  8918. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8919. // Test request without Content-Length header exceeding payload limit
  8920. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8921. "Host: " +
  8922. std::string(HOST) + ":" +
  8923. std::to_string(PORT) +
  8924. "\r\n"
  8925. "Connection: close\r\n"
  8926. "\r\n";
  8927. // Add payload exceeding the 8-byte limit
  8928. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8929. request_without_content_length += large_payload;
  8930. std::string response;
  8931. bool result = send_request(1, request_without_content_length, &response);
  8932. if (!result) {
  8933. // If send_request fails, server likely closed connection due to payload
  8934. // limit
  8935. SUCCEED() << "Server rejected oversized request without Content-Length "
  8936. "(connection closed)";
  8937. } else {
  8938. // Check if server responded with error or closed connection early
  8939. if (response.length() <= 10) {
  8940. SUCCEED() << "Server closed connection for oversized request without "
  8941. "Content-Length";
  8942. } else {
  8943. // Check for error status codes
  8944. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8945. response.find("Payload Too Large") != std::string::npos ||
  8946. response.find("400") != std::string::npos);
  8947. }
  8948. }
  8949. }
  8950. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8951. // Test request without Content-Length header within payload limit
  8952. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8953. "Host: " +
  8954. std::string(HOST) + ":" +
  8955. std::to_string(PORT) +
  8956. "\r\n"
  8957. "Connection: close\r\n"
  8958. "\r\n";
  8959. // Add payload within the 8-byte limit
  8960. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8961. request_without_content_length += small_payload;
  8962. std::string response;
  8963. bool result = send_request(1, request_without_content_length, &response);
  8964. // For requests without Content-Length, the server may have different behavior
  8965. // The key is that it should not reject due to payload limit for small
  8966. // payloads
  8967. if (result) {
  8968. // Check for any HTTP response (success or error, but not connection closed)
  8969. if (response.length() > 10) {
  8970. SUCCEED()
  8971. << "Server processed request without Content-Length within limit";
  8972. } else {
  8973. // Short response might indicate connection closed, which is acceptable
  8974. SUCCEED() << "Server closed connection for request without "
  8975. "Content-Length (acceptable behavior)";
  8976. }
  8977. } else {
  8978. // Connection failure might be due to protocol requirements
  8979. SUCCEED() << "Connection issue with request without Content-Length "
  8980. "(environment-specific)";
  8981. }
  8982. }
  8983. class LargePayloadMaxLengthTest : public ::testing::Test {
  8984. protected:
  8985. LargePayloadMaxLengthTest()
  8986. : cli_(HOST, PORT)
  8987. #ifdef CPPHTTPLIB_SSL_ENABLED
  8988. ,
  8989. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8990. #endif
  8991. {
  8992. #ifdef CPPHTTPLIB_SSL_ENABLED
  8993. cli_.enable_server_certificate_verification(false);
  8994. #endif
  8995. }
  8996. virtual void SetUp() {
  8997. // Set 10MB payload limit
  8998. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8999. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9000. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9001. res.set_content("Large payload test", "text/plain");
  9002. });
  9003. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9004. svr_.wait_until_ready();
  9005. }
  9006. virtual void TearDown() {
  9007. svr_.stop();
  9008. t_.join();
  9009. }
  9010. #ifdef CPPHTTPLIB_SSL_ENABLED
  9011. SSLClient cli_;
  9012. SSLServer svr_;
  9013. #else
  9014. Client cli_;
  9015. Server svr_;
  9016. #endif
  9017. thread t_;
  9018. };
  9019. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9020. // Test chunked encoding with payload within 10MB limit
  9021. std::string medium_payload(5 * 1024 * 1024,
  9022. 'A'); // 5MB payload, within 10MB limit
  9023. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9025. EXPECT_EQ(StatusCode::OK_200, res->status);
  9026. }
  9027. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9028. // Test chunked encoding with payload exceeding 10MB limit
  9029. std::string large_payload(12 * 1024 * 1024,
  9030. 'B'); // 12MB payload, exceeds 10MB limit
  9031. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9032. // Server may either return 413 or close the connection
  9033. if (res) {
  9034. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9035. } else {
  9036. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9037. }
  9038. }
  9039. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9040. // Test request without Content-Length header within 10MB limit
  9041. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9042. "Host: " +
  9043. std::string(HOST) + ":" +
  9044. std::to_string(PORT) +
  9045. "\r\n"
  9046. "Connection: close\r\n"
  9047. "\r\n";
  9048. // Add 1MB payload (within 10MB limit)
  9049. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9050. request_without_content_length += medium_payload;
  9051. std::string response;
  9052. bool result = send_request(5, request_without_content_length, &response);
  9053. if (result) {
  9054. // Should get a proper HTTP response for payloads within limit
  9055. if (response.length() > 10) {
  9056. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9057. "10MB limit";
  9058. } else {
  9059. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9060. "Content-Length)";
  9061. }
  9062. } else {
  9063. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9064. }
  9065. }
  9066. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9067. // Test request without Content-Length header exceeding 10MB limit
  9068. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9069. "Host: " +
  9070. std::string(HOST) + ":" +
  9071. std::to_string(PORT) +
  9072. "\r\n"
  9073. "Connection: close\r\n"
  9074. "\r\n";
  9075. // Add 12MB payload (exceeds 10MB limit)
  9076. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9077. request_without_content_length += large_payload;
  9078. std::string response;
  9079. bool result = send_request(10, request_without_content_length, &response);
  9080. if (!result) {
  9081. // Server should close connection due to payload limit
  9082. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9083. "(connection closed)";
  9084. } else {
  9085. // Check for error response
  9086. if (response.length() <= 10) {
  9087. SUCCEED()
  9088. << "Server closed connection for 12MB request exceeding 10MB limit";
  9089. } else {
  9090. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9091. response.find("Payload Too Large") != std::string::npos ||
  9092. response.find("400") != std::string::npos);
  9093. }
  9094. }
  9095. }
  9096. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9097. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9098. // path.
  9099. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9100. Server svr;
  9101. const size_t LIMIT = 64 * 1024; // 64KB
  9102. svr.set_payload_max_length(LIMIT);
  9103. size_t total = 0;
  9104. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9105. const ContentReader &content_reader) {
  9106. content_reader([&](const char * /*data*/, size_t len) {
  9107. total += len;
  9108. return true;
  9109. });
  9110. res.status = 200;
  9111. res.set_content("stream_ok", "text/plain");
  9112. });
  9113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9114. auto se = detail::scope_exit([&] {
  9115. svr.stop();
  9116. thread.join();
  9117. ASSERT_FALSE(svr.is_running());
  9118. });
  9119. svr.wait_until_ready();
  9120. // Prepare 256KB raw data and gzip-compress it
  9121. std::string raw(256 * 1024, 'A');
  9122. std::string gz;
  9123. {
  9124. z_stream zs{};
  9125. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9126. Z_DEFAULT_STRATEGY);
  9127. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9128. zs.avail_in = static_cast<uInt>(raw.size());
  9129. char outbuf[4096];
  9130. int ret;
  9131. do {
  9132. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9133. zs.avail_out = sizeof(outbuf);
  9134. ret = deflate(&zs, Z_FINISH);
  9135. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9136. } while (ret != Z_STREAM_END);
  9137. deflateEnd(&zs);
  9138. }
  9139. Client cli(HOST, PORT);
  9140. cli.set_connection_timeout(std::chrono::seconds(5));
  9141. Headers headers = {{"Content-Encoding", "gzip"}};
  9142. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9143. "application/octet-stream");
  9144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9145. // Server must reject oversized decompressed payloads with 413.
  9146. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9147. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9148. EXPECT_LE(total, LIMIT);
  9149. }
  9150. #endif
  9151. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9152. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9153. // the payload must be passed through untouched instead of being rejected.
  9154. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9155. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9156. Server svr;
  9157. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9158. res.set_content(body, "image/jpeg");
  9159. res.set_header("Content-Encoding", "UTF-8");
  9160. });
  9161. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9162. res.set_content(body, "image/jpeg");
  9163. res.set_header("Content-Encoding", "identity");
  9164. });
  9165. svr.Post("/echo", [](const Request &req, Response &res) {
  9166. res.set_content(req.body, "image/jpeg");
  9167. });
  9168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9169. auto se = detail::scope_exit([&] {
  9170. svr.stop();
  9171. t.join();
  9172. ASSERT_FALSE(svr.is_running());
  9173. });
  9174. svr.wait_until_ready();
  9175. Client cli(HOST, PORT);
  9176. {
  9177. auto res = cli.Get("/image");
  9178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. EXPECT_EQ(body, res->body);
  9181. }
  9182. {
  9183. auto res = cli.Get("/identity");
  9184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9185. EXPECT_EQ(StatusCode::OK_200, res->status);
  9186. EXPECT_EQ(body, res->body);
  9187. }
  9188. {
  9189. // The same applies to a request body reaching the server.
  9190. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9191. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9193. EXPECT_EQ(StatusCode::OK_200, res->status);
  9194. EXPECT_EQ(body, res->body);
  9195. }
  9196. }
  9197. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9198. // gzip-encoded response even when the build has no zlib support.
  9199. static const char GZIPPED_HELLO_WORLD[] = {
  9200. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9201. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9202. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9203. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9204. // A content coding cpp-httplib recognizes but was not built with must be
  9205. // reported as such. Handing the still-compressed payload back to the caller
  9206. // would silently corrupt it.
  9207. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9208. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9209. Server svr;
  9210. // "image/jpeg" keeps the server from applying a content coding of its own,
  9211. // so the hand-crafted Content-Encoding below survives.
  9212. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9213. res.set_content(gzipped, "image/jpeg");
  9214. res.set_header("Content-Encoding", "gzip");
  9215. });
  9216. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9217. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9218. res.set_content(gzipped, "image/jpeg");
  9219. res.set_header("Content-Encoding", "GZIP");
  9220. });
  9221. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9222. auto se = detail::scope_exit([&] {
  9223. svr.stop();
  9224. t.join();
  9225. ASSERT_FALSE(svr.is_running());
  9226. });
  9227. svr.wait_until_ready();
  9228. Client cli(HOST, PORT);
  9229. {
  9230. auto res = cli.Get("/gzipped");
  9231. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9233. EXPECT_EQ("Hello World!", res->body);
  9234. #else
  9235. ASSERT_FALSE(res);
  9236. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9237. #endif
  9238. }
  9239. {
  9240. // open_stream() must behave the same way.
  9241. auto handle = cli.open_stream("GET", "/gzipped");
  9242. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9243. ASSERT_TRUE(handle.is_valid());
  9244. std::string received;
  9245. char buf[256];
  9246. ssize_t n;
  9247. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9248. received.append(buf, static_cast<size_t>(n));
  9249. }
  9250. EXPECT_EQ("Hello World!", received);
  9251. #else
  9252. EXPECT_FALSE(handle.is_valid());
  9253. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9254. #endif
  9255. }
  9256. {
  9257. // A differently-cased coding must not be mistaken for an unknown one, or
  9258. // the body would be handed back still compressed.
  9259. auto res = cli.Get("/gzipped-uppercase");
  9260. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9262. EXPECT_EQ("Hello World!", res->body);
  9263. #else
  9264. ASSERT_FALSE(res);
  9265. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9266. #endif
  9267. }
  9268. }
  9269. // Regression test for DoS vulnerability: a malicious server sending a response
  9270. // without Content-Length header must not cause unbounded memory consumption on
  9271. // the client side. The client should stop reading after a reasonable limit,
  9272. // similar to the server-side set_payload_max_length protection.
  9273. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9274. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9275. #ifndef _WIN32
  9276. signal(SIGPIPE, SIG_IGN);
  9277. #endif
  9278. auto server_thread = std::thread([] {
  9279. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9280. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9281. default_socket_options(srv);
  9282. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9283. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9284. sockaddr_in addr{};
  9285. addr.sin_family = AF_INET;
  9286. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9287. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9288. int opt = 1;
  9289. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9290. #ifdef _WIN32
  9291. reinterpret_cast<const char *>(&opt),
  9292. #else
  9293. &opt,
  9294. #endif
  9295. sizeof(opt));
  9296. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9297. ::listen(srv, 1);
  9298. sockaddr_in cli_addr{};
  9299. socklen_t cli_len = sizeof(cli_addr);
  9300. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9301. if (cli != INVALID_SOCKET) {
  9302. char buf[4096];
  9303. ::recv(cli, buf, sizeof(buf), 0);
  9304. // Malicious response: no Content-Length, no chunked encoding
  9305. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9306. "Connection: close\r\n"
  9307. "\r\n";
  9308. ::send(cli,
  9309. #ifdef _WIN32
  9310. static_cast<const char *>(response_header.c_str()),
  9311. static_cast<int>(response_header.size()),
  9312. #else
  9313. response_header.c_str(), response_header.size(),
  9314. #endif
  9315. 0);
  9316. // Send 10MB of data
  9317. std::string chunk(64 * 1024, 'A');
  9318. size_t total_sent = 0;
  9319. while (total_sent < MALICIOUS_DATA_SIZE) {
  9320. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9321. auto sent = ::send(cli,
  9322. #ifdef _WIN32
  9323. static_cast<const char *>(chunk.c_str()),
  9324. static_cast<int>(to_send),
  9325. #else
  9326. chunk.c_str(), to_send,
  9327. #endif
  9328. 0);
  9329. if (sent <= 0) break;
  9330. total_sent += static_cast<size_t>(sent);
  9331. }
  9332. detail::close_socket(cli);
  9333. }
  9334. detail::close_socket(srv);
  9335. });
  9336. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9337. size_t total_read = 0;
  9338. {
  9339. Client cli("127.0.0.1", PORT + 2);
  9340. cli.set_read_timeout(5, 0);
  9341. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9342. auto stream = cli.open_stream("GET", "/malicious");
  9343. ASSERT_TRUE(stream.is_valid());
  9344. char buffer[64 * 1024];
  9345. ssize_t n;
  9346. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9347. total_read += static_cast<size_t>(n);
  9348. }
  9349. } // StreamHandle and Client destroyed here, closing the socket
  9350. server_thread.join();
  9351. // With set_payload_max_length, the client must stop reading before consuming
  9352. // all 10MB. The read loop should be cut off at or near the configured limit.
  9353. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9354. << "Client read " << total_read << " bytes, exceeding the configured "
  9355. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9356. }
  9357. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9358. // the entire response body without truncation.
  9359. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9360. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9361. #ifndef _WIN32
  9362. signal(SIGPIPE, SIG_IGN);
  9363. #endif
  9364. auto server_thread = std::thread([] {
  9365. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9366. default_socket_options(srv);
  9367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9368. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9369. sockaddr_in addr{};
  9370. addr.sin_family = AF_INET;
  9371. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9372. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9373. int opt = 1;
  9374. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9375. #ifdef _WIN32
  9376. reinterpret_cast<const char *>(&opt),
  9377. #else
  9378. &opt,
  9379. #endif
  9380. sizeof(opt));
  9381. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9382. ::listen(srv, 1);
  9383. sockaddr_in cli_addr{};
  9384. socklen_t cli_len = sizeof(cli_addr);
  9385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9386. if (cli != INVALID_SOCKET) {
  9387. char buf[4096];
  9388. ::recv(cli, buf, sizeof(buf), 0);
  9389. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9390. "Connection: close\r\n"
  9391. "\r\n";
  9392. ::send(cli,
  9393. #ifdef _WIN32
  9394. static_cast<const char *>(response_header.c_str()),
  9395. static_cast<int>(response_header.size()),
  9396. #else
  9397. response_header.c_str(), response_header.size(),
  9398. #endif
  9399. 0);
  9400. std::string chunk(64 * 1024, 'A');
  9401. size_t total_sent = 0;
  9402. while (total_sent < DATA_SIZE) {
  9403. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9404. auto sent = ::send(cli,
  9405. #ifdef _WIN32
  9406. static_cast<const char *>(chunk.c_str()),
  9407. static_cast<int>(to_send),
  9408. #else
  9409. chunk.c_str(), to_send,
  9410. #endif
  9411. 0);
  9412. if (sent <= 0) break;
  9413. total_sent += static_cast<size_t>(sent);
  9414. }
  9415. #ifdef _WIN32
  9416. ::shutdown(cli, SD_SEND);
  9417. #else
  9418. ::shutdown(cli, SHUT_WR);
  9419. #endif
  9420. // Drain until the client closes its end, ensuring all data is delivered
  9421. char drain[1024];
  9422. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9423. detail::close_socket(cli);
  9424. }
  9425. detail::close_socket(srv);
  9426. });
  9427. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9428. size_t total_read = 0;
  9429. {
  9430. Client cli("127.0.0.1", PORT + 2);
  9431. cli.set_read_timeout(5, 0);
  9432. cli.set_payload_max_length(0); // 0 means no limit
  9433. auto stream = cli.open_stream("GET", "/data");
  9434. ASSERT_TRUE(stream.is_valid());
  9435. char buffer[64 * 1024];
  9436. ssize_t n;
  9437. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9438. total_read += static_cast<size_t>(n);
  9439. }
  9440. }
  9441. server_thread.join();
  9442. EXPECT_EQ(total_read, DATA_SIZE)
  9443. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9444. << " bytes without truncation, but only read " << total_read << " bytes.";
  9445. }
  9446. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9447. // enormous Content-Length must not cause the client to pre-allocate a huge
  9448. // response body buffer. The reservation is capped at payload_max_length_, and
  9449. // the read itself fails when the body exceeds the limit.
  9450. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9451. #ifndef _WIN32
  9452. signal(SIGPIPE, SIG_IGN);
  9453. #endif
  9454. auto server_thread = std::thread([] {
  9455. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9456. default_socket_options(srv);
  9457. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9458. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9459. sockaddr_in addr{};
  9460. addr.sin_family = AF_INET;
  9461. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9462. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9463. int opt = 1;
  9464. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9465. #ifdef _WIN32
  9466. reinterpret_cast<const char *>(&opt),
  9467. #else
  9468. &opt,
  9469. #endif
  9470. sizeof(opt));
  9471. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9472. ::listen(srv, 1);
  9473. sockaddr_in cli_addr{};
  9474. socklen_t cli_len = sizeof(cli_addr);
  9475. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9476. if (cli != INVALID_SOCKET) {
  9477. char buf[4096];
  9478. ::recv(cli, buf, sizeof(buf), 0);
  9479. // Malicious response: claim a 20GB body but send only a tiny payload.
  9480. std::string response = "HTTP/1.1 200 OK\r\n"
  9481. "Content-Length: 20000000000\r\n"
  9482. "\r\n"
  9483. "abc";
  9484. ::send(cli,
  9485. #ifdef _WIN32
  9486. static_cast<const char *>(response.c_str()),
  9487. static_cast<int>(response.size()),
  9488. #else
  9489. response.c_str(), response.size(),
  9490. #endif
  9491. 0);
  9492. detail::close_socket(cli);
  9493. }
  9494. detail::close_socket(srv);
  9495. });
  9496. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9497. {
  9498. Client cli("127.0.0.1", PORT + 2);
  9499. cli.set_read_timeout(5, 0);
  9500. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9501. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9502. // (server claims more bytes than payload_max_length permits), but it must
  9503. // not exhaust memory before getting there.
  9504. auto res = cli.Get("/malicious");
  9505. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9506. }
  9507. server_thread.join();
  9508. }
  9509. // Verify that content_receiver bypasses the default payload_max_length,
  9510. // allowing streaming downloads larger than 100MB without requiring an explicit
  9511. // set_payload_max_length call.
  9512. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9513. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9514. #ifndef _WIN32
  9515. signal(SIGPIPE, SIG_IGN);
  9516. #endif
  9517. auto server_thread = std::thread([] {
  9518. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9519. default_socket_options(srv);
  9520. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9521. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9522. sockaddr_in addr{};
  9523. addr.sin_family = AF_INET;
  9524. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9525. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9526. int opt = 1;
  9527. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9528. #ifdef _WIN32
  9529. reinterpret_cast<const char *>(&opt),
  9530. #else
  9531. &opt,
  9532. #endif
  9533. sizeof(opt));
  9534. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9535. ::listen(srv, 1);
  9536. sockaddr_in cli_addr{};
  9537. socklen_t cli_len = sizeof(cli_addr);
  9538. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9539. if (cli != INVALID_SOCKET) {
  9540. char buf[4096];
  9541. ::recv(cli, buf, sizeof(buf), 0);
  9542. // Response with Content-Length larger than default 100MB limit
  9543. auto content_length = std::to_string(DATA_SIZE);
  9544. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9545. "Content-Length: " +
  9546. content_length +
  9547. "\r\n"
  9548. "Connection: close\r\n"
  9549. "\r\n";
  9550. ::send(cli,
  9551. #ifdef _WIN32
  9552. static_cast<const char *>(response_header.c_str()),
  9553. static_cast<int>(response_header.size()),
  9554. #else
  9555. response_header.c_str(), response_header.size(),
  9556. #endif
  9557. 0);
  9558. std::string chunk(64 * 1024, 'A');
  9559. size_t total_sent = 0;
  9560. while (total_sent < DATA_SIZE) {
  9561. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9562. auto sent = ::send(cli,
  9563. #ifdef _WIN32
  9564. static_cast<const char *>(chunk.c_str()),
  9565. static_cast<int>(to_send),
  9566. #else
  9567. chunk.c_str(), to_send,
  9568. #endif
  9569. 0);
  9570. if (sent <= 0) break;
  9571. total_sent += static_cast<size_t>(sent);
  9572. }
  9573. detail::close_socket(cli);
  9574. }
  9575. detail::close_socket(srv);
  9576. });
  9577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9578. size_t total_received = 0;
  9579. {
  9580. Client cli("127.0.0.1", PORT + 2);
  9581. cli.set_read_timeout(10, 0);
  9582. // Do NOT call set_payload_max_length — use the default 100MB limit
  9583. auto res =
  9584. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9585. total_received += data_length;
  9586. return true;
  9587. });
  9588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9589. EXPECT_EQ(StatusCode::OK_200, res->status);
  9590. }
  9591. server_thread.join();
  9592. EXPECT_EQ(total_received, DATA_SIZE)
  9593. << "With content_receiver, the client should read all " << DATA_SIZE
  9594. << " bytes despite the default 100MB payload_max_length, but only read "
  9595. << total_received << " bytes.";
  9596. }
  9597. // Verify that an explicit set_payload_max_length smaller than the response is
  9598. // enforced even when a content_receiver is used.
  9599. TEST(ClientVulnerabilityTest,
  9600. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9601. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9602. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9603. #ifndef _WIN32
  9604. signal(SIGPIPE, SIG_IGN);
  9605. #endif
  9606. auto server_thread = std::thread([] {
  9607. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9608. default_socket_options(srv);
  9609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9610. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9611. sockaddr_in addr{};
  9612. addr.sin_family = AF_INET;
  9613. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9614. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9615. int opt = 1;
  9616. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9617. #ifdef _WIN32
  9618. reinterpret_cast<const char *>(&opt),
  9619. #else
  9620. &opt,
  9621. #endif
  9622. sizeof(opt));
  9623. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9624. ::listen(srv, 1);
  9625. sockaddr_in cli_addr{};
  9626. socklen_t cli_len = sizeof(cli_addr);
  9627. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9628. if (cli != INVALID_SOCKET) {
  9629. char buf[4096];
  9630. ::recv(cli, buf, sizeof(buf), 0);
  9631. auto content_length = std::to_string(DATA_SIZE);
  9632. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9633. "Content-Length: " +
  9634. content_length +
  9635. "\r\n"
  9636. "Connection: close\r\n"
  9637. "\r\n";
  9638. ::send(cli,
  9639. #ifdef _WIN32
  9640. static_cast<const char *>(response_header.c_str()),
  9641. static_cast<int>(response_header.size()),
  9642. #else
  9643. response_header.c_str(), response_header.size(),
  9644. #endif
  9645. 0);
  9646. std::string chunk(64 * 1024, 'A');
  9647. size_t total_sent = 0;
  9648. while (total_sent < DATA_SIZE) {
  9649. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9650. auto sent = ::send(cli,
  9651. #ifdef _WIN32
  9652. static_cast<const char *>(chunk.c_str()),
  9653. static_cast<int>(to_send),
  9654. #else
  9655. chunk.c_str(), to_send,
  9656. #endif
  9657. 0);
  9658. if (sent <= 0) break;
  9659. total_sent += static_cast<size_t>(sent);
  9660. }
  9661. detail::close_socket(cli);
  9662. }
  9663. detail::close_socket(srv);
  9664. });
  9665. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9666. size_t total_received = 0;
  9667. {
  9668. Client cli("127.0.0.1", PORT + 2);
  9669. cli.set_read_timeout(10, 0);
  9670. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9671. auto res =
  9672. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9673. total_received += data_length;
  9674. return true;
  9675. });
  9676. // Should fail because 200MB exceeds the explicit 150MB limit
  9677. EXPECT_FALSE(res);
  9678. }
  9679. server_thread.join();
  9680. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9681. << "Client with content_receiver should respect the explicit "
  9682. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9683. << total_received << " bytes.";
  9684. }
  9685. // Verify that an explicit set_payload_max_length larger than the response
  9686. // allows the content_receiver to read all data successfully.
  9687. TEST(ClientVulnerabilityTest,
  9688. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9689. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9690. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9691. #ifndef _WIN32
  9692. signal(SIGPIPE, SIG_IGN);
  9693. #endif
  9694. auto server_thread = std::thread([] {
  9695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9696. default_socket_options(srv);
  9697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9699. sockaddr_in addr{};
  9700. addr.sin_family = AF_INET;
  9701. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9702. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9703. int opt = 1;
  9704. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9705. #ifdef _WIN32
  9706. reinterpret_cast<const char *>(&opt),
  9707. #else
  9708. &opt,
  9709. #endif
  9710. sizeof(opt));
  9711. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9712. ::listen(srv, 1);
  9713. sockaddr_in cli_addr{};
  9714. socklen_t cli_len = sizeof(cli_addr);
  9715. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9716. if (cli != INVALID_SOCKET) {
  9717. char buf[4096];
  9718. ::recv(cli, buf, sizeof(buf), 0);
  9719. auto content_length = std::to_string(DATA_SIZE);
  9720. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9721. "Content-Length: " +
  9722. content_length +
  9723. "\r\n"
  9724. "Connection: close\r\n"
  9725. "\r\n";
  9726. ::send(cli,
  9727. #ifdef _WIN32
  9728. static_cast<const char *>(response_header.c_str()),
  9729. static_cast<int>(response_header.size()),
  9730. #else
  9731. response_header.c_str(), response_header.size(),
  9732. #endif
  9733. 0);
  9734. std::string chunk(64 * 1024, 'A');
  9735. size_t total_sent = 0;
  9736. while (total_sent < DATA_SIZE) {
  9737. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9738. auto sent = ::send(cli,
  9739. #ifdef _WIN32
  9740. static_cast<const char *>(chunk.c_str()),
  9741. static_cast<int>(to_send),
  9742. #else
  9743. chunk.c_str(), to_send,
  9744. #endif
  9745. 0);
  9746. if (sent <= 0) break;
  9747. total_sent += static_cast<size_t>(sent);
  9748. }
  9749. #ifdef _WIN32
  9750. ::shutdown(cli, SD_SEND);
  9751. #else
  9752. ::shutdown(cli, SHUT_WR);
  9753. #endif
  9754. char drain[1024];
  9755. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9756. detail::close_socket(cli);
  9757. }
  9758. detail::close_socket(srv);
  9759. });
  9760. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9761. size_t total_received = 0;
  9762. {
  9763. Client cli("127.0.0.1", PORT + 2);
  9764. cli.set_read_timeout(10, 0);
  9765. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9766. auto res =
  9767. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9768. total_received += data_length;
  9769. return true;
  9770. });
  9771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9772. EXPECT_EQ(StatusCode::OK_200, res->status);
  9773. }
  9774. server_thread.join();
  9775. EXPECT_EQ(total_received, DATA_SIZE)
  9776. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9777. << " bytes (larger than " << DATA_SIZE
  9778. << " bytes response), content_receiver should read all data, but only "
  9779. "read "
  9780. << total_received << " bytes.";
  9781. }
  9782. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9783. // Regression test for "zip bomb" attack on the client side: a malicious server
  9784. // sends a small gzip-compressed response that decompresses to a huge payload.
  9785. // The client must enforce payload_max_length on the decompressed size.
  9786. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9787. constexpr size_t DECOMPRESSED_SIZE =
  9788. 10 * 1024 * 1024; // 10MB after decompression
  9789. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9790. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9791. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9792. std::string compressed;
  9793. {
  9794. httplib::detail::gzip_compressor compressor;
  9795. bool ok =
  9796. compressor.compress(uncompressed.data(), uncompressed.size(),
  9797. /*last=*/true, [&](const char *buf, size_t len) {
  9798. compressed.append(buf, len);
  9799. return true;
  9800. });
  9801. ASSERT_TRUE(ok);
  9802. }
  9803. // Sanity: compressed data should be much smaller than the decompressed size
  9804. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9805. #ifndef _WIN32
  9806. signal(SIGPIPE, SIG_IGN);
  9807. #endif
  9808. // Set up the listening socket in the main thread so the server is guaranteed
  9809. // to be ready before the client connects (eliminates race condition).
  9810. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9811. default_socket_options(srv);
  9812. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9813. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9814. sockaddr_in addr{};
  9815. addr.sin_family = AF_INET;
  9816. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9817. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9818. int opt = 1;
  9819. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9820. #ifdef _WIN32
  9821. reinterpret_cast<const char *>(&opt),
  9822. #else
  9823. &opt,
  9824. #endif
  9825. sizeof(opt));
  9826. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9827. ASSERT_EQ(0, ::listen(srv, 1));
  9828. auto server_thread = std::thread([&compressed, srv] {
  9829. sockaddr_in cli_addr{};
  9830. socklen_t cli_len = sizeof(cli_addr);
  9831. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9832. if (cli != INVALID_SOCKET) {
  9833. // Read the full HTTP request (until \r\n\r\n)
  9834. char buf[4096];
  9835. size_t total = 0;
  9836. while (total < sizeof(buf)) {
  9837. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9838. if (n <= 0) break;
  9839. total += static_cast<size_t>(n);
  9840. // Check for end of headers
  9841. if (total >= 4) {
  9842. std::string req(buf, total);
  9843. if (req.find("\r\n\r\n") != std::string::npos) break;
  9844. }
  9845. }
  9846. // Malicious response: gzip-compressed body, no Content-Length
  9847. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9848. "Content-Encoding: gzip\r\n"
  9849. "Connection: close\r\n"
  9850. "\r\n";
  9851. ::send(cli,
  9852. #ifdef _WIN32
  9853. static_cast<const char *>(response_header.c_str()),
  9854. static_cast<int>(response_header.size()),
  9855. #else
  9856. response_header.c_str(), response_header.size(),
  9857. #endif
  9858. 0);
  9859. // Send the compressed payload (small on the wire, huge when decompressed)
  9860. size_t total_sent = 0;
  9861. while (total_sent < compressed.size()) {
  9862. auto to_send = std::min(compressed.size() - total_sent,
  9863. static_cast<size_t>(64 * 1024));
  9864. auto sent =
  9865. ::send(cli,
  9866. #ifdef _WIN32
  9867. static_cast<const char *>(compressed.c_str() + total_sent),
  9868. static_cast<int>(to_send),
  9869. #else
  9870. compressed.c_str() + total_sent, to_send,
  9871. #endif
  9872. 0);
  9873. if (sent <= 0) break;
  9874. total_sent += static_cast<size_t>(sent);
  9875. }
  9876. detail::close_socket(cli);
  9877. }
  9878. });
  9879. auto se = detail::scope_exit([&] {
  9880. detail::close_socket(srv);
  9881. server_thread.join();
  9882. });
  9883. size_t total_decompressed = 0;
  9884. {
  9885. Client cli("127.0.0.1", PORT + 3);
  9886. cli.set_read_timeout(5, 0);
  9887. cli.set_decompress(true);
  9888. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9889. auto stream = cli.open_stream("GET", "/zipbomb");
  9890. ASSERT_TRUE(stream.is_valid());
  9891. char buffer[64 * 1024];
  9892. ssize_t n;
  9893. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9894. total_decompressed += static_cast<size_t>(n);
  9895. }
  9896. }
  9897. // The decompressed size must be capped by payload_max_length. Without
  9898. // protection, the client would decompress the full 10MB from a tiny
  9899. // compressed payload, enabling a zip bomb DoS attack.
  9900. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9901. << "Client decompressed " << total_decompressed
  9902. << " bytes from a gzip response. The decompressed size should be "
  9903. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9904. }
  9905. #endif
  9906. TEST(HostAndPortPropertiesTest, NoSSL) {
  9907. httplib::Client cli("www.google.com", 1234);
  9908. ASSERT_EQ("www.google.com", cli.host());
  9909. ASSERT_EQ(1234, cli.port());
  9910. }
  9911. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9912. httplib::Client cli("www.google.com:1234");
  9913. ASSERT_EQ("www.google.com", cli.host());
  9914. ASSERT_EQ(1234, cli.port());
  9915. }
  9916. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9917. // Port number that overflows int — should not crash, client becomes invalid
  9918. httplib::Client cli("http://www.google.com:99999999999999999999");
  9919. ASSERT_FALSE(cli.is_valid());
  9920. }
  9921. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9922. // Port 99999 exceeds valid range (1-65535) — should not crash
  9923. httplib::Client cli("http://www.google.com:99999");
  9924. ASSERT_FALSE(cli.is_valid());
  9925. }
  9926. #ifdef CPPHTTPLIB_SSL_ENABLED
  9927. TEST(HostAndPortPropertiesTest, SSL) {
  9928. httplib::SSLClient cli("www.google.com");
  9929. ASSERT_EQ("www.google.com", cli.host());
  9930. ASSERT_EQ(443, cli.port());
  9931. }
  9932. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9933. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9934. std::string cert;
  9935. read_file(CA_CERT_FILE, cert);
  9936. httplib::SSLClient httplib_client("www.google.com");
  9937. // Load CA store first time
  9938. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9939. // Load CA store second time (update)
  9940. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9941. // Verify client is still valid and can make connections
  9942. httplib_client.enable_server_certificate_verification(true);
  9943. auto res = httplib_client.Get("/");
  9944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9945. // Google may return 200 or 301 depending on various factors
  9946. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9947. res->status == StatusCode::MovedPermanently_301);
  9948. }
  9949. TEST(SSLClientTest, ServerNameIndication_Online) {
  9950. auto host = "httpbingo.org";
  9951. auto path = std::string{"/get"};
  9952. SSLClient cli(host, 443);
  9953. auto res = cli.Get(path);
  9954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9955. ASSERT_EQ(StatusCode::OK_200, res->status);
  9956. }
  9957. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9958. // Use a site that will cause SSL verification failure due to self-signed cert
  9959. SSLClient cli("self-signed.badssl.com", 443);
  9960. cli.enable_server_certificate_verification(true);
  9961. auto res = cli.Get("/");
  9962. ASSERT_TRUE(!res);
  9963. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9964. // Verify backend error is captured for SSLServerVerification
  9965. // This occurs when certificate verification fails
  9966. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9967. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9968. EXPECT_NE(0UL, res.ssl_backend_error());
  9969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9970. // For OpenSSL, ssl_error is 0 for verification errors
  9971. EXPECT_EQ(0, res.ssl_error());
  9972. #if !defined(_WIN32) || \
  9973. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9974. // On non-Windows or when Windows Schannel is disabled, the error comes
  9975. // from OpenSSL's verification
  9976. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9977. res.ssl_backend_error());
  9978. #endif
  9979. #endif
  9980. }
  9981. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9982. // Use a site where hostname doesn't match the certificate
  9983. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9984. SSLClient cli("wrong.host.badssl.com", 443);
  9985. cli.enable_server_certificate_verification(true);
  9986. cli.enable_server_hostname_verification(true);
  9987. auto res = cli.Get("/");
  9988. ASSERT_TRUE(!res);
  9989. // The error type depends on when hostname verification occurs:
  9990. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9991. // - Mbed TLS: SSLServerVerification (during handshake)
  9992. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9993. res.error() == Error::SSLServerVerification);
  9994. // Verify backend error is captured for hostname verification failure
  9995. EXPECT_NE(0UL, res.ssl_backend_error());
  9996. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9997. // For OpenSSL, ssl_error is 0 for verification errors
  9998. EXPECT_EQ(0, res.ssl_error());
  9999. #if !defined(_WIN32) || \
  10000. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10001. // On non-Windows or when Windows Schannel is disabled, the error comes
  10002. // from OpenSSL's hostname verification
  10003. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10004. res.ssl_backend_error());
  10005. #endif
  10006. #endif
  10007. }
  10008. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10009. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10010. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10011. SSLClient cli("www.google.com", 443);
  10012. cli.enable_server_certificate_verification(true);
  10013. auto res = cli.Get("/");
  10014. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10015. }
  10016. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10017. SSLClient cli("www.google.com", 443);
  10018. cli.enable_server_certificate_verification(true);
  10019. cli.enable_windows_certificate_verification(false);
  10020. auto res = cli.Get("/");
  10021. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10022. }
  10023. #endif
  10024. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10025. Client cli("https://google.com");
  10026. auto res = cli.Get("/");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10029. }
  10030. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10031. SSLClient cli("google.com");
  10032. cli.set_ca_cert_path(CA_CERT_FILE);
  10033. auto res = cli.Get("/");
  10034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10035. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10036. }
  10037. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10038. SSLClient cli("google.com");
  10039. cli.enable_server_certificate_verification(true);
  10040. cli.set_ca_cert_path("hello");
  10041. auto res = cli.Get("/");
  10042. ASSERT_TRUE(!res);
  10043. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10044. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10045. // should be set
  10046. EXPECT_EQ(0, res.ssl_error());
  10047. // Verify backend error is captured for SSLLoadingCerts
  10048. // This error occurs when loading CA certificates fails
  10049. EXPECT_NE(0UL, res.ssl_backend_error());
  10050. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10051. // OpenSSL specific error codes:
  10052. // > openssl errstr 0x80000002
  10053. // error:80000002:system library::No such file or directory
  10054. // > openssl errstr 0xA000126
  10055. // error:0A000126:SSL routines::unexpected eof while reading
  10056. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10057. res.ssl_backend_error() == 0xA000126);
  10058. #endif
  10059. }
  10060. TEST(SSLClientTest, ServerCertificateVerification4) {
  10061. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10062. ASSERT_TRUE(svr.is_valid());
  10063. svr.Get("/test", [&](const Request &, Response &res) {
  10064. res.set_content("test", "text/plain");
  10065. svr.stop();
  10066. ASSERT_TRUE(true);
  10067. });
  10068. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10069. auto se = detail::scope_exit([&] {
  10070. t.join();
  10071. ASSERT_FALSE(svr.is_running());
  10072. });
  10073. svr.wait_until_ready();
  10074. SSLClient cli("127.0.0.1", PORT);
  10075. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10076. cli.enable_server_certificate_verification(true);
  10077. cli.set_connection_timeout(30);
  10078. auto res = cli.Get("/test");
  10079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10080. ASSERT_EQ(StatusCode::OK_200, res->status);
  10081. }
  10082. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10083. std::string cert;
  10084. read_file(CA_CERT_FILE, cert);
  10085. SSLClient cli("google.com");
  10086. cli.load_ca_cert_store(cert.data(), cert.size());
  10087. const auto res = cli.Get("/");
  10088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10089. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10090. }
  10091. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10092. // clang-format off
  10093. static constexpr char cert[] =
  10094. "GlobalSign Root CA\n"
  10095. "==================\n"
  10096. "-----BEGIN CERTIFICATE-----\n"
  10097. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10098. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10099. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10100. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10101. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10102. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10103. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10104. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10105. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10106. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10107. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10108. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10109. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10110. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10111. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10112. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10113. "-----END CERTIFICATE-----\n";
  10114. // clang-format on
  10115. SSLClient cli("google.com");
  10116. cli.load_ca_cert_store(cert, sizeof(cert));
  10117. const auto res = cli.Get("/");
  10118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10119. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10120. }
  10121. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10122. SSLClient cli("www.youtube.com");
  10123. cli.set_ca_cert_path(CA_CERT_FILE);
  10124. cli.enable_server_certificate_verification(true);
  10125. cli.set_follow_location(true);
  10126. auto res = cli.Get("/");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. ASSERT_EQ(StatusCode::OK_200, res->status);
  10129. }
  10130. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10131. SSLClient cli("wWw.YouTube.Com");
  10132. cli.set_ca_cert_path(CA_CERT_FILE);
  10133. cli.enable_server_certificate_verification(true);
  10134. cli.enable_server_hostname_verification(true);
  10135. cli.set_follow_location(true);
  10136. auto res = cli.Get("/");
  10137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10138. ASSERT_EQ(StatusCode::OK_200, res->status);
  10139. }
  10140. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10141. SSLClient cli("gOoGlE.COm");
  10142. cli.enable_server_certificate_verification(true);
  10143. cli.enable_server_hostname_verification(true);
  10144. cli.set_follow_location(true);
  10145. auto res = cli.Get("/");
  10146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10147. ASSERT_EQ(StatusCode::OK_200, res->status);
  10148. }
  10149. TEST(SSLClientTest, Issue2004_Online) {
  10150. Client client("https://google.com");
  10151. client.set_follow_location(true);
  10152. auto res = client.Get("/");
  10153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10154. ASSERT_EQ(StatusCode::OK_200, res->status);
  10155. auto body = res->body;
  10156. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10157. }
  10158. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10159. // Create SSLClient with invalid cert/key to make is_valid() return false
  10160. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10161. "nonexistent_key.pem");
  10162. // is_valid() should be false due to cert loading failure
  10163. ASSERT_FALSE(cli.is_valid());
  10164. auto res = cli.Get("/");
  10165. ASSERT_FALSE(res);
  10166. EXPECT_EQ(Error::SSLConnection, res.error());
  10167. }
  10168. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10169. // Test for Issue #2251: SSL error not properly reported when client cert
  10170. // and key paths are swapped or mismatched
  10171. // This simulates the scenario where user accidentally swaps the cert and key
  10172. // files
  10173. // Using client cert file as private key and vice versa (completely wrong)
  10174. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10175. // Should fail validation due to cert/key mismatch
  10176. ASSERT_FALSE(cli.is_valid());
  10177. // Attempt to make a request should fail with proper error
  10178. auto res = cli.Get("/");
  10179. ASSERT_FALSE(res);
  10180. EXPECT_EQ(Error::SSLConnection, res.error());
  10181. // SSL error should be recorded in the Result object (this is the key fix for
  10182. // Issue #2251)
  10183. auto backend_error = res.ssl_backend_error();
  10184. EXPECT_NE(0u, backend_error);
  10185. }
  10186. // Tests cert/key mismatch detection at the TLS context level
  10187. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10188. // Test that using mismatched cert/key causes connection failure.
  10189. // We verify this at the SSLClient level rather than through internal
  10190. // TLS API functions.
  10191. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10192. cli.enable_server_certificate_verification(false);
  10193. cli.set_connection_timeout(2);
  10194. // The mismatch should cause a connection or handshake error
  10195. auto res = cli.Get("/test");
  10196. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10197. // Either way, the request should fail
  10198. EXPECT_FALSE(res);
  10199. }
  10200. #endif
  10201. #if 0
  10202. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10203. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10204. ASSERT_TRUE(cli != nullptr);
  10205. cli->set_address_family(AF_INET6);
  10206. cli->set_interface("en0");
  10207. auto res = cli->Get("/get");
  10208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10209. ASSERT_EQ(StatusCode::OK_200, res->status);
  10210. }
  10211. #endif
  10212. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10213. #ifdef CPPHTTPLIB_SSL_ENABLED
  10214. void ClientCertPresent(
  10215. const std::string &client_cert_file,
  10216. const std::string &client_private_key_file,
  10217. const std::string &client_encrypted_private_key_pass = std::string()) {
  10218. using namespace httplib::tls;
  10219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10220. CLIENT_CA_CERT_DIR);
  10221. ASSERT_TRUE(svr.is_valid());
  10222. svr.Get("/test", [&](const Request &req, Response &res) {
  10223. res.set_content("test", "text/plain");
  10224. auto cert = req.peer_cert();
  10225. ASSERT_TRUE(static_cast<bool>(cert));
  10226. std::string common_name = cert.subject_cn();
  10227. EXPECT_EQ("Common Name", common_name);
  10228. });
  10229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10230. auto se = detail::scope_exit([&] {
  10231. svr.stop();
  10232. t.join();
  10233. ASSERT_FALSE(svr.is_running());
  10234. });
  10235. svr.wait_until_ready();
  10236. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10237. client_encrypted_private_key_pass);
  10238. cli.enable_server_certificate_verification(false);
  10239. cli.set_connection_timeout(30);
  10240. auto res = cli.Get("/test");
  10241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10242. ASSERT_EQ(StatusCode::OK_200, res->status);
  10243. }
  10244. TEST(SSLClientServerTest, ClientCertPresent) {
  10245. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10246. }
  10247. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10248. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10249. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10250. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10251. }
  10252. // PEM memory-based constructor tests (works with all TLS backends)
  10253. void PemMemoryClientCertPresent(
  10254. const std::string &client_cert_file,
  10255. const std::string &client_private_key_file,
  10256. const std::string &client_encrypted_private_key_pass = std::string()) {
  10257. // Read PEM files into memory
  10258. std::string server_cert_pem, server_key_pem;
  10259. std::string client_ca_pem;
  10260. std::string client_cert_pem, client_key_pem;
  10261. read_file(SERVER_CERT_FILE, server_cert_pem);
  10262. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10263. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10264. read_file(client_cert_file, client_cert_pem);
  10265. read_file(client_private_key_file, client_key_pem);
  10266. // Create server with PEM memory
  10267. SSLServer::PemMemory server_pem = {
  10268. server_cert_pem.c_str(),
  10269. server_cert_pem.size(),
  10270. server_key_pem.c_str(),
  10271. server_key_pem.size(),
  10272. client_ca_pem.c_str(),
  10273. client_ca_pem.size(),
  10274. nullptr // no password for server key
  10275. };
  10276. SSLServer svr(server_pem);
  10277. ASSERT_TRUE(svr.is_valid());
  10278. svr.Get("/test", [&](const Request &, Response &res) {
  10279. res.set_content("test", "text/plain");
  10280. });
  10281. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. ASSERT_FALSE(svr.is_running());
  10286. });
  10287. svr.wait_until_ready();
  10288. // Create client with PEM memory
  10289. const char *password = client_encrypted_private_key_pass.empty()
  10290. ? nullptr
  10291. : client_encrypted_private_key_pass.c_str();
  10292. SSLClient::PemMemory client_pem = {
  10293. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10294. client_key_pem.size(), password};
  10295. SSLClient cli(HOST, PORT, client_pem);
  10296. cli.enable_server_certificate_verification(false);
  10297. cli.set_connection_timeout(30);
  10298. auto res = cli.Get("/test");
  10299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10300. ASSERT_EQ(StatusCode::OK_200, res->status);
  10301. }
  10302. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10303. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10304. }
  10305. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10306. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10307. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10308. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10309. }
  10310. TEST(SSLClientServerTest, ClientCertMissing) {
  10311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10312. CLIENT_CA_CERT_DIR);
  10313. ASSERT_TRUE(svr.is_valid());
  10314. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10316. auto se = detail::scope_exit([&] {
  10317. svr.stop();
  10318. t.join();
  10319. ASSERT_FALSE(svr.is_running());
  10320. });
  10321. svr.wait_until_ready();
  10322. SSLClient cli(HOST, PORT);
  10323. cli.set_connection_timeout(30);
  10324. auto res = cli.Get("/test");
  10325. ASSERT_TRUE(!res);
  10326. // When client cert is missing and server requires it, connection fails
  10327. // Error type depends on backend implementation
  10328. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10329. res.error() == Error::SSLConnection);
  10330. // Verify backend error is captured
  10331. // Note: This test may have different error codes depending on the exact
  10332. // verification failure
  10333. EXPECT_NE(0UL, res.ssl_backend_error());
  10334. }
  10335. TEST(SSLClientServerTest, TrustDirOptional) {
  10336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10337. ASSERT_TRUE(svr.is_valid());
  10338. svr.Get("/test", [&](const Request &, Response &res) {
  10339. res.set_content("test", "text/plain");
  10340. });
  10341. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10342. auto se = detail::scope_exit([&] {
  10343. svr.stop();
  10344. t.join();
  10345. ASSERT_FALSE(svr.is_running());
  10346. });
  10347. svr.wait_until_ready();
  10348. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10349. cli.enable_server_certificate_verification(false);
  10350. cli.set_connection_timeout(30);
  10351. auto res = cli.Get("/test");
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. ASSERT_EQ(StatusCode::OK_200, res->status);
  10354. }
  10355. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10356. class NoListenSSLServer : public SSLServer {
  10357. public:
  10358. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10359. const char *client_ca_cert_file_path,
  10360. const char *client_ca_cert_dir_path = nullptr)
  10361. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10362. client_ca_cert_dir_path),
  10363. stop_(false) {}
  10364. std::atomic_bool stop_;
  10365. private:
  10366. bool process_and_close_socket(socket_t /*sock*/) override {
  10367. // Don't create SSL context
  10368. while (!stop_.load()) {
  10369. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10370. }
  10371. return true;
  10372. }
  10373. };
  10374. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10375. CLIENT_CA_CERT_FILE);
  10376. ASSERT_TRUE(svr.is_valid());
  10377. svr.Get("/test", [&](const Request &, Response &res) {
  10378. res.set_content("test", "text/plain");
  10379. });
  10380. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10381. auto se = detail::scope_exit([&] {
  10382. svr.stop_ = true;
  10383. svr.stop();
  10384. t.join();
  10385. ASSERT_FALSE(svr.is_running());
  10386. });
  10387. svr.wait_until_ready();
  10388. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10389. cli.enable_server_certificate_verification(false);
  10390. cli.set_connection_timeout(1);
  10391. auto res = cli.Get("/test");
  10392. ASSERT_TRUE(!res);
  10393. EXPECT_EQ(Error::SSLConnection, res.error());
  10394. // Timeout results in WantRead error code (maps to backend-specific value)
  10395. EXPECT_NE(0, res.ssl_error());
  10396. }
  10397. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10398. // Test SSLServer with client certificate verification using the standard
  10399. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10401. CLIENT_CA_CERT_DIR);
  10402. ASSERT_TRUE(svr.is_valid());
  10403. svr.Get("/test", [&](const Request &req, Response &res) {
  10404. res.set_content("test", "text/plain");
  10405. auto cert = req.peer_cert();
  10406. ASSERT_TRUE(static_cast<bool>(cert));
  10407. auto common_name = cert.subject_cn();
  10408. EXPECT_EQ("Common Name", common_name);
  10409. });
  10410. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10411. auto se = detail::scope_exit([&] {
  10412. svr.stop();
  10413. t.join();
  10414. ASSERT_FALSE(svr.is_running());
  10415. });
  10416. svr.wait_until_ready();
  10417. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10418. cli.enable_server_certificate_verification(false);
  10419. cli.set_connection_timeout(30);
  10420. auto res = cli.Get("/test");
  10421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10422. ASSERT_EQ(StatusCode::OK_200, res->status);
  10423. }
  10424. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10425. // Verifies that wildcard matching and exact matching work consistently
  10426. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10427. using namespace httplib::tls;
  10428. // We need a running server to test against
  10429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10430. ASSERT_TRUE(svr.is_valid());
  10431. svr.Get("/test", [](const Request &, Response &res) {
  10432. res.set_content("ok", "text/plain");
  10433. });
  10434. thread t([&]() { svr.listen(HOST, PORT); });
  10435. auto se = detail::scope_exit([&] {
  10436. svr.stop();
  10437. t.join();
  10438. });
  10439. svr.wait_until_ready();
  10440. bool verify_callback_called = false;
  10441. bool verify_result_wrong = false;
  10442. SSLClient cli(HOST, PORT);
  10443. cli.enable_server_certificate_verification(true);
  10444. cli.set_ca_cert_path(CA_CERT_FILE);
  10445. cli.set_connection_timeout(5);
  10446. // Note: Test certificate has CN="Common Name", not "localhost"
  10447. bool verify_result_cn = false;
  10448. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10449. verify_callback_called = true;
  10450. if (!ctx.cert) return false;
  10451. // Test 1: "Common Name" should match (our test server cert CN)
  10452. verify_result_cn = ctx.check_hostname("Common Name");
  10453. // Test 2: wrong hostname should not match
  10454. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10455. return true; // Accept for the purpose of this test
  10456. });
  10457. auto res = cli.Get("/test");
  10458. // The request may succeed or fail depending on cert configuration
  10459. // but the callback should have been called
  10460. ASSERT_TRUE(verify_callback_called)
  10461. << "Verify callback should have been called";
  10462. // CN="Common Name" should match our test certificate
  10463. //
  10464. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10465. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10466. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10467. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10468. // <openssl/base.h>, which is included transitively when
  10469. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10470. #if defined(OPENSSL_IS_BORINGSSL)
  10471. EXPECT_FALSE(verify_result_cn)
  10472. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10473. #else
  10474. EXPECT_TRUE(verify_result_cn)
  10475. << "verify_hostname should match 'Common Name' (certificate CN)";
  10476. #endif
  10477. // Wrong hostname should not match
  10478. EXPECT_FALSE(verify_result_wrong)
  10479. << "verify_hostname should not match 'wronghost.example.com'";
  10480. }
  10481. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10482. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10483. // X509_check_ip behavior and must hold for every backend.
  10484. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10485. using namespace httplib::tls;
  10486. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10487. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10488. ASSERT_TRUE(svr.is_valid());
  10489. svr.Get("/test", [](const Request &, Response &res) {
  10490. res.set_content("ok", "text/plain");
  10491. });
  10492. thread t([&]() { svr.listen(HOST, PORT); });
  10493. auto se = detail::scope_exit([&] {
  10494. svr.stop();
  10495. t.join();
  10496. });
  10497. svr.wait_until_ready();
  10498. bool verify_callback_called = false;
  10499. bool ip_matched_via_cn = true;
  10500. SSLClient cli(HOST, PORT);
  10501. cli.enable_server_certificate_verification(true);
  10502. cli.set_ca_cert_path(CA_CERT_FILE);
  10503. cli.set_connection_timeout(5);
  10504. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10505. verify_callback_called = true;
  10506. if (!ctx.cert) return false;
  10507. // The IP appears only in the CN, so it must NOT be accepted.
  10508. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10509. return true; // Accept for the purpose of this test
  10510. });
  10511. cli.Get("/test");
  10512. ASSERT_TRUE(verify_callback_called)
  10513. << "Verify callback should have been called";
  10514. EXPECT_FALSE(ip_matched_via_cn)
  10515. << "An IP host must not be authenticated via the certificate CN";
  10516. }
  10517. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10518. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10519. using namespace httplib::tls;
  10520. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10521. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10522. ASSERT_TRUE(svr.is_valid());
  10523. svr.Get("/test", [](const Request &, Response &res) {
  10524. res.set_content("ok", "text/plain");
  10525. });
  10526. thread t([&]() { svr.listen(HOST, PORT); });
  10527. auto se = detail::scope_exit([&] {
  10528. svr.stop();
  10529. t.join();
  10530. });
  10531. svr.wait_until_ready();
  10532. bool verify_callback_called = false;
  10533. bool san_matched = false;
  10534. bool wrong_ipv6_matched = true;
  10535. bool cn_ipv6_matched = true;
  10536. SSLClient cli(HOST, PORT);
  10537. cli.enable_server_certificate_verification(true);
  10538. cli.set_ca_cert_path(CA_CERT_FILE);
  10539. cli.set_connection_timeout(5);
  10540. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10541. verify_callback_called = true;
  10542. if (!ctx.cert) return false;
  10543. // Matches the IPv6 iPAddress SAN.
  10544. san_matched = ctx.check_hostname("2001:db8::1");
  10545. // A different IPv6 address must not match.
  10546. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10547. // "::1" lives only in the CN, so it must not be accepted.
  10548. cn_ipv6_matched = ctx.check_hostname("::1");
  10549. return true; // Accept for the purpose of this test
  10550. });
  10551. cli.Get("/test");
  10552. ASSERT_TRUE(verify_callback_called)
  10553. << "Verify callback should have been called";
  10554. EXPECT_TRUE(san_matched)
  10555. << "verify_hostname should match an IPv6 iPAddress SAN";
  10556. EXPECT_FALSE(wrong_ipv6_matched)
  10557. << "verify_hostname should not match a non-matching IPv6 address";
  10558. EXPECT_FALSE(cn_ipv6_matched)
  10559. << "An IPv6 host must not be authenticated via the certificate CN";
  10560. }
  10561. #endif
  10562. // mbedTLS-specific callback constructor test
  10563. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10564. #ifdef CPPHTTPLIB_SSL_ENABLED
  10565. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10567. ASSERT_TRUE(svr.is_valid());
  10568. // Set up a handler to verify client certificate is present
  10569. bool client_cert_verified = false;
  10570. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10571. // Verify that client certificate was provided
  10572. client_cert_verified = true;
  10573. res.set_content("success", "text/plain");
  10574. });
  10575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10576. auto se = detail::scope_exit([&] {
  10577. svr.stop();
  10578. t.join();
  10579. ASSERT_FALSE(svr.is_running());
  10580. });
  10581. svr.wait_until_ready();
  10582. // Client with certificate
  10583. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10584. cli.enable_server_certificate_verification(false);
  10585. cli.set_connection_timeout(30);
  10586. auto res = cli.Get("/test");
  10587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10588. ASSERT_EQ(StatusCode::OK_200, res->status);
  10589. ASSERT_TRUE(client_cert_verified);
  10590. EXPECT_EQ("success", res->body);
  10591. }
  10592. #endif
  10593. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10594. // backends
  10595. #ifdef CPPHTTPLIB_SSL_ENABLED
  10596. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10597. using namespace httplib::tls;
  10598. // Test that when client CA cert file is provided,
  10599. // the server properly requests and validates client certificates
  10600. // Create a server with client authentication
  10601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10602. ASSERT_TRUE(svr.is_valid());
  10603. bool handler_called = false;
  10604. svr.Get("/test", [&](const Request &req, Response &res) {
  10605. handler_called = true;
  10606. // Verify that a client certificate was provided
  10607. auto cert = req.peer_cert();
  10608. ASSERT_TRUE(static_cast<bool>(cert));
  10609. // Get the issuer name
  10610. std::string issuer_str = cert.issuer_name();
  10611. ASSERT_FALSE(issuer_str.empty());
  10612. // The client certificate should be issued by our test CA
  10613. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10614. res.set_content("authenticated", "text/plain");
  10615. });
  10616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10617. auto se = detail::scope_exit([&] {
  10618. svr.stop();
  10619. t.join();
  10620. ASSERT_FALSE(svr.is_running());
  10621. });
  10622. svr.wait_until_ready();
  10623. // Connect with a client certificate issued by the CA
  10624. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10625. cli.enable_server_certificate_verification(false);
  10626. cli.set_connection_timeout(30);
  10627. auto res = cli.Get("/test");
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. ASSERT_EQ(StatusCode::OK_200, res->status);
  10630. ASSERT_TRUE(handler_called);
  10631. EXPECT_EQ("authenticated", res->body);
  10632. }
  10633. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10634. using namespace httplib::tls;
  10635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10636. ASSERT_TRUE(svr.is_valid());
  10637. svr.Get("/test", [](const Request &, Response &res) {
  10638. res.set_content("ok", "text/plain");
  10639. });
  10640. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10641. auto se = detail::scope_exit([&] {
  10642. svr.stop();
  10643. t.join();
  10644. });
  10645. svr.wait_until_ready();
  10646. SSLClient cli(HOST, PORT);
  10647. cli.enable_server_certificate_verification(false);
  10648. cli.set_connection_timeout(30);
  10649. bool cert_checked = false;
  10650. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10651. if (ctx.cert) {
  10652. auto sans = ctx.sans();
  10653. // Test certificate may or may not have SANs - just verify the API
  10654. // works If SANs exist, verify the types are valid
  10655. for (const auto &san : sans) {
  10656. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10657. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10658. san.type == SanType::OTHER);
  10659. EXPECT_FALSE(san.value.empty());
  10660. }
  10661. cert_checked = true;
  10662. }
  10663. return true;
  10664. });
  10665. auto res = cli.Get("/test");
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_TRUE(cert_checked);
  10668. }
  10669. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10670. using namespace httplib::tls;
  10671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10672. ASSERT_TRUE(svr.is_valid());
  10673. svr.Get("/test", [](const Request &, Response &res) {
  10674. res.set_content("ok", "text/plain");
  10675. });
  10676. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10677. auto se = detail::scope_exit([&] {
  10678. svr.stop();
  10679. t.join();
  10680. });
  10681. svr.wait_until_ready();
  10682. SSLClient cli(HOST, PORT);
  10683. cli.enable_server_certificate_verification(false);
  10684. cli.set_connection_timeout(30);
  10685. bool validity_checked = false;
  10686. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10687. if (ctx.cert) {
  10688. time_t not_before = 0, not_after = 0;
  10689. bool result = ctx.validity(not_before, not_after);
  10690. EXPECT_TRUE(result);
  10691. // Verify that not_before < now < not_after for a valid cert
  10692. time_t now = time(nullptr);
  10693. EXPECT_LT(not_before, now);
  10694. EXPECT_GT(not_after, now);
  10695. validity_checked = true;
  10696. }
  10697. return true;
  10698. });
  10699. auto res = cli.Get("/test");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_TRUE(validity_checked);
  10702. }
  10703. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10704. using namespace httplib::tls;
  10705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10706. ASSERT_TRUE(svr.is_valid());
  10707. svr.Get("/test", [](const Request &, Response &res) {
  10708. res.set_content("ok", "text/plain");
  10709. });
  10710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10711. auto se = detail::scope_exit([&] {
  10712. svr.stop();
  10713. t.join();
  10714. });
  10715. svr.wait_until_ready();
  10716. SSLClient cli(HOST, PORT);
  10717. cli.enable_server_certificate_verification(false);
  10718. cli.set_connection_timeout(30);
  10719. bool serial_checked = false;
  10720. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10721. if (ctx.cert) {
  10722. std::string serial = ctx.serial();
  10723. EXPECT_FALSE(serial.empty());
  10724. // Serial should be a hex string
  10725. for (char c : serial) {
  10726. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10727. (c >= 'a' && c <= 'f'));
  10728. }
  10729. serial_checked = true;
  10730. }
  10731. return true;
  10732. });
  10733. auto res = cli.Get("/test");
  10734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10735. EXPECT_TRUE(serial_checked);
  10736. }
  10737. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10738. // Test 1: Valid CA file - no error should be recorded
  10739. {
  10740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10741. CLIENT_CA_CERT_FILE);
  10742. ASSERT_TRUE(svr.is_valid());
  10743. // With valid setup, last_ssl_error should be 0
  10744. EXPECT_EQ(0, svr.ssl_last_error());
  10745. }
  10746. // Test 2: Invalid CA file content
  10747. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10748. {
  10749. // Create a temporary file with completely invalid content
  10750. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10751. {
  10752. std::ofstream ofs(temp_invalid_ca);
  10753. ofs << "This is not a certificate file at all\n";
  10754. ofs << "Just plain text content\n";
  10755. }
  10756. // Create server with invalid CA file
  10757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10758. // Clean up temporary file
  10759. std::remove(temp_invalid_ca);
  10760. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10761. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10762. // Note: SSL_CTX_load_verify_locations typically fails first,
  10763. // but our error handling code path is still exercised
  10764. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10765. }
  10766. }
  10767. TEST(VerifyCallbackTest, VerifyContextFields) {
  10768. using namespace httplib::tls;
  10769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10770. ASSERT_TRUE(svr.is_valid());
  10771. svr.Get("/test", [](const Request &, Response &res) {
  10772. res.set_content("ok", "text/plain");
  10773. });
  10774. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10775. auto se = detail::scope_exit([&] {
  10776. svr.stop();
  10777. t.join();
  10778. });
  10779. svr.wait_until_ready();
  10780. SSLClient cli(HOST, PORT);
  10781. cli.enable_server_certificate_verification(false);
  10782. cli.set_connection_timeout(30);
  10783. int callback_count = 0;
  10784. bool saw_leaf_cert = false;
  10785. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10786. if (ctx.cert) {
  10787. callback_count++;
  10788. // We should see at least one certificate (the leaf)
  10789. std::string cn = ctx.subject_cn();
  10790. if (!cn.empty()) { saw_leaf_cert = true; }
  10791. // Verify context fields are populated
  10792. EXPECT_NE(ctx.session, nullptr);
  10793. EXPECT_GE(ctx.depth, 0);
  10794. }
  10795. return true;
  10796. });
  10797. auto res = cli.Get("/test");
  10798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10799. EXPECT_GT(callback_count, 0);
  10800. EXPECT_TRUE(saw_leaf_cert);
  10801. }
  10802. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10803. using httplib::tls::TlsError;
  10804. // Test that verify_error_to_string returns empty for success
  10805. std::string success_str = TlsError::verify_error_to_string(0);
  10806. EXPECT_TRUE(success_str.empty());
  10807. // Test that verify_error_to_string returns non-empty for error codes
  10808. // Using a common error code (certificate expired)
  10809. std::string error_str =
  10810. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10811. EXPECT_FALSE(error_str.empty());
  10812. }
  10813. TEST(SessionVerifierTest, CertificateAccepted) {
  10814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10815. ASSERT_TRUE(svr.is_valid());
  10816. svr.Get("/test", [](const Request &, Response &res) {
  10817. res.set_content("ok", "text/plain");
  10818. });
  10819. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10820. auto se = detail::scope_exit([&] {
  10821. svr.stop();
  10822. t.join();
  10823. });
  10824. svr.wait_until_ready();
  10825. SSLClient cli(HOST, PORT);
  10826. cli.enable_server_certificate_verification(false);
  10827. cli.set_connection_timeout(30);
  10828. bool callback_called = false;
  10829. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10830. EXPECT_NE(session, nullptr);
  10831. callback_called = true;
  10832. return SSLVerifierResponse::CertificateAccepted;
  10833. });
  10834. auto res = cli.Get("/test");
  10835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10836. EXPECT_EQ(200, res->status);
  10837. EXPECT_TRUE(callback_called);
  10838. }
  10839. TEST(SessionVerifierTest, CertificateRejected) {
  10840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10841. ASSERT_TRUE(svr.is_valid());
  10842. svr.Get("/test", [](const Request &, Response &res) {
  10843. res.set_content("ok", "text/plain");
  10844. });
  10845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10846. auto se = detail::scope_exit([&] {
  10847. svr.stop();
  10848. t.join();
  10849. });
  10850. svr.wait_until_ready();
  10851. SSLClient cli(HOST, PORT);
  10852. cli.enable_server_certificate_verification(false);
  10853. cli.set_connection_timeout(30);
  10854. bool callback_called = false;
  10855. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10856. EXPECT_NE(session, nullptr);
  10857. callback_called = true;
  10858. return SSLVerifierResponse::CertificateRejected;
  10859. });
  10860. auto res = cli.Get("/test");
  10861. EXPECT_FALSE(res);
  10862. EXPECT_TRUE(callback_called);
  10863. }
  10864. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10866. ASSERT_TRUE(svr.is_valid());
  10867. svr.Get("/test", [](const Request &, Response &res) {
  10868. res.set_content("ok", "text/plain");
  10869. });
  10870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10871. auto se = detail::scope_exit([&] {
  10872. svr.stop();
  10873. t.join();
  10874. });
  10875. svr.wait_until_ready();
  10876. // NoDecisionMade with verification disabled should succeed (no default check)
  10877. SSLClient cli(HOST, PORT);
  10878. cli.enable_server_certificate_verification(false);
  10879. cli.set_connection_timeout(30);
  10880. bool callback_called = false;
  10881. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10882. EXPECT_NE(session, nullptr);
  10883. callback_called = true;
  10884. return SSLVerifierResponse::NoDecisionMade;
  10885. });
  10886. auto res = cli.Get("/test");
  10887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10888. EXPECT_EQ(200, res->status);
  10889. EXPECT_TRUE(callback_called);
  10890. }
  10891. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10893. ASSERT_TRUE(svr.is_valid());
  10894. svr.Get("/test", [](const Request &, Response &res) {
  10895. res.set_content("ok", "text/plain");
  10896. });
  10897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10898. auto se = detail::scope_exit([&] {
  10899. svr.stop();
  10900. t.join();
  10901. });
  10902. svr.wait_until_ready();
  10903. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10904. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10905. // so we only check that the request fails, not whether the callback was
  10906. // called.
  10907. SSLClient cli(HOST, PORT);
  10908. cli.enable_server_certificate_verification(true);
  10909. cli.set_connection_timeout(30);
  10910. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10911. EXPECT_NE(session, nullptr);
  10912. return SSLVerifierResponse::NoDecisionMade;
  10913. });
  10914. auto res = cli.Get("/test");
  10915. EXPECT_FALSE(res);
  10916. }
  10917. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10918. // Test SSL server using PemMemory constructor with client CA certificates
  10919. // Read PEM files
  10920. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10921. read_file(SERVER_CERT_FILE, server_cert_pem);
  10922. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10923. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10924. // Create SSLServer with PemMemory constructor including client CA
  10925. SSLServer::PemMemory server_pem = {
  10926. server_cert_pem.c_str(),
  10927. server_cert_pem.size(),
  10928. server_key_pem.c_str(),
  10929. server_key_pem.size(),
  10930. client_ca_pem.c_str(),
  10931. client_ca_pem.size(),
  10932. nullptr // no password for server key
  10933. };
  10934. SSLServer svr(server_pem);
  10935. ASSERT_TRUE(svr.is_valid());
  10936. // No SSL error should be recorded for valid setup
  10937. EXPECT_EQ(0, svr.ssl_last_error());
  10938. // Set up server endpoints
  10939. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10940. res.set_content("ok", "text/plain");
  10941. });
  10942. // Start server in a thread
  10943. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10944. svr.wait_until_ready();
  10945. // Connect with client certificate (using constructor with paths)
  10946. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10947. cli.enable_server_certificate_verification(false);
  10948. auto res = cli.Get("/test-pem-ca");
  10949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10950. EXPECT_EQ(200, res->status);
  10951. EXPECT_EQ("ok", res->body);
  10952. svr.stop();
  10953. server_thread.join();
  10954. }
  10955. #endif
  10956. #ifdef _WIN32
  10957. TEST(CleanupTest, WSACleanup) {
  10958. int ret = WSACleanup();
  10959. ASSERT_EQ(0, ret);
  10960. }
  10961. #endif
  10962. #ifndef CPPHTTPLIB_SSL_ENABLED
  10963. TEST(NoSSLSupport, SimpleInterface) {
  10964. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10965. }
  10966. #endif
  10967. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10968. TEST(InvalidScheme, SimpleInterface) {
  10969. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10970. }
  10971. #endif
  10972. TEST(NoScheme, SimpleInterface) {
  10973. Client cli("yahoo.com:80");
  10974. ASSERT_TRUE(cli.is_valid());
  10975. }
  10976. TEST(SendAPI, SimpleInterface_Online) {
  10977. Client cli("http://yahoo.com");
  10978. Request req;
  10979. req.method = "GET";
  10980. req.path = "/";
  10981. auto res = cli.send(req);
  10982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10983. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10984. }
  10985. TEST(SendAPI, WithParamsInRequest) {
  10986. Server svr;
  10987. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10988. EXPECT_TRUE(req.has_param("test"));
  10989. EXPECT_EQ("test_value", req.get_param_value("test"));
  10990. });
  10991. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. t.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. });
  10997. svr.wait_until_ready();
  10998. Client cli(HOST, PORT);
  10999. {
  11000. Request req;
  11001. req.method = "GET";
  11002. req.path = "/";
  11003. req.params.emplace("test", "test_value");
  11004. auto res = cli.send(req);
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. }
  11007. {
  11008. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11010. }
  11011. }
  11012. TEST(ClientImplMethods, GetSocketTest) {
  11013. httplib::Server svr;
  11014. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11015. res.status = StatusCode::OK_200;
  11016. });
  11017. auto port = svr.bind_to_any_port("127.0.0.1");
  11018. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11019. auto se = detail::scope_exit([&] {
  11020. svr.stop();
  11021. thread.join();
  11022. ASSERT_FALSE(svr.is_running());
  11023. });
  11024. svr.wait_until_ready();
  11025. {
  11026. httplib::Client cli("127.0.0.1", port);
  11027. cli.set_keep_alive(true);
  11028. // Use the behavior of cpp-httplib of opening the connection
  11029. // only when the first request happens. If that changes,
  11030. // this test would be obsolete.
  11031. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11032. // This also implicitly tests the server. But other tests would fail much
  11033. // earlier than this one to be considered.
  11034. auto res = cli.Get("/");
  11035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11036. EXPECT_EQ(StatusCode::OK_200, res->status);
  11037. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11038. }
  11039. }
  11040. #ifdef CPPHTTPLIB_SSL_ENABLED
  11041. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11042. Client cli("http://yahoo.com");
  11043. auto res = cli.Get("/");
  11044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11045. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11046. cli.set_follow_location(true);
  11047. res = cli.Get("/");
  11048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11049. EXPECT_EQ(StatusCode::OK_200, res->status);
  11050. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11051. }
  11052. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11053. Client cli("https://yahoo.com");
  11054. auto res = cli.Get("/");
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11057. cli.set_follow_location(true);
  11058. res = cli.Get("/");
  11059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11060. EXPECT_EQ(StatusCode::OK_200, res->status);
  11061. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11062. }
  11063. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11064. Client cli("https://yahoo.com");
  11065. auto res = cli.Get("/");
  11066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11067. ASSERT_FALSE(!res);
  11068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11069. ASSERT_FALSE(res == nullptr);
  11070. ASSERT_TRUE(res != nullptr);
  11071. EXPECT_EQ(Error::Success, res.error());
  11072. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11073. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11074. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11075. cli.set_follow_location(true);
  11076. res = cli.Get("/");
  11077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11078. EXPECT_EQ(Error::Success, res.error());
  11079. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11080. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11081. EXPECT_EQ(StatusCode::OK_200, res->status);
  11082. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11083. }
  11084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11085. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11086. Client cli("https://cdnjs.cloudflare.com");
  11087. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11088. Headers{{"Accept-Encoding", "br"}});
  11089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11090. EXPECT_EQ(StatusCode::OK_200, res->status);
  11091. EXPECT_EQ(287630U, res->body.size());
  11092. EXPECT_EQ("application/javascript; charset=utf-8",
  11093. res->get_header_value("Content-Type"));
  11094. }
  11095. #endif
  11096. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11097. #undef REDIR_HOST // Silence compiler warning
  11098. #define REDIR_HOST "https://httpbingo.org"
  11099. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11100. Client cli(REDIR_HOST);
  11101. cli.set_follow_location(true);
  11102. auto res =
  11103. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11105. EXPECT_EQ(StatusCode::OK_200, res->status);
  11106. }
  11107. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11108. Client cli(REDIR_HOST);
  11109. cli.set_follow_location(true);
  11110. Params params;
  11111. params.emplace("url", "http://example.com");
  11112. params.emplace("status_code", "302");
  11113. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11115. EXPECT_EQ(StatusCode::OK_200, res->status);
  11116. }
  11117. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11118. Client cli(REDIR_HOST);
  11119. cli.set_follow_location(true);
  11120. Params params;
  11121. params.emplace("url", "http://example.com");
  11122. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11124. EXPECT_EQ(StatusCode::OK_200, res->status);
  11125. }
  11126. TEST(HttpToHttpsRedirectTest, CertFile) {
  11127. auto ssl_port = PORT + 1;
  11128. Server svr;
  11129. ASSERT_TRUE(svr.is_valid());
  11130. svr.Get("/index", [&](const Request &, Response &res) {
  11131. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11132. "/index");
  11133. svr.stop();
  11134. });
  11135. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11136. ASSERT_TRUE(ssl_svr.is_valid());
  11137. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11138. res.set_content("test", "text/plain");
  11139. ssl_svr.stop();
  11140. });
  11141. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11142. thread t2 =
  11143. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11144. auto se = detail::scope_exit([&] {
  11145. t2.join();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. ssl_svr.wait_until_ready();
  11151. Client cli("127.0.0.1", PORT);
  11152. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11153. cli.enable_server_certificate_verification(true);
  11154. cli.set_follow_location(true);
  11155. cli.set_connection_timeout(30);
  11156. auto res = cli.Get("/index");
  11157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11158. ASSERT_EQ(StatusCode::OK_200, res->status);
  11159. }
  11160. TEST(SSLClientRedirectTest, CertFile) {
  11161. auto ssl_port = PORT + 1;
  11162. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11163. ASSERT_TRUE(ssl_svr1.is_valid());
  11164. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11165. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11166. "/index");
  11167. ssl_svr1.stop();
  11168. });
  11169. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11170. ASSERT_TRUE(ssl_svr2.is_valid());
  11171. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11172. res.set_content("test", "text/plain");
  11173. ssl_svr2.stop();
  11174. });
  11175. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11176. thread t2 =
  11177. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11178. auto se = detail::scope_exit([&] {
  11179. t2.join();
  11180. t.join();
  11181. ASSERT_FALSE(ssl_svr1.is_running());
  11182. });
  11183. ssl_svr1.wait_until_ready();
  11184. ssl_svr2.wait_until_ready();
  11185. SSLClient cli("127.0.0.1", PORT);
  11186. std::string cert;
  11187. read_file(SERVER_CERT2_FILE, cert);
  11188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11189. cli.enable_server_certificate_verification(true);
  11190. cli.set_follow_location(true);
  11191. cli.set_connection_timeout(30);
  11192. auto res = cli.Get("/index");
  11193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11194. ASSERT_EQ(StatusCode::OK_200, res->status);
  11195. }
  11196. #endif
  11197. #ifdef CPPHTTPLIB_SSL_ENABLED
  11198. // Test that set_ca_cert_store() skips system certs (consistent with
  11199. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11200. // should be trusted - system certs should NOT be loaded.
  11201. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11202. // Load a specific cert that is NOT a system CA cert
  11203. std::string cert;
  11204. read_file(SERVER_CERT2_FILE, cert);
  11205. SSLClient cli("google.com");
  11206. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11207. cli.enable_server_certificate_verification(true);
  11208. // This should FAIL because:
  11209. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11210. // 2. System certs should NOT be loaded when custom store is set
  11211. // If system certs WERE loaded, this would succeed
  11212. auto res = cli.Get("/");
  11213. ASSERT_FALSE(res);
  11214. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11215. }
  11216. // Same as above, but through the native store handle path. Regression test:
  11217. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11218. // merged system certs into the user-provided store.
  11219. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11220. std::string cert;
  11221. read_file(SERVER_CERT2_FILE, cert);
  11222. SSLClient cli("google.com");
  11223. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11224. cli.enable_server_certificate_verification(true);
  11225. auto res = cli.Get("/");
  11226. ASSERT_FALSE(res);
  11227. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11228. }
  11229. // A custom store set via the native handle must still verify a server whose
  11230. // cert it does contain.
  11231. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11232. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11233. ASSERT_TRUE(svr.is_valid());
  11234. svr.Get("/test", [&](const Request &, Response &res) {
  11235. res.set_content("test", "text/plain");
  11236. });
  11237. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11238. auto se = detail::scope_exit([&] {
  11239. svr.stop();
  11240. t.join();
  11241. ASSERT_FALSE(svr.is_running());
  11242. });
  11243. svr.wait_until_ready();
  11244. SSLClient cli("127.0.0.1", PORT);
  11245. std::string cert;
  11246. read_file(SERVER_CERT2_FILE, cert);
  11247. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11248. cli.enable_server_certificate_verification(true);
  11249. cli.set_connection_timeout(30);
  11250. auto res = cli.Get("/test");
  11251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11252. ASSERT_EQ(StatusCode::OK_200, res->status);
  11253. }
  11254. // CA certs loaded through the universal Client must be transferred to the
  11255. // client created internally for following an HTTPS redirect. Regression test:
  11256. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11257. // the CA data for redirect transfer.
  11258. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11259. auto ssl_port = PORT + 1;
  11260. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11261. ASSERT_TRUE(ssl_svr1.is_valid());
  11262. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11263. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11264. "/index");
  11265. });
  11266. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11267. ASSERT_TRUE(ssl_svr2.is_valid());
  11268. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11269. res.set_content("test", "text/plain");
  11270. });
  11271. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11272. thread t2 =
  11273. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11274. auto se = detail::scope_exit([&] {
  11275. ssl_svr2.stop();
  11276. ssl_svr1.stop();
  11277. t2.join();
  11278. t.join();
  11279. ASSERT_FALSE(ssl_svr1.is_running());
  11280. });
  11281. ssl_svr1.wait_until_ready();
  11282. ssl_svr2.wait_until_ready();
  11283. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11284. std::string cert;
  11285. read_file(SERVER_CERT2_FILE, cert);
  11286. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11287. cli.enable_server_certificate_verification(true);
  11288. cli.set_follow_location(true);
  11289. cli.set_connection_timeout(30);
  11290. auto res = cli.Get("/index");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. ASSERT_EQ(StatusCode::OK_200, res->status);
  11293. }
  11294. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11295. // so a host signed by a system CA verifies even though a custom CA is set
  11296. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11297. std::string cert;
  11298. read_file(SERVER_CERT2_FILE, cert);
  11299. SSLClient cli("google.com");
  11300. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11301. cli.enable_system_ca(true);
  11302. cli.enable_server_certificate_verification(true);
  11303. auto res = cli.Get("/");
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11306. }
  11307. // The custom CA remains effective when combined with the system CA
  11308. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11309. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11310. ASSERT_TRUE(svr.is_valid());
  11311. svr.Get("/test", [&](const Request &, Response &res) {
  11312. res.set_content("test", "text/plain");
  11313. });
  11314. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11315. auto se = detail::scope_exit([&] {
  11316. svr.stop();
  11317. t.join();
  11318. ASSERT_FALSE(svr.is_running());
  11319. });
  11320. svr.wait_until_ready();
  11321. SSLClient cli("127.0.0.1", PORT);
  11322. std::string cert;
  11323. read_file(SERVER_CERT2_FILE, cert);
  11324. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11325. cli.enable_system_ca(true);
  11326. cli.enable_server_certificate_verification(true);
  11327. cli.set_connection_timeout(30);
  11328. auto res = cli.Get("/test");
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. ASSERT_EQ(StatusCode::OK_200, res->status);
  11331. }
  11332. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11333. // skip chain verification entirely (only the certificate identity was
  11334. // checked), so a server presenting an untrusted certificate with a matching
  11335. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11336. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11337. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11338. ASSERT_TRUE(svr.is_valid());
  11339. svr.Get("/test", [&](const Request &, Response &res) {
  11340. res.set_content("test", "text/plain");
  11341. });
  11342. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11343. auto se = detail::scope_exit([&] {
  11344. svr.stop();
  11345. t.join();
  11346. ASSERT_FALSE(svr.is_running());
  11347. });
  11348. svr.wait_until_ready();
  11349. SSLClient cli("127.0.0.1", PORT);
  11350. std::string cert;
  11351. // A trusted CA that did not sign the server certificate. The server cert
  11352. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11353. // this connection.
  11354. read_file(CLIENT_CA_CERT_FILE, cert);
  11355. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11356. cli.enable_server_certificate_verification(true);
  11357. cli.set_connection_timeout(30);
  11358. auto res = cli.Get("/test");
  11359. ASSERT_FALSE(res);
  11360. }
  11361. // enable_system_ca(false) prevents system CA loading entirely
  11362. TEST(SSLClientTest, DisableSystemCa_Online) {
  11363. SSLClient cli("google.com");
  11364. cli.enable_system_ca(false);
  11365. cli.enable_server_certificate_verification(true);
  11366. auto res = cli.Get("/");
  11367. ASSERT_FALSE(res);
  11368. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11369. // itself when the CA chain is empty
  11370. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11371. res.error() == Error::SSLConnection);
  11372. }
  11373. // The universal Client forwards enable_system_ca()
  11374. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11375. std::string cert;
  11376. read_file(SERVER_CERT2_FILE, cert);
  11377. Client cli("https://google.com");
  11378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11379. cli.enable_system_ca(true);
  11380. cli.enable_server_certificate_verification(true);
  11381. auto res = cli.Get("/");
  11382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11384. }
  11385. // The system CA policy must carry over to the client created internally for
  11386. // following a cross-host HTTPS redirect
  11387. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11388. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11389. ASSERT_TRUE(svr.is_valid());
  11390. svr.Get("/index", [&](const Request &, Response &res) {
  11391. res.set_redirect("https://www.google.com/");
  11392. });
  11393. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11394. auto se = detail::scope_exit([&] {
  11395. svr.stop();
  11396. t.join();
  11397. ASSERT_FALSE(svr.is_running());
  11398. });
  11399. svr.wait_until_ready();
  11400. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11401. std::string cert;
  11402. read_file(SERVER_CERT2_FILE, cert);
  11403. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11404. cli.enable_system_ca(true);
  11405. cli.enable_server_certificate_verification(true);
  11406. cli.set_follow_location(true);
  11407. cli.set_connection_timeout(30);
  11408. // Receiving any response proves the redirect client completed the TLS
  11409. // handshake with a system-CA-signed host
  11410. auto res = cli.Get("/index");
  11411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11412. }
  11413. TEST(MultipartFormDataTest, LargeData) {
  11414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11415. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11416. const ContentReader &content_reader) {
  11417. if (req.is_multipart_form_data()) {
  11418. std::vector<FormData> items;
  11419. content_reader(
  11420. [&](const FormData &file) {
  11421. items.push_back(file);
  11422. return true;
  11423. },
  11424. [&](const char *data, size_t data_length) {
  11425. items.back().content.append(data, data_length);
  11426. return true;
  11427. });
  11428. EXPECT_TRUE(std::string(items[0].name) == "document");
  11429. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11430. EXPECT_TRUE(items[0].filename == "2MB_data");
  11431. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11432. EXPECT_TRUE(items[1].name == "hello");
  11433. EXPECT_TRUE(items[1].content == "world");
  11434. EXPECT_TRUE(items[1].filename == "");
  11435. EXPECT_TRUE(items[1].content_type == "");
  11436. } else {
  11437. std::string body;
  11438. content_reader([&](const char *data, size_t data_length) {
  11439. body.append(data, data_length);
  11440. return true;
  11441. });
  11442. }
  11443. });
  11444. auto port = svr.bind_to_any_port(HOST);
  11445. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11446. auto se = detail::scope_exit([&] {
  11447. svr.stop();
  11448. t.join();
  11449. ASSERT_FALSE(svr.is_running());
  11450. });
  11451. svr.wait_until_ready();
  11452. {
  11453. std::string data(1024 * 1024 * 2, '.');
  11454. std::stringstream buffer;
  11455. buffer << data;
  11456. SSLClient cli(HOST, port);
  11457. cli.enable_server_certificate_verification(false);
  11458. UploadFormDataItems items{
  11459. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11460. {"hello", "world", "", ""},
  11461. };
  11462. auto res = cli.Post("/post", items);
  11463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11464. ASSERT_EQ(StatusCode::OK_200, res->status);
  11465. }
  11466. }
  11467. TEST(MultipartFormDataTest, DataProviderItems) {
  11468. std::random_device seed_gen;
  11469. std::mt19937 random(seed_gen());
  11470. std::string rand1;
  11471. rand1.resize(1000);
  11472. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11473. std::string rand2;
  11474. rand2.resize(3000);
  11475. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11477. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11478. const ContentReader &content_reader) {
  11479. ASSERT_FALSE(req.is_multipart_form_data());
  11480. std::string body;
  11481. content_reader([&](const char *data, size_t data_length) {
  11482. body.append(data, data_length);
  11483. return true;
  11484. });
  11485. EXPECT_EQ(body, "");
  11486. });
  11487. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11488. const ContentReader &content_reader) {
  11489. ASSERT_TRUE(req.is_multipart_form_data());
  11490. std::vector<FormData> items;
  11491. content_reader(
  11492. [&](const FormData &file) {
  11493. items.push_back(file);
  11494. return true;
  11495. },
  11496. [&](const char *data, size_t data_length) {
  11497. items.back().content.append(data, data_length);
  11498. return true;
  11499. });
  11500. ASSERT_TRUE(items.size() == 2);
  11501. EXPECT_EQ(std::string(items[0].name), "name1");
  11502. EXPECT_EQ(items[0].content, "Testing123");
  11503. EXPECT_EQ(items[0].filename, "filename1");
  11504. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11505. EXPECT_EQ(items[1].name, "name2");
  11506. EXPECT_EQ(items[1].content, "Testing456");
  11507. EXPECT_EQ(items[1].filename, "");
  11508. EXPECT_EQ(items[1].content_type, "");
  11509. });
  11510. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11511. const ContentReader &content_reader) {
  11512. ASSERT_TRUE(req.is_multipart_form_data());
  11513. std::vector<FormData> items;
  11514. content_reader(
  11515. [&](const FormData &file) {
  11516. items.push_back(file);
  11517. return true;
  11518. },
  11519. [&](const char *data, size_t data_length) {
  11520. items.back().content.append(data, data_length);
  11521. return true;
  11522. });
  11523. ASSERT_TRUE(items.size() == 2);
  11524. EXPECT_EQ(items[0].name, "name3");
  11525. EXPECT_EQ(items[0].content, rand1);
  11526. EXPECT_EQ(items[0].filename, "filename3");
  11527. EXPECT_EQ(items[0].content_type, "");
  11528. EXPECT_EQ(items[1].name, "name4");
  11529. EXPECT_EQ(items[1].content, rand2);
  11530. EXPECT_EQ(items[1].filename, "filename4");
  11531. EXPECT_EQ(items[1].content_type, "");
  11532. });
  11533. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11534. const ContentReader &content_reader) {
  11535. ASSERT_TRUE(req.is_multipart_form_data());
  11536. std::vector<FormData> items;
  11537. content_reader(
  11538. [&](const FormData &file) {
  11539. items.push_back(file);
  11540. return true;
  11541. },
  11542. [&](const char *data, size_t data_length) {
  11543. items.back().content.append(data, data_length);
  11544. return true;
  11545. });
  11546. ASSERT_TRUE(items.size() == 4);
  11547. EXPECT_EQ(std::string(items[0].name), "name1");
  11548. EXPECT_EQ(items[0].content, "Testing123");
  11549. EXPECT_EQ(items[0].filename, "filename1");
  11550. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11551. EXPECT_EQ(items[1].name, "name2");
  11552. EXPECT_EQ(items[1].content, "Testing456");
  11553. EXPECT_EQ(items[1].filename, "");
  11554. EXPECT_EQ(items[1].content_type, "");
  11555. EXPECT_EQ(items[2].name, "name3");
  11556. EXPECT_EQ(items[2].content, rand1);
  11557. EXPECT_EQ(items[2].filename, "filename3");
  11558. EXPECT_EQ(items[2].content_type, "");
  11559. EXPECT_EQ(items[3].name, "name4");
  11560. EXPECT_EQ(items[3].content, rand2);
  11561. EXPECT_EQ(items[3].filename, "filename4");
  11562. EXPECT_EQ(items[3].content_type, "");
  11563. });
  11564. auto port = svr.bind_to_any_port("localhost");
  11565. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11566. auto se = detail::scope_exit([&] {
  11567. svr.stop();
  11568. t.join();
  11569. ASSERT_FALSE(svr.is_running());
  11570. });
  11571. svr.wait_until_ready();
  11572. {
  11573. SSLClient cli("localhost", port);
  11574. cli.enable_server_certificate_verification(false);
  11575. UploadFormDataItems items{
  11576. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11577. {"name2", "Testing456", "", ""}, // not a file
  11578. };
  11579. {
  11580. auto res = cli.Post("/post-none", {}, {}, {});
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. ASSERT_EQ(StatusCode::OK_200, res->status);
  11583. }
  11584. FormDataProviderItems providers;
  11585. {
  11586. auto res =
  11587. cli.Post("/post-items", {}, items, providers); // empty providers
  11588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11589. ASSERT_EQ(StatusCode::OK_200, res->status);
  11590. }
  11591. providers.push_back({"name3",
  11592. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11593. // test the offset is given correctly at each step
  11594. if (!offset)
  11595. sink.os.write(rand1.data(), 30);
  11596. else if (offset == 30)
  11597. sink.os.write(rand1.data() + 30, 300);
  11598. else if (offset == 330)
  11599. sink.os.write(rand1.data() + 330, 670);
  11600. else if (offset == rand1.size())
  11601. sink.done();
  11602. return true;
  11603. },
  11604. "filename3",
  11605. {}});
  11606. providers.push_back({"name4",
  11607. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11608. // test the offset is given correctly at each step
  11609. if (!offset)
  11610. sink.os.write(rand2.data(), 2000);
  11611. else if (offset == 2000)
  11612. sink.os.write(rand2.data() + 2000, 1);
  11613. else if (offset == 2001)
  11614. sink.os.write(rand2.data() + 2001, 999);
  11615. else if (offset == rand2.size())
  11616. sink.done();
  11617. return true;
  11618. },
  11619. "filename4",
  11620. {}});
  11621. {
  11622. auto res = cli.Post("/post-providers", {}, {}, providers);
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. ASSERT_EQ(StatusCode::OK_200, res->status);
  11625. }
  11626. {
  11627. auto res = cli.Post("/post-both", {}, items, providers);
  11628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11629. ASSERT_EQ(StatusCode::OK_200, res->status);
  11630. }
  11631. }
  11632. }
  11633. TEST(MultipartFormDataTest, BadHeader) {
  11634. Server svr;
  11635. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11636. res.set_content("ok", "text/plain");
  11637. });
  11638. thread t = thread([&] { svr.listen(HOST, PORT); });
  11639. auto se = detail::scope_exit([&] {
  11640. svr.stop();
  11641. t.join();
  11642. ASSERT_FALSE(svr.is_running());
  11643. });
  11644. svr.wait_until_ready();
  11645. const std::string body =
  11646. "This is the preamble. It is to be ignored, though it\r\n"
  11647. "is a handy place for composition agents to include an\r\n"
  11648. "explanatory note to non-MIME conformant readers.\r\n"
  11649. "\r\n"
  11650. "\r\n"
  11651. "--simple boundary\r\n"
  11652. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11653. ": BAD...\r\n"
  11654. "\r\n"
  11655. "value1\r\n"
  11656. "--simple boundary\r\n"
  11657. "Content-Disposition: form-data; name=\"field2\"; "
  11658. "filename=\"example.txt\"\r\n"
  11659. "\r\n"
  11660. "value2\r\n"
  11661. "--simple boundary--\r\n"
  11662. "This is the epilogue. It is also to be ignored.\r\n";
  11663. std::string content_type =
  11664. R"(multipart/form-data; boundary="simple boundary")";
  11665. Client cli(HOST, PORT);
  11666. auto res = cli.Post("/post", body, content_type.c_str());
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11669. }
  11670. TEST(MultipartFormDataTest, WithPreamble) {
  11671. Server svr;
  11672. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11673. res.set_content("ok", "text/plain");
  11674. });
  11675. thread t = thread([&] { svr.listen(HOST, PORT); });
  11676. auto se = detail::scope_exit([&] {
  11677. svr.stop();
  11678. t.join();
  11679. ASSERT_FALSE(svr.is_running());
  11680. });
  11681. svr.wait_until_ready();
  11682. const std::string body =
  11683. "This is the preamble. It is to be ignored, though it\r\n"
  11684. "is a handy place for composition agents to include an\r\n"
  11685. "explanatory note to non-MIME conformant readers.\r\n"
  11686. "\r\n"
  11687. "\r\n"
  11688. "--simple boundary\r\n"
  11689. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11690. "\r\n"
  11691. "value1\r\n"
  11692. "--simple boundary\r\n"
  11693. "Content-Disposition: form-data; name=\"field2\"; "
  11694. "filename=\"example.txt\"\r\n"
  11695. "\r\n"
  11696. "value2\r\n"
  11697. "--simple boundary--\r\n"
  11698. "This is the epilogue. It is also to be ignored.\r\n";
  11699. std::string content_type =
  11700. R"(multipart/form-data; boundary="simple boundary")";
  11701. Client cli(HOST, PORT);
  11702. auto res = cli.Post("/post", body, content_type.c_str());
  11703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11704. EXPECT_EQ(StatusCode::OK_200, res->status);
  11705. }
  11706. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11708. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11709. const ContentReader &content_reader) {
  11710. if (req.is_multipart_form_data()) {
  11711. std::vector<FormData> items;
  11712. content_reader(
  11713. [&](const FormData &file) {
  11714. items.push_back(file);
  11715. return true;
  11716. },
  11717. [&](const char *data, size_t data_length) {
  11718. items.back().content.append(data, data_length);
  11719. return true;
  11720. });
  11721. EXPECT_TRUE(std::string(items[0].name) == "document");
  11722. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11723. EXPECT_TRUE(items[0].filename == "2MB_data");
  11724. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11725. EXPECT_TRUE(items[1].name == "hello");
  11726. EXPECT_TRUE(items[1].content == "world");
  11727. EXPECT_TRUE(items[1].filename == "");
  11728. EXPECT_TRUE(items[1].content_type == "");
  11729. } else {
  11730. std::string body;
  11731. content_reader([&](const char *data, size_t data_length) {
  11732. body.append(data, data_length);
  11733. return true;
  11734. });
  11735. }
  11736. });
  11737. auto port = svr.bind_to_any_port("localhost");
  11738. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11739. auto se = detail::scope_exit([&] {
  11740. svr.stop();
  11741. t.join();
  11742. ASSERT_FALSE(svr.is_running());
  11743. });
  11744. svr.wait_until_ready();
  11745. {
  11746. std::string data(1024 * 1024 * 2, '.');
  11747. std::stringstream buffer;
  11748. buffer << data;
  11749. SSLClient cli("localhost", port);
  11750. cli.enable_server_certificate_verification(false);
  11751. UploadFormDataItems items{
  11752. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11753. {"hello", "world", "", ""},
  11754. };
  11755. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11757. ASSERT_EQ(StatusCode::OK_200, res->status);
  11758. }
  11759. }
  11760. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11761. std::string data(1024 * 1024 * 2, '&');
  11762. std::stringstream buffer;
  11763. buffer << data;
  11764. Client cli("https://localhost:8080");
  11765. UploadFormDataItems items{
  11766. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11767. {"hello", "world", "", ""},
  11768. };
  11769. for (const char &c : " \t\r\n") {
  11770. auto res =
  11771. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11772. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11773. ASSERT_FALSE(res);
  11774. }
  11775. }
  11776. TEST(MultipartFormDataTest, PutFormData) {
  11777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11778. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11779. const ContentReader &content_reader) {
  11780. if (req.is_multipart_form_data()) {
  11781. std::vector<FormData> items;
  11782. content_reader(
  11783. [&](const FormData &file) {
  11784. items.push_back(file);
  11785. return true;
  11786. },
  11787. [&](const char *data, size_t data_length) {
  11788. items.back().content.append(data, data_length);
  11789. return true;
  11790. });
  11791. EXPECT_TRUE(std::string(items[0].name) == "document");
  11792. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11793. EXPECT_TRUE(items[0].filename == "2MB_data");
  11794. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11795. EXPECT_TRUE(items[1].name == "hello");
  11796. EXPECT_TRUE(items[1].content == "world");
  11797. EXPECT_TRUE(items[1].filename == "");
  11798. EXPECT_TRUE(items[1].content_type == "");
  11799. } else {
  11800. std::string body;
  11801. content_reader([&](const char *data, size_t data_length) {
  11802. body.append(data, data_length);
  11803. return true;
  11804. });
  11805. }
  11806. });
  11807. auto port = svr.bind_to_any_port("localhost");
  11808. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. t.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. {
  11816. std::string data(1024 * 1024 * 2, '&');
  11817. std::stringstream buffer;
  11818. buffer << data;
  11819. SSLClient cli("localhost", port);
  11820. cli.enable_server_certificate_verification(false);
  11821. UploadFormDataItems items{
  11822. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11823. {"hello", "world", "", ""},
  11824. };
  11825. auto res = cli.Put("/put", items);
  11826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11827. ASSERT_EQ(StatusCode::OK_200, res->status);
  11828. }
  11829. }
  11830. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11832. svr.Put("/put_customboundary",
  11833. [&](const Request &req, const Response & /*res*/,
  11834. const ContentReader &content_reader) {
  11835. if (req.is_multipart_form_data()) {
  11836. std::vector<FormData> items;
  11837. content_reader(
  11838. [&](const FormData &file) {
  11839. items.push_back(file);
  11840. return true;
  11841. },
  11842. [&](const char *data, size_t data_length) {
  11843. items.back().content.append(data, data_length);
  11844. return true;
  11845. });
  11846. EXPECT_TRUE(std::string(items[0].name) == "document");
  11847. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11848. EXPECT_TRUE(items[0].filename == "2MB_data");
  11849. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11850. EXPECT_TRUE(items[1].name == "hello");
  11851. EXPECT_TRUE(items[1].content == "world");
  11852. EXPECT_TRUE(items[1].filename == "");
  11853. EXPECT_TRUE(items[1].content_type == "");
  11854. } else {
  11855. std::string body;
  11856. content_reader([&](const char *data, size_t data_length) {
  11857. body.append(data, data_length);
  11858. return true;
  11859. });
  11860. }
  11861. });
  11862. auto port = svr.bind_to_any_port("localhost");
  11863. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11864. auto se = detail::scope_exit([&] {
  11865. svr.stop();
  11866. t.join();
  11867. ASSERT_FALSE(svr.is_running());
  11868. });
  11869. svr.wait_until_ready();
  11870. {
  11871. std::string data(1024 * 1024 * 2, '&');
  11872. std::stringstream buffer;
  11873. buffer << data;
  11874. SSLClient cli("localhost", port);
  11875. cli.enable_server_certificate_verification(false);
  11876. UploadFormDataItems items{
  11877. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11878. {"hello", "world", "", ""},
  11879. };
  11880. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11882. ASSERT_EQ(StatusCode::OK_200, res->status);
  11883. }
  11884. }
  11885. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11886. std::string data(1024 * 1024 * 2, '&');
  11887. std::stringstream buffer;
  11888. buffer << data;
  11889. Client cli("https://localhost:8080");
  11890. cli.enable_server_certificate_verification(false);
  11891. UploadFormDataItems items{
  11892. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11893. {"hello", "world", "", ""},
  11894. };
  11895. for (const char &c : " \t\r\n") {
  11896. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11897. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11898. ASSERT_FALSE(res);
  11899. }
  11900. }
  11901. TEST(MultipartFormDataTest, AlternateFilename) {
  11902. auto handled = false;
  11903. Server svr;
  11904. svr.Post("/test", [&](const Request &req, Response &res) {
  11905. ASSERT_EQ(2u, req.form.files.size());
  11906. ASSERT_EQ(1u, req.form.fields.size());
  11907. // Test files
  11908. const auto &file1 = req.form.get_file("file1");
  11909. ASSERT_EQ("file1", file1.name);
  11910. ASSERT_EQ("A.txt", file1.filename);
  11911. ASSERT_EQ("text/plain", file1.content_type);
  11912. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11913. const auto &file2 = req.form.get_file("file2");
  11914. ASSERT_EQ("file2", file2.name);
  11915. ASSERT_EQ("a.html", file2.filename);
  11916. ASSERT_EQ("text/html", file2.content_type);
  11917. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11918. file2.content);
  11919. // Test text field
  11920. const auto &text = req.form.get_field("text");
  11921. ASSERT_EQ("text default", text);
  11922. res.set_content("ok", "text/plain");
  11923. handled = true;
  11924. });
  11925. thread t = thread([&] { svr.listen(HOST, PORT); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. t.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. ASSERT_TRUE(handled);
  11931. });
  11932. svr.wait_until_ready();
  11933. auto req = "POST /test HTTP/1.1\r\n"
  11934. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11935. "Content-Length: 399\r\n"
  11936. "\r\n"
  11937. "----------\r\n"
  11938. "Content-Disposition: form-data; name=\"text\"\r\n"
  11939. "\r\n"
  11940. "text default\r\n"
  11941. "----------\r\n"
  11942. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11943. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11944. "Content-Type: text/plain\r\n"
  11945. "\r\n"
  11946. "Content of a.txt.\r\n"
  11947. "\r\n"
  11948. "----------\r\n"
  11949. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11950. "\"a.html\"\r\n"
  11951. "Content-Type: text/html\r\n"
  11952. "\r\n"
  11953. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11954. "\r\n"
  11955. "------------\r\n";
  11956. ASSERT_TRUE(send_request(1, req));
  11957. }
  11958. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11959. auto handled = false;
  11960. Server svr;
  11961. svr.Post("/test", [&](const Request &req, Response &res) {
  11962. // Case-insensitive "utf-8''" prefix with a long value
  11963. const auto &file = req.form.get_file("file1");
  11964. ASSERT_EQ("file1", file.name);
  11965. // 8000 chars exercises both the Content-Disposition parser and the
  11966. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11967. // Prior to the fix, std::regex_match on this header would cause O(N)
  11968. // stack recursion in libstdc++, leading to SIGSEGV.
  11969. std::string expected_filename(8000, 'A');
  11970. ASSERT_EQ(expected_filename, file.filename);
  11971. res.set_content("ok", "text/plain");
  11972. handled = true;
  11973. });
  11974. thread t = thread([&] { svr.listen(HOST, PORT); });
  11975. auto se = detail::scope_exit([&] {
  11976. svr.stop();
  11977. t.join();
  11978. ASSERT_FALSE(svr.is_running());
  11979. ASSERT_TRUE(handled);
  11980. });
  11981. svr.wait_until_ready();
  11982. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11983. // Regression test for GHSA-qq6v-r583-3h69
  11984. std::string long_filename(8000, 'A');
  11985. std::string body = "----------\r\n"
  11986. "Content-Disposition: form-data; name=\"file1\"; "
  11987. "filename*=\"Utf-8''" +
  11988. long_filename +
  11989. "\"\r\n"
  11990. "\r\n"
  11991. "hello\r\n"
  11992. "------------\r\n";
  11993. auto req = "POST /test HTTP/1.1\r\n"
  11994. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11995. "Content-Length: " +
  11996. std::to_string(body.size()) + "\r\n\r\n" + body;
  11997. ASSERT_TRUE(send_request(1, req));
  11998. }
  11999. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12000. auto handled = false;
  12001. Server svr;
  12002. svr.Post("/test", [&](const Request &req, Response &) {
  12003. ASSERT_EQ(2u, req.form.fields.size());
  12004. const auto &text1 = req.form.get_field("text1");
  12005. ASSERT_EQ("text1", text1);
  12006. const auto &text2 = req.form.get_field("text2");
  12007. ASSERT_EQ("text2", text2);
  12008. handled = true;
  12009. });
  12010. thread t = thread([&] { svr.listen(HOST, PORT); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. t.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. ASSERT_TRUE(handled);
  12016. });
  12017. svr.wait_until_ready();
  12018. auto req = "POST /test HTTP/1.1\r\n"
  12019. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12020. "Content-Length: 146\r\n"
  12021. "\r\n----------\r\n"
  12022. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12023. "\r\n"
  12024. "text1"
  12025. "\r\n----------\r\n"
  12026. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12027. "\r\n"
  12028. "text2"
  12029. "\r\n------------";
  12030. std::string response;
  12031. ASSERT_TRUE(send_request(1, req, &response));
  12032. ASSERT_EQ("200", response.substr(9, 3));
  12033. }
  12034. TEST(MultipartFormDataTest, ContentLength) {
  12035. auto handled = false;
  12036. Server svr;
  12037. svr.Post("/test", [&](const Request &req, Response &) {
  12038. ASSERT_EQ(2u, req.form.fields.size());
  12039. const auto &text1 = req.form.get_field("text1");
  12040. ASSERT_EQ("text1", text1);
  12041. const auto &text2 = req.form.get_field("text2");
  12042. ASSERT_EQ("text2", text2);
  12043. handled = true;
  12044. });
  12045. thread t = thread([&] { svr.listen(HOST, PORT); });
  12046. auto se = detail::scope_exit([&] {
  12047. svr.stop();
  12048. t.join();
  12049. ASSERT_FALSE(svr.is_running());
  12050. ASSERT_TRUE(handled);
  12051. });
  12052. svr.wait_until_ready();
  12053. auto req = "POST /test HTTP/1.1\r\n"
  12054. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12055. "Content-Length: 167\r\n"
  12056. "\r\n----------\r\n"
  12057. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12058. "Content-Length: 5\r\n"
  12059. "\r\n"
  12060. "text1"
  12061. "\r\n----------\r\n"
  12062. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12063. "\r\n"
  12064. "text2"
  12065. "\r\n------------\r\n";
  12066. std::string response;
  12067. ASSERT_TRUE(send_request(1, req, &response));
  12068. ASSERT_EQ("200", response.substr(9, 3));
  12069. }
  12070. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12071. auto handled = false;
  12072. Server svr;
  12073. svr.Post("/test", [&](const Request &req, Response &) {
  12074. ASSERT_EQ(2u, req.form.fields.size());
  12075. const auto &text1 = req.form.get_field("text1");
  12076. ASSERT_EQ("text1", text1);
  12077. // TODO: Add header access for text fields if needed
  12078. const auto &text2 = req.form.get_field("text2");
  12079. ASSERT_EQ("text2", text2);
  12080. // TODO: Header access for text fields needs to be implemented
  12081. // auto &headers = it->second.headers;
  12082. // ASSERT_EQ(3U, headers.size());
  12083. // auto custom_header = headers.find("x-whatever");
  12084. // ASSERT_TRUE(custom_header != headers.end());
  12085. // ASSERT_NE("customvalue", custom_header->second);
  12086. // ASSERT_EQ("CustomValue", custom_header->second);
  12087. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12088. handled = true;
  12089. });
  12090. thread t = thread([&] { svr.listen(HOST, PORT); });
  12091. auto se = detail::scope_exit([&] {
  12092. svr.stop();
  12093. t.join();
  12094. ASSERT_FALSE(svr.is_running());
  12095. ASSERT_TRUE(handled);
  12096. });
  12097. svr.wait_until_ready();
  12098. auto req = "POST /test HTTP/1.1\r\n"
  12099. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12100. "Content-Length: 232\r\n"
  12101. "\r\n----------\r\n"
  12102. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12103. "Content-Length: 5\r\n"
  12104. "X-Test: 1\r\n"
  12105. "\r\n"
  12106. "text1"
  12107. "\r\n----------\r\n"
  12108. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12109. "Content-Type: text/plain\r\n"
  12110. "X-Whatever: CustomValue\r\n"
  12111. "\r\n"
  12112. "text2"
  12113. "\r\n------------\r\n"
  12114. "That should be disregarded. Not even read";
  12115. std::string response;
  12116. ASSERT_TRUE(send_request(1, req, &response));
  12117. ASSERT_EQ("200", response.substr(9, 3));
  12118. }
  12119. TEST(MultipartFormDataTest, LargeHeader) {
  12120. auto handled = false;
  12121. Server svr;
  12122. svr.Post("/test", [&](const Request &req, Response &) {
  12123. ASSERT_EQ(1u, req.form.fields.size());
  12124. const auto &text = req.form.get_field("name1");
  12125. ASSERT_EQ("text1", text);
  12126. handled = true;
  12127. });
  12128. thread t = thread([&] { svr.listen(HOST, PORT); });
  12129. auto se = detail::scope_exit([&] {
  12130. svr.stop();
  12131. t.join();
  12132. ASSERT_FALSE(svr.is_running());
  12133. ASSERT_TRUE(handled);
  12134. });
  12135. svr.wait_until_ready();
  12136. auto boundary = std::string("cpp-httplib-multipart-data");
  12137. std::string content = "--" + boundary +
  12138. "\r\n"
  12139. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12140. "\r\n"
  12141. "text1\r\n"
  12142. "--" +
  12143. boundary + "--\r\n";
  12144. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12145. "Content-Type: multipart/form-data;boundary=" +
  12146. boundary +
  12147. "\r\n"
  12148. "Content-Length: " +
  12149. std::to_string(content.size()) +
  12150. "\r\n"
  12151. "Dummy-Header: ";
  12152. std::string header_suffix = "\r\n"
  12153. "\r\n";
  12154. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12155. size_t header_dummy_size =
  12156. read_buff_size -
  12157. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12158. auto header_dummy = std::string(header_dummy_size, '@');
  12159. auto req = header_prefix + header_dummy + header_suffix + content;
  12160. std::string response;
  12161. ASSERT_TRUE(send_request(1, req, &response));
  12162. ASSERT_EQ("200", response.substr(9, 3));
  12163. }
  12164. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12165. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12166. // (not chunked Transfer-Encoding) after the streaming refactor.
  12167. auto handled = false;
  12168. Server svr;
  12169. svr.Post("/upload", [&](const Request &req, Response &res) {
  12170. auto cl_it = req.headers.find("Content-Length");
  12171. EXPECT_TRUE(cl_it != req.headers.end());
  12172. auto te_it = req.headers.find("Transfer-Encoding");
  12173. EXPECT_TRUE(te_it == req.headers.end());
  12174. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12175. res.set_content("ok", "text/plain");
  12176. handled = true;
  12177. });
  12178. auto port = svr.bind_to_any_port(HOST);
  12179. auto t = thread([&] { svr.listen_after_bind(); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. t.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. ASSERT_TRUE(handled);
  12185. });
  12186. svr.wait_until_ready();
  12187. UploadFormDataItems items = {
  12188. {"field1", "hello", "", "text/plain"},
  12189. {"file1", "world", "test.txt", "application/octet-stream"},
  12190. };
  12191. Client cli(HOST, port);
  12192. auto res = cli.Post("/upload", {}, items);
  12193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12194. EXPECT_EQ(StatusCode::OK_200, res->status);
  12195. }
  12196. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12197. // Verify that make_multipart_content_provider coalesces many small segments
  12198. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12199. constexpr size_t kItemCount = 1000;
  12200. UploadFormDataItems items;
  12201. items.reserve(kItemCount);
  12202. for (size_t i = 0; i < kItemCount; i++) {
  12203. items.push_back(
  12204. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12205. }
  12206. const std::string boundary = "----test-boundary";
  12207. auto content_length = detail::get_multipart_content_length(items, boundary);
  12208. auto provider = detail::make_multipart_content_provider(items, boundary);
  12209. // Drive the provider the same way write_content_with_progress does
  12210. size_t write_count = 0;
  12211. size_t total_bytes = 0;
  12212. DataSink sink;
  12213. size_t offset = 0;
  12214. sink.write = [&](const char *d, size_t l) -> bool {
  12215. (void)d;
  12216. write_count++;
  12217. total_bytes += l;
  12218. offset += l;
  12219. return true;
  12220. };
  12221. sink.is_writable = []() -> bool { return true; };
  12222. while (offset < content_length) {
  12223. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12224. }
  12225. EXPECT_EQ(content_length, total_bytes);
  12226. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12227. // With buffering into 64KB blocks, write_count should be much smaller.
  12228. auto segment_count = 3 * kItemCount + 1;
  12229. EXPECT_LT(write_count, segment_count / 10);
  12230. }
  12231. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12232. // Integration test: send many UploadFormDataItems and verify the server
  12233. // receives all of them correctly (#2410).
  12234. constexpr size_t kItemCount = 500;
  12235. auto handled = false;
  12236. Server svr;
  12237. svr.Post("/upload", [&](const Request &req, Response &res) {
  12238. EXPECT_EQ(kItemCount, req.form.fields.size());
  12239. for (size_t i = 0; i < kItemCount; i++) {
  12240. auto key = "field" + std::to_string(i);
  12241. auto val = "value" + std::to_string(i);
  12242. auto it = req.form.fields.find(key);
  12243. if (it != req.form.fields.end()) {
  12244. EXPECT_EQ(val, it->second.content);
  12245. } else {
  12246. ADD_FAILURE() << "Missing field: " << key;
  12247. }
  12248. }
  12249. res.set_content("ok", "text/plain");
  12250. handled = true;
  12251. });
  12252. auto port = svr.bind_to_any_port(HOST);
  12253. auto t = thread([&] { svr.listen_after_bind(); });
  12254. auto se = detail::scope_exit([&] {
  12255. svr.stop();
  12256. t.join();
  12257. ASSERT_FALSE(svr.is_running());
  12258. ASSERT_TRUE(handled);
  12259. });
  12260. svr.wait_until_ready();
  12261. UploadFormDataItems items;
  12262. items.reserve(kItemCount);
  12263. for (size_t i = 0; i < kItemCount; i++) {
  12264. items.push_back(
  12265. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12266. }
  12267. Client cli(HOST, port);
  12268. auto res = cli.Post("/upload", items);
  12269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12270. EXPECT_EQ(StatusCode::OK_200, res->status);
  12271. }
  12272. TEST(MultipartFormDataTest, MakeFileProvider) {
  12273. // Verify make_file_provider sends a file's contents correctly.
  12274. const std::string file_content(4096, 'Z');
  12275. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12276. {
  12277. std::ofstream ofs(tmp_path, std::ios::binary);
  12278. ofs.write(file_content.data(),
  12279. static_cast<std::streamsize>(file_content.size()));
  12280. }
  12281. auto handled = false;
  12282. Server svr;
  12283. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12284. const ContentReader &content_reader) {
  12285. ASSERT_TRUE(req.is_multipart_form_data());
  12286. std::vector<FormData> items;
  12287. content_reader(
  12288. [&](const FormData &file) {
  12289. items.push_back(file);
  12290. return true;
  12291. },
  12292. [&](const char *data, size_t data_length) {
  12293. items.back().content.append(data, data_length);
  12294. return true;
  12295. });
  12296. ASSERT_EQ(1u, items.size());
  12297. EXPECT_EQ("myfile", items[0].name);
  12298. EXPECT_EQ("data.bin", items[0].filename);
  12299. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12300. EXPECT_EQ(file_content, items[0].content);
  12301. handled = true;
  12302. });
  12303. auto port = svr.bind_to_any_port(HOST);
  12304. auto t = thread([&] { svr.listen_after_bind(); });
  12305. auto se = detail::scope_exit([&] {
  12306. svr.stop();
  12307. t.join();
  12308. ASSERT_FALSE(svr.is_running());
  12309. ASSERT_TRUE(handled);
  12310. std::remove(tmp_path.c_str());
  12311. });
  12312. svr.wait_until_ready();
  12313. FormDataProviderItems providers;
  12314. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12315. "application/octet-stream"));
  12316. Client cli(HOST, port);
  12317. auto res = cli.Post("/upload", {}, {}, providers);
  12318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12319. EXPECT_EQ(StatusCode::OK_200, res->status);
  12320. }
  12321. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12322. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12323. // (100) headers is rejected with a 400 Bad Request response.
  12324. Server svr;
  12325. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12326. res.set_content("ok", "text/plain");
  12327. });
  12328. thread t = thread([&] { svr.listen(HOST, PORT); });
  12329. auto se = detail::scope_exit([&] {
  12330. svr.stop();
  12331. t.join();
  12332. ASSERT_FALSE(svr.is_running());
  12333. });
  12334. svr.wait_until_ready();
  12335. // Build a multipart part with 101 custom headers (exceeding
  12336. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12337. std::stringstream body;
  12338. body << "--simpleboundary\r\n"
  12339. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12340. for (int i = 0; i < 101; i++) {
  12341. body << "X-Custom-Header-" << i << ": value\r\n";
  12342. }
  12343. body << "\r\n"
  12344. << "value1\r\n"
  12345. << "--simpleboundary--\r\n";
  12346. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12347. Client cli(HOST, PORT);
  12348. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12351. }
  12352. TEST(MakeFileBodyTest, Basic) {
  12353. const std::string file_content(4096, 'Z');
  12354. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12355. {
  12356. std::ofstream ofs(tmp_path, std::ios::binary);
  12357. ofs.write(file_content.data(),
  12358. static_cast<std::streamsize>(file_content.size()));
  12359. }
  12360. auto handled = false;
  12361. Server svr;
  12362. svr.Post("/upload", [&](const Request &req, Response &res) {
  12363. EXPECT_EQ(file_content, req.body);
  12364. handled = true;
  12365. res.status = StatusCode::OK_200;
  12366. });
  12367. auto port = svr.bind_to_any_port(HOST);
  12368. auto t = thread([&] { svr.listen_after_bind(); });
  12369. auto se = detail::scope_exit([&] {
  12370. svr.stop();
  12371. t.join();
  12372. ASSERT_FALSE(svr.is_running());
  12373. ASSERT_TRUE(handled);
  12374. std::remove(tmp_path.c_str());
  12375. });
  12376. svr.wait_until_ready();
  12377. auto fb = make_file_body(tmp_path);
  12378. ASSERT_GT(fb.first, 0u);
  12379. Client cli(HOST, port);
  12380. auto res =
  12381. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12383. EXPECT_EQ(StatusCode::OK_200, res->status);
  12384. }
  12385. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12386. static constexpr unsigned int number_of_tasks{1000000};
  12387. std::atomic_uint count{0};
  12388. std::unique_ptr<TaskQueue> task_queue{
  12389. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12390. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12391. auto queued = task_queue->enqueue(
  12392. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12393. EXPECT_TRUE(queued);
  12394. }
  12395. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12396. task_queue->shutdown();
  12397. #else
  12398. EXPECT_NO_THROW(task_queue->shutdown());
  12399. #endif
  12400. EXPECT_EQ(number_of_tasks, count.load());
  12401. }
  12402. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12403. static constexpr unsigned int number_of_tasks{1000000};
  12404. static constexpr unsigned int qlimit{2};
  12405. unsigned int queued_count{0};
  12406. std::atomic_uint count{0};
  12407. std::unique_ptr<TaskQueue> task_queue{
  12408. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12409. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12410. if (task_queue->enqueue(
  12411. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12412. queued_count++;
  12413. }
  12414. }
  12415. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12416. task_queue->shutdown();
  12417. #else
  12418. EXPECT_NO_THROW(task_queue->shutdown());
  12419. #endif
  12420. EXPECT_EQ(queued_count, count.load());
  12421. EXPECT_TRUE(queued_count <= number_of_tasks);
  12422. EXPECT_TRUE(queued_count >= qlimit);
  12423. }
  12424. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12425. // Use a short idle timeout so a dynamic thread spawns, times out and
  12426. // exits during the test, and the pool keeps working afterwards.
  12427. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12428. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12429. /*idle_timeout_sec=*/1}};
  12430. std::atomic_uint count{0};
  12431. std::condition_variable cv;
  12432. std::mutex mtx;
  12433. bool release = false;
  12434. // Block the base thread so the second task spawns a dynamic thread.
  12435. EXPECT_TRUE(task_queue->enqueue([&] {
  12436. std::unique_lock<std::mutex> lock(mtx);
  12437. while (!release) {
  12438. cv.wait(lock);
  12439. }
  12440. count++;
  12441. }));
  12442. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12443. // Let the dynamic thread finish its task and exceed the idle timeout.
  12444. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12445. {
  12446. std::unique_lock<std::mutex> lock(mtx);
  12447. release = true;
  12448. }
  12449. cv.notify_all();
  12450. // The pool must still accept and run tasks after the dynamic thread exited.
  12451. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12452. task_queue->shutdown();
  12453. EXPECT_EQ(3u, count.load());
  12454. }
  12455. TEST(TaskQueueTest, MaxQueuedRequests) {
  12456. static constexpr unsigned int qlimit{3};
  12457. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12458. std::condition_variable sem_cv;
  12459. std::mutex sem_mtx;
  12460. int credits = 0;
  12461. bool queued;
  12462. /* Fill up the queue with tasks that will block until we give them credits to
  12463. * complete. */
  12464. for (unsigned int n = 0; n <= qlimit;) {
  12465. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12466. std::unique_lock<std::mutex> lock(sem_mtx);
  12467. while (credits <= 0) {
  12468. sem_cv.wait(lock);
  12469. }
  12470. /* Consume the credit and signal the test code if they are all gone. */
  12471. if (--credits == 0) { sem_cv.notify_one(); }
  12472. });
  12473. if (n < qlimit) {
  12474. /* The first qlimit enqueues must succeed. */
  12475. EXPECT_TRUE(queued);
  12476. } else {
  12477. /* The last one will succeed only when the worker thread
  12478. * starts and dequeues the first blocking task. Although
  12479. * not necessary for the correctness of this test, we sleep for
  12480. * a short while to avoid busy waiting. */
  12481. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12482. }
  12483. if (queued) { n++; }
  12484. }
  12485. /* Further enqueues must fail since the queue is full. */
  12486. for (auto i = 0; i < 4; i++) {
  12487. queued = task_queue->enqueue([] {});
  12488. EXPECT_FALSE(queued);
  12489. }
  12490. /* Give the credits to allow the previous tasks to complete. */
  12491. {
  12492. std::unique_lock<std::mutex> lock(sem_mtx);
  12493. credits += qlimit + 1;
  12494. }
  12495. sem_cv.notify_all();
  12496. /* Wait for all the credits to be consumed. */
  12497. {
  12498. std::unique_lock<std::mutex> lock(sem_mtx);
  12499. while (credits > 0) {
  12500. sem_cv.wait(lock);
  12501. }
  12502. }
  12503. /* Check that we are able again to enqueue at least qlimit tasks. */
  12504. for (unsigned int i = 0; i < qlimit; i++) {
  12505. queued = task_queue->enqueue([] {});
  12506. EXPECT_TRUE(queued);
  12507. }
  12508. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12509. task_queue->shutdown();
  12510. #else
  12511. EXPECT_NO_THROW(task_queue->shutdown());
  12512. #endif
  12513. }
  12514. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12515. Server svr;
  12516. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12517. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12518. });
  12519. svr.Get("/hello", [](const Request &req, Response &res) {
  12520. res.set_content(req.get_param_value("key"), "text/plain");
  12521. });
  12522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12523. auto se = detail::scope_exit([&] {
  12524. svr.stop();
  12525. thread.join();
  12526. ASSERT_FALSE(svr.is_running());
  12527. });
  12528. svr.wait_until_ready();
  12529. {
  12530. Client cli(HOST, PORT);
  12531. cli.set_follow_location(true);
  12532. auto res = cli.Get("/");
  12533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12534. EXPECT_EQ(StatusCode::OK_200, res->status);
  12535. EXPECT_EQ("val&key2=val2", res->body);
  12536. }
  12537. }
  12538. #endif
  12539. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12540. Server svr;
  12541. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12542. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12543. });
  12544. svr.Get("/hello", [](const Request &req, Response &res) {
  12545. res.set_content(req.get_param_value("key"), "text/plain");
  12546. });
  12547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12548. auto se = detail::scope_exit([&] {
  12549. svr.stop();
  12550. thread.join();
  12551. ASSERT_FALSE(svr.is_running());
  12552. });
  12553. svr.wait_until_ready();
  12554. {
  12555. Client cli(HOST, PORT);
  12556. cli.set_follow_location(true);
  12557. auto res = cli.Get("/");
  12558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12559. EXPECT_EQ(StatusCode::OK_200, res->status);
  12560. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12561. }
  12562. }
  12563. TEST(RedirectTest, RedirectWithPlusInPath) {
  12564. Server svr;
  12565. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12566. res.set_redirect("/a+b");
  12567. });
  12568. // Route pattern uses regex; escape + as \\+
  12569. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12570. res.set_content(req.path, "text/plain");
  12571. });
  12572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12573. auto se = detail::scope_exit([&] {
  12574. svr.stop();
  12575. thread.join();
  12576. ASSERT_FALSE(svr.is_running());
  12577. });
  12578. svr.wait_until_ready();
  12579. {
  12580. Client cli(HOST, PORT);
  12581. cli.set_follow_location(true);
  12582. auto res = cli.Get("/");
  12583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12584. EXPECT_EQ(StatusCode::OK_200, res->status);
  12585. EXPECT_EQ("/a+b", res->body);
  12586. }
  12587. }
  12588. #ifdef CPPHTTPLIB_SSL_ENABLED
  12589. TEST(RedirectTest, Issue2185_Online) {
  12590. SSLClient client("github.com");
  12591. client.set_follow_location(true);
  12592. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12593. "Coollab-Windows.zip");
  12594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12595. EXPECT_EQ(StatusCode::OK_200, res->status);
  12596. EXPECT_EQ(9920427U, res->body.size());
  12597. }
  12598. #endif
  12599. TEST(VulnerabilityTest, CRLFInjection) {
  12600. Server svr;
  12601. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12602. res.set_content("Hello 1", "text/plain");
  12603. });
  12604. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12605. res.set_content("Hello 2", "text/plain");
  12606. });
  12607. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12608. res.set_content("Hello 3", "text/plain");
  12609. });
  12610. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12611. res.set_content("Hello 4", "text/plain");
  12612. });
  12613. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12614. for (const auto &x : req.headers) {
  12615. auto key = x.first;
  12616. EXPECT_STRNE("evil", key.c_str());
  12617. }
  12618. });
  12619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12620. auto se = detail::scope_exit([&] {
  12621. svr.stop();
  12622. thread.join();
  12623. ASSERT_FALSE(svr.is_running());
  12624. });
  12625. svr.wait_until_ready();
  12626. {
  12627. Client cli(HOST, PORT);
  12628. cli.Post("/test1", "A=B",
  12629. "application/x-www-form-urlencoded\r\nevil: hello1");
  12630. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12631. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12632. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12633. }
  12634. }
  12635. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12636. auto server_thread = std::thread([] {
  12637. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12638. default_socket_options(srv);
  12639. sockaddr_in addr{};
  12640. addr.sin_family = AF_INET;
  12641. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12642. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12643. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12644. ::listen(srv, 1);
  12645. sockaddr_in cli_addr{};
  12646. socklen_t cli_len = sizeof(cli_addr);
  12647. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12648. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12649. std::string buf_all;
  12650. char buf[2048];
  12651. ssize_t n;
  12652. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12653. buf_all.append(buf, static_cast<size_t>(n));
  12654. size_t pos;
  12655. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12656. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12657. auto e = request_block.find("\r\n");
  12658. if (e != std::string::npos) {
  12659. auto request_line = request_block.substr(0, e);
  12660. std::string msg =
  12661. "CRLF injection detected in request line: '" + request_line + "'";
  12662. EXPECT_FALSE(true) << msg;
  12663. }
  12664. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12665. ::send(cli,
  12666. #ifdef _WIN32
  12667. static_cast<const char *>(resp.c_str()),
  12668. static_cast<int>(resp.size()),
  12669. #else
  12670. resp.c_str(), resp.size(),
  12671. #endif
  12672. 0);
  12673. buf_all.erase(0, pos + 4);
  12674. }
  12675. }
  12676. detail::close_socket(cli);
  12677. detail::close_socket(srv);
  12678. });
  12679. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12680. auto cli = Client("127.0.0.1", PORT + 1);
  12681. auto headers = Headers{
  12682. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12683. {"Connection", "keep-alive"}};
  12684. auto res = cli.Get("/hi", headers);
  12685. EXPECT_FALSE(res);
  12686. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12687. server_thread.join();
  12688. }
  12689. TEST(PathParamsTest, StaticMatch) {
  12690. const auto pattern = "/users/all";
  12691. detail::PathParamsMatcher matcher(pattern);
  12692. Request request;
  12693. request.path = "/users/all";
  12694. ASSERT_TRUE(matcher.match(request));
  12695. std::unordered_map<std::string, std::string> expected_params = {};
  12696. EXPECT_EQ(request.path_params, expected_params);
  12697. }
  12698. TEST(PathParamsTest, StaticMismatch) {
  12699. const auto pattern = "/users/all";
  12700. detail::PathParamsMatcher matcher(pattern);
  12701. Request request;
  12702. request.path = "/users/1";
  12703. ASSERT_FALSE(matcher.match(request));
  12704. }
  12705. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12706. const auto pattern = "/users/:id/subscriptions";
  12707. detail::PathParamsMatcher matcher(pattern);
  12708. Request request;
  12709. request.path = "/users/42/subscriptions";
  12710. ASSERT_TRUE(matcher.match(request));
  12711. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12712. EXPECT_EQ(request.path_params, expected_params);
  12713. }
  12714. TEST(PathParamsTest, SingleParamInTheEnd) {
  12715. const auto pattern = "/users/:id";
  12716. detail::PathParamsMatcher matcher(pattern);
  12717. Request request;
  12718. request.path = "/users/24";
  12719. ASSERT_TRUE(matcher.match(request));
  12720. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12721. EXPECT_EQ(request.path_params, expected_params);
  12722. }
  12723. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12724. const auto pattern = "/users/:id/";
  12725. detail::PathParamsMatcher matcher(pattern);
  12726. Request request;
  12727. request.path = "/users/42/";
  12728. ASSERT_TRUE(matcher.match(request));
  12729. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12730. EXPECT_EQ(request.path_params, expected_params);
  12731. }
  12732. TEST(PathParamsTest, EmptyParam) {
  12733. const auto pattern = "/users/:id/";
  12734. detail::PathParamsMatcher matcher(pattern);
  12735. Request request;
  12736. request.path = "/users//";
  12737. ASSERT_TRUE(matcher.match(request));
  12738. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12739. EXPECT_EQ(request.path_params, expected_params);
  12740. }
  12741. TEST(PathParamsTest, FragmentMismatch) {
  12742. const auto pattern = "/users/:id/";
  12743. detail::PathParamsMatcher matcher(pattern);
  12744. Request request;
  12745. request.path = "/admins/24/";
  12746. ASSERT_FALSE(matcher.match(request));
  12747. }
  12748. TEST(PathParamsTest, ExtraFragments) {
  12749. const auto pattern = "/users/:id";
  12750. detail::PathParamsMatcher matcher(pattern);
  12751. Request request;
  12752. request.path = "/users/42/subscriptions";
  12753. ASSERT_FALSE(matcher.match(request));
  12754. }
  12755. TEST(PathParamsTest, MissingTrailingParam) {
  12756. const auto pattern = "/users/:id";
  12757. detail::PathParamsMatcher matcher(pattern);
  12758. Request request;
  12759. request.path = "/users";
  12760. ASSERT_FALSE(matcher.match(request));
  12761. }
  12762. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12763. const auto pattern = "/users/:id/subscriptions";
  12764. detail::PathParamsMatcher matcher(pattern);
  12765. Request request;
  12766. request.path = "/users/subscriptions";
  12767. ASSERT_FALSE(matcher.match(request));
  12768. }
  12769. TEST(PathParamsTest, MultipleParams) {
  12770. const auto pattern = "/users/:userid/subscriptions/:subid";
  12771. detail::PathParamsMatcher matcher(pattern);
  12772. Request request;
  12773. request.path = "/users/42/subscriptions/2";
  12774. ASSERT_TRUE(matcher.match(request));
  12775. std::unordered_map<std::string, std::string> expected_params = {
  12776. {"userid", "42"}, {"subid", "2"}};
  12777. EXPECT_EQ(request.path_params, expected_params);
  12778. }
  12779. TEST(PathParamsTest, SequenceOfParams) {
  12780. const auto pattern = "/values/:x/:y/:z";
  12781. detail::PathParamsMatcher matcher(pattern);
  12782. Request request;
  12783. request.path = "/values/1/2/3";
  12784. ASSERT_TRUE(matcher.match(request));
  12785. std::unordered_map<std::string, std::string> expected_params = {
  12786. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12787. EXPECT_EQ(request.path_params, expected_params);
  12788. }
  12789. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12790. const auto pattern = "/prefix:suffix";
  12791. detail::PathParamsMatcher matcher(pattern);
  12792. Request request;
  12793. request.path = "/prefix:suffix";
  12794. ASSERT_TRUE(matcher.match(request));
  12795. const std::unordered_map<std::string, std::string> expected_params = {};
  12796. EXPECT_EQ(request.path_params, expected_params);
  12797. }
  12798. TEST(ParseUrlTest, VariousPatterns) {
  12799. {
  12800. detail::UrlComponents uc;
  12801. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12802. EXPECT_EQ("http", uc.scheme);
  12803. EXPECT_EQ("example.com", uc.host);
  12804. EXPECT_EQ("8080", uc.port);
  12805. EXPECT_EQ("/path", uc.path);
  12806. EXPECT_EQ("?q=1", uc.query);
  12807. }
  12808. {
  12809. detail::UrlComponents uc;
  12810. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12811. EXPECT_EQ("https", uc.scheme);
  12812. EXPECT_EQ("example.com", uc.host);
  12813. EXPECT_TRUE(uc.port.empty());
  12814. EXPECT_EQ("/path", uc.path);
  12815. }
  12816. {
  12817. detail::UrlComponents uc;
  12818. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12819. EXPECT_EQ("::1", uc.host);
  12820. EXPECT_EQ("8080", uc.port);
  12821. EXPECT_EQ("/path", uc.path);
  12822. }
  12823. {
  12824. detail::UrlComponents uc;
  12825. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12826. }
  12827. {
  12828. detail::UrlComponents uc;
  12829. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12830. EXPECT_TRUE(uc.scheme.empty());
  12831. EXPECT_EQ("example.com", uc.host);
  12832. EXPECT_EQ("/path", uc.path);
  12833. EXPECT_EQ("?q=1", uc.query);
  12834. }
  12835. {
  12836. detail::UrlComponents uc;
  12837. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12838. EXPECT_TRUE(uc.host.empty());
  12839. EXPECT_EQ("/path", uc.path);
  12840. EXPECT_EQ("?q=1", uc.query);
  12841. }
  12842. {
  12843. detail::UrlComponents uc;
  12844. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12845. EXPECT_EQ("example.com", uc.host);
  12846. EXPECT_EQ("8080", uc.port);
  12847. }
  12848. {
  12849. // Unix socket path — must not be parsed as host
  12850. detail::UrlComponents uc;
  12851. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12852. EXPECT_TRUE(uc.host.empty());
  12853. }
  12854. {
  12855. detail::UrlComponents uc;
  12856. ASSERT_TRUE(detail::parse_url("", uc));
  12857. EXPECT_TRUE(uc.host.empty());
  12858. EXPECT_TRUE(uc.path.empty());
  12859. }
  12860. {
  12861. detail::UrlComponents uc;
  12862. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12863. }
  12864. {
  12865. detail::UrlComponents uc;
  12866. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12867. }
  12868. {
  12869. // Accepted by parse_url; callers restrict to http/https
  12870. detail::UrlComponents uc;
  12871. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12872. EXPECT_EQ("ftp", uc.scheme);
  12873. }
  12874. {
  12875. detail::UrlComponents uc;
  12876. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12877. }
  12878. {
  12879. detail::UrlComponents uc;
  12880. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12881. }
  12882. }
  12883. TEST(ParseUrlTest, FragmentHandling) {
  12884. {
  12885. detail::UrlComponents uc;
  12886. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12887. EXPECT_EQ("/path", uc.path);
  12888. EXPECT_TRUE(uc.query.empty());
  12889. }
  12890. {
  12891. detail::UrlComponents uc;
  12892. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12893. EXPECT_TRUE(uc.path.empty());
  12894. EXPECT_TRUE(uc.query.empty());
  12895. }
  12896. }
  12897. TEST(ParseUrlTest, UserinfoHandling) {
  12898. // Userinfo with @ but no colon — host includes @
  12899. detail::UrlComponents uc;
  12900. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12901. EXPECT_EQ("user@host.com", uc.host);
  12902. EXPECT_EQ("/path", uc.path);
  12903. }
  12904. TEST(ParseUrlTest, IPv6EdgeCases) {
  12905. {
  12906. detail::UrlComponents uc;
  12907. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12908. EXPECT_TRUE(uc.scheme.empty());
  12909. EXPECT_EQ("::1", uc.host);
  12910. EXPECT_EQ("8080", uc.port);
  12911. }
  12912. {
  12913. // Zone ID '%25' is not in [a-fA-F0-9:]
  12914. detail::UrlComponents uc;
  12915. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12916. }
  12917. }
  12918. TEST(ParseUrlTest, SchemeEdgeCases) {
  12919. {
  12920. detail::UrlComponents uc;
  12921. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12922. }
  12923. {
  12924. detail::UrlComponents uc;
  12925. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12926. }
  12927. {
  12928. detail::UrlComponents uc;
  12929. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12930. }
  12931. }
  12932. TEST(ParseUrlTest, PortEdgeCases) {
  12933. {
  12934. detail::UrlComponents uc;
  12935. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12936. EXPECT_TRUE(uc.port.empty());
  12937. EXPECT_EQ("/path", uc.path);
  12938. }
  12939. {
  12940. // parse_url accepts any port string; validation is done by parse_port
  12941. detail::UrlComponents uc;
  12942. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12943. EXPECT_EQ("abc", uc.port);
  12944. }
  12945. }
  12946. TEST(ParseUrlTest, WebSocketPatterns) {
  12947. {
  12948. detail::UrlComponents uc;
  12949. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12950. EXPECT_EQ("ws", uc.scheme);
  12951. EXPECT_EQ("echo.example.com", uc.host);
  12952. EXPECT_EQ("8080", uc.port);
  12953. EXPECT_EQ("/ws", uc.path);
  12954. }
  12955. {
  12956. detail::UrlComponents uc;
  12957. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12958. EXPECT_EQ("wss", uc.scheme);
  12959. EXPECT_EQ("echo.example.com", uc.host);
  12960. EXPECT_TRUE(uc.port.empty());
  12961. EXPECT_EQ("/ws", uc.path);
  12962. }
  12963. }
  12964. TEST(ParseUrlTest, QueryOnly) {
  12965. detail::UrlComponents uc;
  12966. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12967. EXPECT_TRUE(uc.host.empty());
  12968. EXPECT_TRUE(uc.path.empty());
  12969. EXPECT_EQ("?q=1&r=2", uc.query);
  12970. }
  12971. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12972. detail::UrlComponents uc;
  12973. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12974. EXPECT_TRUE(uc.scheme.empty());
  12975. EXPECT_EQ("example.com", uc.host);
  12976. EXPECT_EQ("443", uc.port);
  12977. EXPECT_EQ("/path", uc.path);
  12978. }
  12979. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12980. // If ipv6 regex working, regex match codepath is taken.
  12981. // else port will default to 80 in Client impl
  12982. int clientImplMagicPort = 80;
  12983. int port = 4321;
  12984. // above ports must be different to avoid false negative
  12985. EXPECT_NE(clientImplMagicPort, port);
  12986. std::string ipV6TestURL = "http://[ff06::c3]";
  12987. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12988. CLIENT_PRIVATE_KEY_FILE);
  12989. EXPECT_EQ(cli.port(), port);
  12990. }
  12991. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12992. auto file_path = "./www/dir/index.html";
  12993. auto dir_path = "./www/dir";
  12994. detail::FileStat stat_file(file_path);
  12995. EXPECT_TRUE(stat_file.is_file());
  12996. EXPECT_FALSE(stat_file.is_dir());
  12997. detail::FileStat stat_dir(dir_path);
  12998. EXPECT_FALSE(stat_dir.is_file());
  12999. EXPECT_TRUE(stat_dir.is_dir());
  13000. }
  13001. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13002. // IPv4 with default HTTP port (80)
  13003. EXPECT_EQ("example.com",
  13004. detail::make_host_and_port_string("example.com", 80, false));
  13005. // IPv4 with default HTTPS port (443)
  13006. EXPECT_EQ("example.com",
  13007. detail::make_host_and_port_string("example.com", 443, true));
  13008. // IPv4 with non-default HTTP port
  13009. EXPECT_EQ("example.com:8080",
  13010. detail::make_host_and_port_string("example.com", 8080, false));
  13011. // IPv4 with non-default HTTPS port
  13012. EXPECT_EQ("example.com:8443",
  13013. detail::make_host_and_port_string("example.com", 8443, true));
  13014. // IPv6 with default HTTP port (80)
  13015. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13016. // IPv6 with default HTTPS port (443)
  13017. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13018. // IPv6 with non-default HTTP port
  13019. EXPECT_EQ("[::1]:8080",
  13020. detail::make_host_and_port_string("::1", 8080, false));
  13021. // IPv6 with non-default HTTPS port
  13022. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13023. // IPv6 full address with default port
  13024. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13025. detail::make_host_and_port_string(
  13026. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13027. // IPv6 full address with non-default port
  13028. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13029. detail::make_host_and_port_string(
  13030. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13031. // IPv6 localhost with non-default port
  13032. EXPECT_EQ("[::1]:3000",
  13033. detail::make_host_and_port_string("::1", 3000, false));
  13034. // IPv6 with zone ID (link-local address) with default port
  13035. EXPECT_EQ("[fe80::1%eth0]",
  13036. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13037. // IPv6 with zone ID (link-local address) with non-default port
  13038. EXPECT_EQ("[fe80::1%eth0]:8080",
  13039. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13040. // Edge case: Port 443 with is_ssl=false (should add port)
  13041. EXPECT_EQ("example.com:443",
  13042. detail::make_host_and_port_string("example.com", 443, false));
  13043. // Edge case: Port 80 with is_ssl=true (should add port)
  13044. EXPECT_EQ("example.com:80",
  13045. detail::make_host_and_port_string("example.com", 80, true));
  13046. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13047. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13048. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13049. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13050. // Security fix: Already bracketed IPv6 should not get double brackets
  13051. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13052. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13053. EXPECT_EQ("[::1]:8080",
  13054. detail::make_host_and_port_string("[::1]", 8080, false));
  13055. EXPECT_EQ("[2001:db8::1]:8080",
  13056. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13057. EXPECT_EQ("[fe80::1%eth0]",
  13058. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13059. EXPECT_EQ("[fe80::1%eth0]:8080",
  13060. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13061. // Edge case: Empty host (should return as-is)
  13062. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13063. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13064. // This is a known limitation but shouldn't crash
  13065. EXPECT_EQ("[host:name]",
  13066. detail::make_host_and_port_string("host:name", 80, false));
  13067. // Port number edge cases (no validation, but should not crash)
  13068. EXPECT_EQ("example.com:0",
  13069. detail::make_host_and_port_string("example.com", 0, false));
  13070. EXPECT_EQ("example.com:-1",
  13071. detail::make_host_and_port_string("example.com", -1, false));
  13072. EXPECT_EQ("example.com:65535",
  13073. detail::make_host_and_port_string("example.com", 65535, false));
  13074. EXPECT_EQ("example.com:65536",
  13075. detail::make_host_and_port_string("example.com", 65536, false));
  13076. }
  13077. #ifdef CPPHTTPLIB_SSL_ENABLED
  13078. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13079. httplib::SSLClient cli("roblox.com", 443);
  13080. cli.set_follow_location(true);
  13081. auto res = cli.Get("/");
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. EXPECT_EQ(StatusCode::OK_200, res->status);
  13084. }
  13085. #endif
  13086. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13087. Server svr;
  13088. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13089. EXPECT_EQ(res.status, 400);
  13090. });
  13091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13092. auto se = detail::scope_exit([&] {
  13093. svr.stop();
  13094. thread.join();
  13095. ASSERT_FALSE(svr.is_running());
  13096. });
  13097. svr.wait_until_ready();
  13098. Client cli(HOST, PORT);
  13099. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13100. }
  13101. TEST(InvalidHeaderCharsTest, is_field_name) {
  13102. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13103. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13104. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13105. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13106. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13107. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13108. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13109. EXPECT_FALSE(detail::fields::is_field_name(""));
  13110. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13111. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13112. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13113. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13114. }
  13115. TEST(InvalidHeaderCharsTest, is_field_value) {
  13116. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13117. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13118. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13119. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13120. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13121. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13122. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13123. EXPECT_TRUE(detail::fields::is_field_value(""));
  13124. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13125. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13126. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13127. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13128. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13129. }
  13130. TEST(InvalidHeaderCharsTest, OnServer) {
  13131. Server svr;
  13132. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13133. std::string header = "Not Set";
  13134. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13135. res.set_header(header, "value");
  13136. res.set_content("Page Content Page Content", "text/plain");
  13137. });
  13138. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13139. std::string header = "Not Set";
  13140. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13141. res.set_header("X-Test", header);
  13142. res.set_content("Page Content Page Content", "text/plain");
  13143. });
  13144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13145. auto se = detail::scope_exit([&] {
  13146. svr.stop();
  13147. thread.join();
  13148. ASSERT_FALSE(svr.is_running());
  13149. });
  13150. svr.wait_until_ready();
  13151. Client cli(HOST, PORT);
  13152. {
  13153. auto res = cli.Get(
  13154. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13156. EXPECT_EQ("Page Content Page Content", res->body);
  13157. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13158. }
  13159. {
  13160. auto res = cli.Get(
  13161. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13163. EXPECT_EQ("Page Content Page Content", res->body);
  13164. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13165. }
  13166. }
  13167. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13168. auto handled = false;
  13169. Server svr;
  13170. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13171. thread t = thread([&] { svr.listen(HOST, PORT); });
  13172. auto se = detail::scope_exit([&] {
  13173. svr.stop();
  13174. t.join();
  13175. ASSERT_FALSE(svr.is_running());
  13176. ASSERT_FALSE(handled);
  13177. });
  13178. svr.wait_until_ready();
  13179. auto req = "POST /test HTTP/1.1\r\n"
  13180. "Content-Length: x\r\n"
  13181. "\r\n";
  13182. std::string response;
  13183. ASSERT_TRUE(send_request(1, req, &response));
  13184. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13185. response.substr(0, response.find("\r\n")));
  13186. }
  13187. #ifndef _WIN32
  13188. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13189. static constexpr char reject[] = "Unauthorized";
  13190. static constexpr char accept[] = "Upload accepted";
  13191. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13192. Server svr;
  13193. svr.set_expect_100_continue_handler(
  13194. [](const Request & /*req*/, Response &res) {
  13195. res.status = StatusCode::Unauthorized_401;
  13196. res.set_content(reject, "text/plain");
  13197. return res.status;
  13198. });
  13199. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13200. res.set_content(accept, "text/plain");
  13201. });
  13202. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13203. auto se = detail::scope_exit([&] {
  13204. svr.stop();
  13205. thread.join();
  13206. ASSERT_FALSE(svr.is_running());
  13207. });
  13208. svr.wait_until_ready();
  13209. {
  13210. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13211. curl_easy_init(), &curl_easy_cleanup};
  13212. ASSERT_NE(curl, nullptr);
  13213. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13214. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13215. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13216. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13217. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13218. &curl_slist_free_all};
  13219. ASSERT_NE(list, nullptr);
  13220. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13221. struct read_data {
  13222. size_t read_size;
  13223. size_t total_size;
  13224. } data = {0, total_size};
  13225. using read_callback_t =
  13226. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13227. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13228. void *userdata) -> size_t {
  13229. read_data *d = (read_data *)userdata;
  13230. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13231. std::fill_n(ptr, size * nmemb, 'A');
  13232. d->read_size += size * nmemb;
  13233. return size * nmemb;
  13234. };
  13235. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13236. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13237. std::vector<char> buffer;
  13238. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13239. using write_callback_t =
  13240. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13241. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13242. void *userdata) -> size_t {
  13243. std::vector<char> *buf = (std::vector<char> *)userdata;
  13244. buf->reserve(buf->size() + size * nmemb + 1);
  13245. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13246. return size * nmemb;
  13247. };
  13248. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13249. {
  13250. const auto res = curl_easy_perform(curl.get());
  13251. ASSERT_EQ(res, CURLE_OK);
  13252. }
  13253. {
  13254. auto response_code = long{};
  13255. const auto res =
  13256. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13257. ASSERT_EQ(res, CURLE_OK);
  13258. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13259. }
  13260. {
  13261. auto dl = curl_off_t{};
  13262. const auto res =
  13263. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13264. ASSERT_EQ(res, CURLE_OK);
  13265. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13266. }
  13267. {
  13268. buffer.push_back('\0');
  13269. ASSERT_STRCASEEQ(buffer.data(), reject);
  13270. }
  13271. }
  13272. }
  13273. #endif
  13274. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13275. // Regression test for #2458.
  13276. //
  13277. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13278. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13279. // ticket can make the client socket spuriously readable during the
  13280. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13281. // the client withholds the body and then blocks reading a response that never
  13282. // comes, failing with `Failed to read connection`.
  13283. //
  13284. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13285. // within the timeout. This raw OpenSSL server deliberately never sends
  13286. // `100 Continue`; the client must still deliver the body and receive 200.
  13287. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13288. signal(SIGPIPE, SIG_IGN);
  13289. const auto port = PORT + 4;
  13290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13291. ASSERT_NE(srv, INVALID_SOCKET);
  13292. int opt = 1;
  13293. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13294. sockaddr_in addr{};
  13295. addr.sin_family = AF_INET;
  13296. addr.sin_port = htons(static_cast<uint16_t>(port));
  13297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13298. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13299. ASSERT_EQ(0, ::listen(srv, 1));
  13300. std::atomic<size_t> server_body_bytes{0};
  13301. auto server_thread = std::thread([&] {
  13302. sockaddr_in cli_addr{};
  13303. socklen_t cli_len = sizeof(cli_addr);
  13304. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13305. if (cli == INVALID_SOCKET) { return; }
  13306. // Bound the lifetime of the server side so a buggy client (which never
  13307. // sends the body) cannot make this thread block forever on join.
  13308. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13309. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13310. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13311. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13312. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13313. SSL *ssl = SSL_new(ctx);
  13314. SSL_set_fd(ssl, static_cast<int>(cli));
  13315. if (SSL_accept(ssl) > 0) {
  13316. // Read the request headers. Reading here also flushes the TLS 1.3
  13317. // session tickets to the client. Deliberately do NOT send
  13318. // `100 Continue`.
  13319. std::string buf;
  13320. char tmp[1024];
  13321. while (buf.find("\r\n\r\n") == std::string::npos) {
  13322. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13323. if (n <= 0) { break; }
  13324. buf.append(tmp, static_cast<size_t>(n));
  13325. }
  13326. // A correct client sends the body now; count what arrives.
  13327. auto pos = buf.find("\r\n\r\n");
  13328. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13329. while (body < 4096) {
  13330. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13331. if (n <= 0) { break; }
  13332. body += static_cast<size_t>(n);
  13333. }
  13334. server_body_bytes = body;
  13335. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13336. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13337. SSL_shutdown(ssl);
  13338. }
  13339. SSL_free(ssl);
  13340. detail::close_socket(cli);
  13341. SSL_CTX_free(ctx);
  13342. });
  13343. auto se = detail::scope_exit([&] {
  13344. server_thread.join();
  13345. detail::close_socket(srv);
  13346. });
  13347. SSLClient cli("127.0.0.1", port);
  13348. cli.enable_server_certificate_verification(false);
  13349. cli.set_connection_timeout(5, 0);
  13350. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13351. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13352. std::string body(4096, 'A');
  13353. auto res = cli.Put("/api/test", body, "application/json");
  13354. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13355. EXPECT_EQ(StatusCode::OK_200, res->status);
  13356. EXPECT_EQ(body.size(), server_body_bytes.load());
  13357. }
  13358. #endif
  13359. template <typename S, typename C>
  13360. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13361. svr.Get("/stream", [&](const Request &, Response &res) {
  13362. auto data = new std::string("01234567890123456789");
  13363. res.set_content_provider(
  13364. data->size(), "text/plain",
  13365. [&, data](size_t offset, size_t length, DataSink &sink) {
  13366. const size_t DATA_CHUNK_SIZE = 4;
  13367. const auto &d = *data;
  13368. std::this_thread::sleep_for(std::chrono::seconds(1));
  13369. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13370. return true;
  13371. },
  13372. [data](bool success) {
  13373. EXPECT_FALSE(success);
  13374. delete data;
  13375. });
  13376. });
  13377. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13378. auto i = new size_t(0);
  13379. res.set_content_provider(
  13380. "text/plain",
  13381. [i](size_t, DataSink &sink) {
  13382. if (*i < 5) {
  13383. std::this_thread::sleep_for(std::chrono::seconds(1));
  13384. sink.write("abcd", 4);
  13385. (*i)++;
  13386. } else {
  13387. sink.done();
  13388. }
  13389. return true;
  13390. },
  13391. [i](bool success) {
  13392. EXPECT_FALSE(success);
  13393. delete i;
  13394. });
  13395. });
  13396. svr.Get("/chunked", [&](const Request &, Response &res) {
  13397. auto i = new size_t(0);
  13398. res.set_chunked_content_provider(
  13399. "text/plain",
  13400. [i](size_t, DataSink &sink) {
  13401. if (*i < 5) {
  13402. std::this_thread::sleep_for(std::chrono::seconds(1));
  13403. sink.os << "abcd";
  13404. (*i)++;
  13405. } else {
  13406. sink.done();
  13407. }
  13408. return true;
  13409. },
  13410. [i](bool success) {
  13411. EXPECT_FALSE(success);
  13412. delete i;
  13413. });
  13414. });
  13415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13416. auto se = detail::scope_exit([&] {
  13417. svr.stop();
  13418. listen_thread.join();
  13419. ASSERT_FALSE(svr.is_running());
  13420. });
  13421. svr.wait_until_ready();
  13422. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13423. {
  13424. auto start = std::chrono::steady_clock::now();
  13425. auto res = cli.Get("/stream");
  13426. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13427. std::chrono::steady_clock::now() - start)
  13428. .count();
  13429. ASSERT_FALSE(res);
  13430. EXPECT_EQ(Error::Read, res.error());
  13431. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13432. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13433. }
  13434. {
  13435. auto start = std::chrono::steady_clock::now();
  13436. auto res = cli.Get("/stream_without_length");
  13437. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13438. std::chrono::steady_clock::now() - start)
  13439. .count();
  13440. ASSERT_FALSE(res);
  13441. EXPECT_EQ(Error::Read, res.error());
  13442. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13443. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13444. }
  13445. {
  13446. auto start = std::chrono::steady_clock::now();
  13447. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13448. EXPECT_EQ("abcd", string(data, data_length));
  13449. return true;
  13450. });
  13451. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13452. std::chrono::steady_clock::now() - start)
  13453. .count();
  13454. ASSERT_FALSE(res);
  13455. EXPECT_EQ(Error::Read, res.error());
  13456. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13457. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13458. }
  13459. }
  13460. TEST(MaxTimeoutTest, ContentStream) {
  13461. time_t timeout = 2000;
  13462. time_t threshold = 200;
  13463. Server svr;
  13464. Client cli("localhost", PORT);
  13465. max_timeout_test(svr, cli, timeout, threshold);
  13466. }
  13467. #ifdef CPPHTTPLIB_SSL_ENABLED
  13468. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13469. time_t timeout = 2000;
  13470. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13472. SSLClient cli("localhost", PORT);
  13473. cli.enable_server_certificate_verification(false);
  13474. max_timeout_test(svr, cli, timeout, threshold);
  13475. }
  13476. #endif
  13477. class EventDispatcher {
  13478. public:
  13479. EventDispatcher() {}
  13480. bool wait_event(DataSink *sink) {
  13481. unique_lock<mutex> lk(m_);
  13482. int id = id_;
  13483. // Wait with timeout to prevent hanging if client disconnects
  13484. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13485. [&] { return cid_ == id; })) {
  13486. return false; // Timeout occurred
  13487. }
  13488. sink->write(message_.data(), message_.size());
  13489. return true;
  13490. }
  13491. void send_event(const string &message) {
  13492. lock_guard<mutex> lk(m_);
  13493. cid_ = id_++;
  13494. message_ = message;
  13495. cv_.notify_all();
  13496. }
  13497. private:
  13498. mutex m_;
  13499. condition_variable cv_;
  13500. atomic_int id_{0};
  13501. atomic_int cid_{-1};
  13502. string message_;
  13503. };
  13504. TEST(ClientInThreadTest, Issue2068) {
  13505. EventDispatcher ed;
  13506. Server svr;
  13507. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13508. res.set_chunked_content_provider("text/event-stream",
  13509. [&](size_t /*offset*/, DataSink &sink) {
  13510. return ed.wait_event(&sink);
  13511. });
  13512. });
  13513. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13514. svr.wait_until_ready();
  13515. thread event_thread([&] {
  13516. int id = 0;
  13517. while (svr.is_running()) {
  13518. this_thread::sleep_for(chrono::milliseconds(500));
  13519. std::stringstream ss;
  13520. ss << "data: " << id << "\n\n";
  13521. ed.send_event(ss.str());
  13522. id++;
  13523. }
  13524. });
  13525. auto se = detail::scope_exit([&] {
  13526. svr.stop();
  13527. listen_thread.join();
  13528. event_thread.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. {
  13532. auto client = detail::make_unique<Client>(HOST, PORT);
  13533. client->set_read_timeout(std::chrono::minutes(10));
  13534. std::atomic<bool> stop{false};
  13535. std::thread t([&] {
  13536. client->Get("/event1",
  13537. [&](const char *, size_t) -> bool { return !stop; });
  13538. });
  13539. std::this_thread::sleep_for(std::chrono::seconds(2));
  13540. stop = true;
  13541. client->stop();
  13542. t.join();
  13543. // Reset client after thread has finished
  13544. client.reset();
  13545. }
  13546. }
  13547. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13548. auto handled = false;
  13549. Server svr;
  13550. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13551. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13552. auto se = detail::scope_exit([&] {
  13553. svr.stop();
  13554. t.join();
  13555. ASSERT_FALSE(svr.is_running());
  13556. ASSERT_FALSE(handled);
  13557. });
  13558. svr.wait_until_ready();
  13559. // Two Content-Length headers with different values — must be rejected
  13560. auto req = "POST /test HTTP/1.1\r\n"
  13561. "Content-Length: 5\r\n"
  13562. "Content-Length: 10\r\n"
  13563. "\r\n"
  13564. "hello";
  13565. std::string response;
  13566. ASSERT_TRUE(send_request(1, req, &response));
  13567. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13568. response.substr(0, response.find("\r\n")));
  13569. }
  13570. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13571. auto handled = false;
  13572. Server svr;
  13573. svr.Post("/test", [&](const Request &, Response &res) {
  13574. handled = true;
  13575. res.set_content("ok", "text/plain");
  13576. });
  13577. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. ASSERT_FALSE(svr.is_running());
  13582. ASSERT_TRUE(handled);
  13583. });
  13584. svr.wait_until_ready();
  13585. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13586. auto req = "POST /test HTTP/1.1\r\n"
  13587. "Content-Length: 5\r\n"
  13588. "Content-Length: 5\r\n"
  13589. "\r\n"
  13590. "hello";
  13591. std::string response;
  13592. ASSERT_TRUE(send_request(1, req, &response));
  13593. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13594. }
  13595. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13596. Server svr;
  13597. svr.Get("/", [](const Request &req, Response &res) {
  13598. EXPECT_EQ(2U, req.trailers.size());
  13599. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13600. // Denied
  13601. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13602. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13603. // Accepted
  13604. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13605. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13606. EXPECT_TRUE(req.has_trailer("X-World"));
  13607. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13608. res.set_content("ok", "text/plain");
  13609. });
  13610. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13611. auto se = detail::scope_exit([&] {
  13612. svr.stop();
  13613. t.join();
  13614. ASSERT_FALSE(svr.is_running());
  13615. });
  13616. svr.wait_until_ready();
  13617. const std::string req = "GET / HTTP/1.1\r\n"
  13618. "Transfer-Encoding: chunked\r\n"
  13619. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13620. "\r\n"
  13621. "0\r\n"
  13622. "Content-Length: 10\r\n"
  13623. "Host: internal.local\r\n"
  13624. "Content-Type: malicious/content\r\n"
  13625. "Cookie: any\r\n"
  13626. "Set-Cookie: any\r\n"
  13627. "X-Forwarded-For: attacker.com\r\n"
  13628. "X-Real-Ip: 1.1.1.1\r\n"
  13629. "X-Hello: hello\r\n"
  13630. "X-World: world\r\n"
  13631. "\r\n";
  13632. std::string res;
  13633. ASSERT_TRUE(send_request(1, req, &res));
  13634. }
  13635. // A direct client that is not listed in trusted_proxies must not be able to
  13636. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13637. // the peer address on the actual TCP connection determines whether the
  13638. // header is honored.
  13639. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13640. Server svr;
  13641. // Deliberately does NOT include the loopback address the test client
  13642. // actually connects from, so the direct connection is not a trusted proxy.
  13643. svr.set_trusted_proxies({"203.0.113.66"});
  13644. std::string observed_remote_addr;
  13645. svr.Get("/ip", [&](const Request &req, Response &res) {
  13646. observed_remote_addr = req.remote_addr;
  13647. res.set_content("ok", "text/plain");
  13648. });
  13649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13650. auto se = detail::scope_exit([&] {
  13651. svr.stop();
  13652. t.join();
  13653. ASSERT_FALSE(svr.is_running());
  13654. });
  13655. svr.wait_until_ready();
  13656. Client cli(HOST, PORT);
  13657. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. EXPECT_EQ(StatusCode::OK_200, res->status);
  13660. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13661. // ignored entirely and the real connection-level address retained.
  13662. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13663. observed_remote_addr == "127.0.0.1");
  13664. }
  13665. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13666. Server svr;
  13667. std::string observed_remote_addr;
  13668. std::string observed_xff;
  13669. svr.Get("/ip", [&](const Request &req, Response &res) {
  13670. observed_remote_addr = req.remote_addr;
  13671. observed_xff = req.get_header_value("X-Forwarded-For");
  13672. res.set_content("ok", "text/plain");
  13673. });
  13674. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13675. auto se = detail::scope_exit([&] {
  13676. svr.stop();
  13677. t.join();
  13678. ASSERT_FALSE(svr.is_running());
  13679. });
  13680. svr.wait_until_ready();
  13681. Client cli(HOST, PORT);
  13682. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13684. EXPECT_EQ(StatusCode::OK_200, res->status);
  13685. EXPECT_EQ(observed_xff, "203.0.113.66");
  13686. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13687. observed_remote_addr == "127.0.0.1");
  13688. }
  13689. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13690. Server svr;
  13691. svr.set_trusted_proxies({"203.0.113.66"});
  13692. std::string observed_remote_addr;
  13693. std::string observed_xff;
  13694. svr.Get("/ip", [&](const Request &req, Response &res) {
  13695. observed_remote_addr = req.remote_addr;
  13696. observed_xff = req.get_header_value("X-Forwarded-For");
  13697. res.set_content("ok", "text/plain");
  13698. });
  13699. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13700. auto se = detail::scope_exit([&] {
  13701. svr.stop();
  13702. t.join();
  13703. ASSERT_FALSE(svr.is_running());
  13704. });
  13705. svr.wait_until_ready();
  13706. Client cli(HOST, PORT);
  13707. auto res = cli.Get("/ip");
  13708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13709. EXPECT_EQ(StatusCode::OK_200, res->status);
  13710. EXPECT_EQ(observed_xff, "");
  13711. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13712. observed_remote_addr == "127.0.0.1");
  13713. }
  13714. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13715. Server svr;
  13716. // Include the loopback address the test client actually connects from, so
  13717. // the direct connection itself is recognized as the trusted proxy hop.
  13718. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13719. std::string observed_remote_addr;
  13720. std::string observed_xff;
  13721. svr.Get("/ip", [&](const Request &req, Response &res) {
  13722. observed_remote_addr = req.remote_addr;
  13723. observed_xff = req.get_header_value("X-Forwarded-For");
  13724. res.set_content("ok", "text/plain");
  13725. });
  13726. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. t.join();
  13730. ASSERT_FALSE(svr.is_running());
  13731. });
  13732. svr.wait_until_ready();
  13733. Client cli(HOST, PORT);
  13734. auto res = cli.Get(
  13735. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13737. EXPECT_EQ(StatusCode::OK_200, res->status);
  13738. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13739. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13740. }
  13741. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13742. Server svr;
  13743. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13744. std::string observed_remote_addr;
  13745. std::string observed_xff;
  13746. svr.Get("/ip", [&](const Request &req, Response &res) {
  13747. observed_remote_addr = req.remote_addr;
  13748. observed_xff = req.get_header_value("X-Forwarded-For");
  13749. res.set_content("ok", "text/plain");
  13750. });
  13751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13752. auto se = detail::scope_exit([&] {
  13753. svr.stop();
  13754. t.join();
  13755. ASSERT_FALSE(svr.is_running());
  13756. });
  13757. svr.wait_until_ready();
  13758. Client cli(HOST, PORT);
  13759. auto res = cli.Get(
  13760. "/ip",
  13761. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13763. EXPECT_EQ(StatusCode::OK_200, res->status);
  13764. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13765. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13766. }
  13767. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13768. Server svr;
  13769. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13770. std::string observed_remote_addr;
  13771. std::string observed_xff;
  13772. svr.Get("/ip", [&](const Request &req, Response &res) {
  13773. observed_remote_addr = req.remote_addr;
  13774. observed_xff = req.get_header_value("X-Forwarded-For");
  13775. res.set_content("ok", "text/plain");
  13776. });
  13777. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13778. auto se = detail::scope_exit([&] {
  13779. svr.stop();
  13780. t.join();
  13781. ASSERT_FALSE(svr.is_running());
  13782. });
  13783. svr.wait_until_ready();
  13784. Client cli(HOST, PORT);
  13785. auto res = cli.Get(
  13786. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13788. EXPECT_EQ(StatusCode::OK_200, res->status);
  13789. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13790. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13791. // and must not be selected.
  13792. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13793. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13794. }
  13795. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13796. Server svr;
  13797. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13798. std::string observed_remote_addr;
  13799. svr.Get("/ip", [&](const Request &req, Response &res) {
  13800. observed_remote_addr = req.remote_addr;
  13801. res.set_content("ok", "text/plain");
  13802. });
  13803. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13804. auto se = detail::scope_exit([&] {
  13805. svr.stop();
  13806. t.join();
  13807. ASSERT_FALSE(svr.is_running());
  13808. });
  13809. svr.wait_until_ready();
  13810. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13811. // a forged address and the trusted proxy's own address; the forged value must
  13812. // not win over the address the trusted proxy actually recorded.
  13813. Client cli(HOST, PORT);
  13814. auto res = cli.Get(
  13815. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13817. EXPECT_EQ(StatusCode::OK_200, res->status);
  13818. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13819. }
  13820. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13821. Server svr;
  13822. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13823. std::string observed_remote_addr;
  13824. std::string observed_xff;
  13825. svr.Get("/ip", [&](const Request &req, Response &res) {
  13826. observed_remote_addr = req.remote_addr;
  13827. observed_xff = req.get_header_value("X-Forwarded-For");
  13828. res.set_content("ok", "text/plain");
  13829. });
  13830. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13831. auto se = detail::scope_exit([&] {
  13832. svr.stop();
  13833. t.join();
  13834. ASSERT_FALSE(svr.is_running());
  13835. });
  13836. svr.wait_until_ready();
  13837. Client cli(HOST, PORT);
  13838. auto res = cli.Get(
  13839. "/ip",
  13840. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13842. EXPECT_EQ(StatusCode::OK_200, res->status);
  13843. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13844. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13845. }
  13846. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13847. Server svr;
  13848. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13849. std::string observed_remote_addr;
  13850. std::string observed_xff;
  13851. svr.Get("/ip", [&](const Request &req, Response &res) {
  13852. observed_remote_addr = req.remote_addr;
  13853. observed_xff = req.get_header_value("X-Forwarded-For");
  13854. res.set_content("ok", "text/plain");
  13855. });
  13856. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13857. auto se = detail::scope_exit([&] {
  13858. svr.stop();
  13859. t.join();
  13860. ASSERT_FALSE(svr.is_running());
  13861. });
  13862. svr.wait_until_ready();
  13863. std::string raw_req =
  13864. "GET /ip HTTP/1.1\r\n"
  13865. "Host: localhost\r\n"
  13866. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13867. "Connection: close\r\n"
  13868. "\r\n";
  13869. std::string out;
  13870. ASSERT_TRUE(send_request(5, raw_req, &out));
  13871. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13872. // Header parser trims surrounding whitespace of the header value
  13873. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13874. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13875. }
  13876. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13877. // crash the server (it used to call front() on an empty vector inside
  13878. // get_client_ip). The connection-level remote address must be retained instead.
  13879. static void run_malformed_xff_test(const std::string &xff_value) {
  13880. Server svr;
  13881. svr.set_trusted_proxies({"192.0.2.45"});
  13882. std::string observed_remote_addr;
  13883. svr.Get("/ip", [&](const Request &req, Response &res) {
  13884. observed_remote_addr = req.remote_addr;
  13885. res.set_content("ok", "text/plain");
  13886. });
  13887. int port = 0;
  13888. thread t = thread([&]() {
  13889. port = svr.bind_to_any_port(HOST);
  13890. svr.listen_after_bind();
  13891. });
  13892. auto se = detail::scope_exit([&] {
  13893. svr.stop();
  13894. t.join();
  13895. ASSERT_FALSE(svr.is_running());
  13896. });
  13897. svr.wait_until_ready();
  13898. Client cli(HOST, port);
  13899. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13901. EXPECT_EQ(StatusCode::OK_200, res->status);
  13902. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13903. observed_remote_addr == "127.0.0.1");
  13904. }
  13905. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13906. run_malformed_xff_test("");
  13907. }
  13908. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13909. run_malformed_xff_test(",");
  13910. }
  13911. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13912. run_malformed_xff_test(", , ,");
  13913. }
  13914. #ifndef _WIN32
  13915. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13916. Server svr;
  13917. svr.Post("/post", [&](const Request &req, Response &res) {
  13918. res.set_content(req.body, "text/plain");
  13919. });
  13920. svr.Put("/put", [&](const Request &req, Response &res) {
  13921. res.set_content(req.body, "text/plain");
  13922. });
  13923. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13924. res.set_content(req.body, "text/plain");
  13925. });
  13926. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13927. res.set_content(req.body, "text/plain");
  13928. });
  13929. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13930. auto se = detail::scope_exit([&] {
  13931. svr.stop();
  13932. t.join();
  13933. ASSERT_FALSE(svr.is_running());
  13934. });
  13935. svr.wait_until_ready();
  13936. std::string resp;
  13937. // POST without Content-Length
  13938. ASSERT_TRUE(send_request(5,
  13939. "POST /post HTTP/1.1\r\n"
  13940. "Host: localhost\r\n"
  13941. "Connection: close\r\n"
  13942. "\r\n",
  13943. &resp));
  13944. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13945. // PUT without Content-Length
  13946. resp.clear();
  13947. ASSERT_TRUE(send_request(5,
  13948. "PUT /put HTTP/1.1\r\n"
  13949. "Host: localhost\r\n"
  13950. "Connection: close\r\n"
  13951. "\r\n",
  13952. &resp));
  13953. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13954. // PATCH without Content-Length
  13955. resp.clear();
  13956. ASSERT_TRUE(send_request(5,
  13957. "PATCH /patch HTTP/1.1\r\n"
  13958. "Host: localhost\r\n"
  13959. "Connection: close\r\n"
  13960. "\r\n",
  13961. &resp));
  13962. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13963. // DELETE without Content-Length
  13964. resp.clear();
  13965. ASSERT_TRUE(send_request(5,
  13966. "DELETE /delete HTTP/1.1\r\n"
  13967. "Host: localhost\r\n"
  13968. "Connection: close\r\n"
  13969. "\r\n",
  13970. &resp));
  13971. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13972. }
  13973. #endif
  13974. //==============================================================================
  13975. // open_stream() Tests
  13976. //==============================================================================
  13977. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13978. std::string result;
  13979. char buf[8192];
  13980. ssize_t n;
  13981. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13982. result.append(buf, static_cast<size_t>(n));
  13983. }
  13984. return result;
  13985. }
  13986. // Mock stream for unit tests
  13987. class MockStream : public Stream {
  13988. public:
  13989. std::string data;
  13990. size_t pos = 0;
  13991. ssize_t error_after = -1; // -1 = no error
  13992. explicit MockStream(const std::string &d, ssize_t err = -1)
  13993. : data(d), error_after(err) {}
  13994. bool is_readable() const override { return true; }
  13995. bool wait_readable() const override { return true; }
  13996. bool wait_writable() const override { return true; }
  13997. ssize_t read(char *ptr, size_t size) override {
  13998. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13999. if (pos >= data.size()) return 0;
  14000. size_t limit =
  14001. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14002. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14003. std::memcpy(ptr, data.data() + pos, to_read);
  14004. pos += to_read;
  14005. return static_cast<ssize_t>(to_read);
  14006. }
  14007. ssize_t write(const char *, size_t) override { return -1; }
  14008. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14009. ip = "127.0.0.1";
  14010. port = 0;
  14011. }
  14012. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14013. ip = "127.0.0.1";
  14014. port = 0;
  14015. }
  14016. socket_t socket() const override { return INVALID_SOCKET; }
  14017. time_t duration() const override { return 0; }
  14018. };
  14019. TEST(StreamHandleTest, Basic) {
  14020. ClientImpl::StreamHandle handle;
  14021. EXPECT_FALSE(handle.is_valid());
  14022. handle.response = detail::make_unique<Response>();
  14023. handle.error = Error::Connection;
  14024. EXPECT_FALSE(handle.is_valid());
  14025. handle.error = Error::Success;
  14026. EXPECT_TRUE(handle.is_valid());
  14027. }
  14028. TEST(BodyReaderTest, Basic) {
  14029. MockStream stream("Hello, World!");
  14030. detail::BodyReader reader;
  14031. reader.stream = &stream;
  14032. reader.content_length = 13;
  14033. char buf[32];
  14034. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14035. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14036. EXPECT_TRUE(reader.eof);
  14037. }
  14038. TEST(BodyReaderTest, NoStream) {
  14039. detail::BodyReader reader;
  14040. char buf[32];
  14041. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14042. EXPECT_EQ(Error::Connection, reader.last_error);
  14043. }
  14044. TEST(BodyReaderTest, Error) {
  14045. MockStream stream("Hello, World!", 5);
  14046. detail::BodyReader reader;
  14047. reader.stream = &stream;
  14048. reader.content_length = 13;
  14049. char buf[32];
  14050. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14051. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14052. EXPECT_EQ(Error::Read, reader.last_error);
  14053. }
  14054. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14055. // Mock-based StreamHandle tests relying on private internals are removed.
  14056. class OpenStreamTest : public ::testing::Test {
  14057. protected:
  14058. void SetUp() override {
  14059. svr_.Get("/hello", [](const Request &, Response &res) {
  14060. res.set_content("Hello World!", "text/plain");
  14061. });
  14062. svr_.Get("/large", [](const Request &, Response &res) {
  14063. res.set_content(std::string(10000, 'X'), "text/plain");
  14064. });
  14065. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14066. res.set_content("Hello World!", "image/jpeg");
  14067. res.set_header("Content-Encoding", "UTF-8");
  14068. });
  14069. svr_.Get("/chunked", [](const Request &, Response &res) {
  14070. res.set_chunked_content_provider("text/plain",
  14071. [](size_t offset, DataSink &sink) {
  14072. if (offset < 15) {
  14073. sink.write("chunk", 5);
  14074. return true;
  14075. }
  14076. sink.done();
  14077. return true;
  14078. });
  14079. });
  14080. svr_.Get("/compressible", [](const Request &, Response &res) {
  14081. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14082. DataSink &sink) {
  14083. if (offset < 100 * 1024) {
  14084. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14085. sink.write(chunk.data(), chunk.size());
  14086. return true;
  14087. }
  14088. sink.done();
  14089. return true;
  14090. });
  14091. });
  14092. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14093. [](const Request & /*req*/, Response &res) {
  14094. auto i = new int(0);
  14095. res.set_header("Trailer", "Content-Length, X-Allowed");
  14096. res.set_chunked_content_provider(
  14097. "text/plain",
  14098. [i](size_t /*offset*/, DataSink &sink) {
  14099. switch (*i) {
  14100. case 0: sink.os << "123"; break;
  14101. case 1: sink.os << "456"; break;
  14102. case 2: sink.os << "789"; break;
  14103. case 3: {
  14104. sink.done_with_trailer(
  14105. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14106. } break;
  14107. }
  14108. (*i)++;
  14109. return true;
  14110. },
  14111. [i](bool success) {
  14112. EXPECT_TRUE(success);
  14113. delete i;
  14114. });
  14115. });
  14116. // Echo headers endpoint for header-related tests
  14117. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14118. std::string body;
  14119. for (const auto &h : req.headers) {
  14120. body.append(h.first);
  14121. body.push_back(':');
  14122. body.append(h.second);
  14123. body.push_back('\n');
  14124. }
  14125. res.set_content(body, "text/plain");
  14126. });
  14127. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14128. std::string body;
  14129. for (const auto &h : req.headers) {
  14130. body.append(h.first);
  14131. body.push_back(':');
  14132. body.append(h.second);
  14133. body.push_back('\n');
  14134. }
  14135. res.set_content(body, "text/plain");
  14136. });
  14137. port_ = svr_.bind_to_any_port("127.0.0.1");
  14138. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14139. svr_.wait_until_ready();
  14140. }
  14141. void TearDown() override {
  14142. svr_.stop();
  14143. if (thread_.joinable()) thread_.join();
  14144. }
  14145. Server svr_;
  14146. std::thread thread_;
  14147. int port_ = 0;
  14148. };
  14149. TEST_F(OpenStreamTest, Basic) {
  14150. Client cli("127.0.0.1", port_);
  14151. auto handle = cli.open_stream("GET", "/hello");
  14152. EXPECT_TRUE(handle.is_valid());
  14153. EXPECT_EQ("Hello World!", read_all(handle));
  14154. }
  14155. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14156. Client cli("127.0.0.1", port_);
  14157. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14158. ASSERT_TRUE(handle.is_valid());
  14159. EXPECT_EQ("Hello World!", read_all(handle));
  14160. }
  14161. TEST_F(OpenStreamTest, SmallBuffer) {
  14162. Client cli("127.0.0.1", port_);
  14163. auto handle = cli.open_stream("GET", "/hello");
  14164. std::string result;
  14165. char buf[4];
  14166. ssize_t n;
  14167. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14168. result.append(buf, static_cast<size_t>(n));
  14169. EXPECT_EQ("Hello World!", result);
  14170. }
  14171. TEST_F(OpenStreamTest, DefaultHeaders) {
  14172. Client cli("127.0.0.1", port_);
  14173. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14174. {
  14175. auto handle = cli.open_stream("GET", "/echo-headers");
  14176. ASSERT_TRUE(handle.is_valid());
  14177. auto body = read_all(handle);
  14178. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14179. std::string::npos);
  14180. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14181. std::string::npos);
  14182. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14183. }
  14184. // open_stream POST with body and no explicit content_type should NOT add
  14185. // text/plain Content-Type (behavior differs from non-streaming path), but
  14186. // should include Content-Length
  14187. {
  14188. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14189. ASSERT_TRUE(handle.is_valid());
  14190. auto body = read_all(handle);
  14191. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14192. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14193. }
  14194. // open_stream POST with explicit Content-Type should preserve it
  14195. {
  14196. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14197. {{"Content-Type", "application/custom"}},
  14198. "{}", "application/custom");
  14199. ASSERT_TRUE(handle.is_valid());
  14200. auto body = read_all(handle);
  14201. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14202. }
  14203. // User-specified User-Agent must not be overwritten for stream API
  14204. {
  14205. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14206. {{"User-Agent", "MyAgent/1.2"}});
  14207. ASSERT_TRUE(handle.is_valid());
  14208. auto body = read_all(handle);
  14209. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14210. }
  14211. }
  14212. TEST_F(OpenStreamTest, Large) {
  14213. Client cli("127.0.0.1", port_);
  14214. auto handle = cli.open_stream("GET", "/large");
  14215. EXPECT_EQ(10000u, read_all(handle).size());
  14216. }
  14217. TEST_F(OpenStreamTest, ConnectionError) {
  14218. Client cli("127.0.0.1", 9999);
  14219. auto handle = cli.open_stream("GET", "/hello");
  14220. EXPECT_FALSE(handle.is_valid());
  14221. }
  14222. TEST_F(OpenStreamTest, Chunked) {
  14223. Client cli("127.0.0.1", port_);
  14224. auto handle = cli.open_stream("GET", "/chunked");
  14225. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14226. "Transfer-Encoding") == "chunked");
  14227. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14228. }
  14229. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14230. Client cli("127.0.0.1", port_);
  14231. auto handle =
  14232. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14233. ASSERT_TRUE(handle.is_valid());
  14234. // Consume body to allow trailers to be received/parsed
  14235. auto body = read_all(handle);
  14236. // Explicitly parse trailers (ensure trailers are available for assertion)
  14237. handle.parse_trailers_if_needed();
  14238. EXPECT_EQ(std::string("123456789"), body);
  14239. // The response should include a Trailer header declaring both names
  14240. ASSERT_TRUE(handle.response);
  14241. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14242. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14243. handle.response->get_header_value("Trailer"));
  14244. // Prohibited trailer must not be present
  14245. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14246. // Allowed trailer should be present
  14247. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14248. EXPECT_EQ(std::string("yes"),
  14249. handle.response->get_trailer_value("X-Allowed"));
  14250. // Verify trailers are NOT present as regular headers
  14251. EXPECT_EQ(std::string(""),
  14252. handle.response->get_header_value("Content-Length"));
  14253. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14254. }
  14255. static std::thread serve_single_response(std::promise<int> &port_promise,
  14256. const std::string &response) {
  14257. return std::thread([&port_promise, response] {
  14258. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14259. default_socket_options(srv);
  14260. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14261. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14262. sockaddr_in addr{};
  14263. addr.sin_family = AF_INET;
  14264. addr.sin_port = htons(0); // Let OS assign a free port
  14265. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14266. int opt = 1;
  14267. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14268. #ifdef _WIN32
  14269. reinterpret_cast<const char *>(&opt),
  14270. #else
  14271. &opt,
  14272. #endif
  14273. sizeof(opt));
  14274. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14275. ::listen(srv, 1) != 0) {
  14276. port_promise.set_value(-1);
  14277. detail::close_socket(srv);
  14278. return;
  14279. }
  14280. socklen_t addr_len = sizeof(addr);
  14281. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14282. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14283. sockaddr_in cli_addr{};
  14284. socklen_t cli_len = sizeof(cli_addr);
  14285. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14286. if (cli != INVALID_SOCKET) {
  14287. // Read the complete HTTP request (until the blank line that terminates
  14288. // headers) before sending the response. If the server closes the socket
  14289. // while the client's request data is still unread in the kernel receive
  14290. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14291. // connection on both sides: it discards the client's receive buffer
  14292. // (which already holds our response) and causes any in-progress write on
  14293. // the client to fail with ECONNRESET. Reading all request data first
  14294. // ensures close() emits a graceful FIN.
  14295. {
  14296. char rbuf[256];
  14297. std::string req;
  14298. while (req.find("\r\n\r\n") == std::string::npos) {
  14299. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14300. if (n <= 0) { break; }
  14301. req.append(rbuf, static_cast<size_t>(n));
  14302. }
  14303. }
  14304. ::send(cli,
  14305. #ifdef _WIN32
  14306. static_cast<const char *>(response.c_str()),
  14307. static_cast<int>(response.size()),
  14308. #else
  14309. response.c_str(), response.size(),
  14310. #endif
  14311. 0);
  14312. detail::close_socket(cli);
  14313. }
  14314. detail::close_socket(srv);
  14315. });
  14316. }
  14317. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14318. #ifndef _WIN32
  14319. signal(SIGPIPE, SIG_IGN);
  14320. #endif
  14321. std::promise<int> port_promise;
  14322. auto port_future = port_promise.get_future();
  14323. auto server_thread =
  14324. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14325. "Content-Type: text/plain\r\n"
  14326. "Content-Length: not-a-number\r\n"
  14327. "Connection: close\r\n"
  14328. "\r\n"
  14329. "hello");
  14330. auto port = port_future.get();
  14331. ASSERT_GT(port, 0);
  14332. Client cli("127.0.0.1", port);
  14333. auto handle = cli.open_stream("GET", "/");
  14334. EXPECT_FALSE(handle.is_valid());
  14335. server_thread.join();
  14336. }
  14337. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14338. #ifndef _WIN32
  14339. signal(SIGPIPE, SIG_IGN);
  14340. #endif
  14341. std::promise<int> port_promise;
  14342. auto port_future = port_promise.get_future();
  14343. auto server_thread = serve_single_response(
  14344. port_promise, "HTTP/1.1 200 OK\r\n"
  14345. "Content-Type: text/plain\r\n"
  14346. "Content-Length: 99999999999999999999999999\r\n"
  14347. "Connection: close\r\n"
  14348. "\r\n"
  14349. "hello");
  14350. auto port = port_future.get();
  14351. ASSERT_GT(port, 0);
  14352. // Historically std::stoull would throw std::out_of_range here and crash
  14353. // the process, then parsing silently clamped to a bogus framing length and
  14354. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14355. // so the stream fails to open, matching the not-a-number case above. The
  14356. // process still must NOT terminate.
  14357. Client cli("127.0.0.1", port);
  14358. auto handle = cli.open_stream("GET", "/");
  14359. EXPECT_FALSE(handle.is_valid());
  14360. server_thread.join();
  14361. }
  14362. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14363. TEST_F(OpenStreamTest, Gzip) {
  14364. Client cli("127.0.0.1", port_);
  14365. auto handle = cli.open_stream("GET", "/compressible", {},
  14366. {{"Accept-Encoding", "gzip"}});
  14367. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14368. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14369. }
  14370. #endif
  14371. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14372. TEST_F(OpenStreamTest, Brotli) {
  14373. Client cli("127.0.0.1", port_);
  14374. auto handle =
  14375. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14376. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14377. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14378. }
  14379. #endif
  14380. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14381. TEST_F(OpenStreamTest, Zstd) {
  14382. Client cli("127.0.0.1", port_);
  14383. auto handle = cli.open_stream("GET", "/compressible", {},
  14384. {{"Accept-Encoding", "zstd"}});
  14385. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14386. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14387. }
  14388. #endif
  14389. #ifdef CPPHTTPLIB_SSL_ENABLED
  14390. class SSLOpenStreamTest : public ::testing::Test {
  14391. protected:
  14392. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14393. void SetUp() override {
  14394. svr_.Get("/hello", [](const Request &, Response &res) {
  14395. res.set_content("Hello SSL World!", "text/plain");
  14396. });
  14397. svr_.Get("/chunked", [](const Request &, Response &res) {
  14398. res.set_chunked_content_provider("text/plain",
  14399. [](size_t offset, DataSink &sink) {
  14400. if (offset < 15) {
  14401. sink.write("chunk", 5);
  14402. return true;
  14403. }
  14404. sink.done();
  14405. return true;
  14406. });
  14407. });
  14408. svr_.Post("/echo", [](const Request &req, Response &res) {
  14409. res.set_content(req.body, req.get_header_value("Content-Type"));
  14410. });
  14411. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14412. std::string body = req.body;
  14413. res.set_chunked_content_provider(
  14414. "text/plain", [body](size_t offset, DataSink &sink) {
  14415. if (offset < body.size()) {
  14416. sink.write(body.data() + offset, body.size() - offset);
  14417. }
  14418. sink.done();
  14419. return true;
  14420. });
  14421. });
  14422. port_ = svr_.bind_to_any_port("127.0.0.1");
  14423. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14424. svr_.wait_until_ready();
  14425. }
  14426. void TearDown() override {
  14427. svr_.stop();
  14428. if (thread_.joinable()) thread_.join();
  14429. }
  14430. SSLServer svr_;
  14431. std::thread thread_;
  14432. int port_ = 0;
  14433. };
  14434. TEST_F(SSLOpenStreamTest, Basic) {
  14435. SSLClient cli("127.0.0.1", port_);
  14436. cli.enable_server_certificate_verification(false);
  14437. auto handle = cli.open_stream("GET", "/hello");
  14438. ASSERT_TRUE(handle.is_valid());
  14439. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14440. }
  14441. TEST_F(SSLOpenStreamTest, Chunked) {
  14442. SSLClient cli("127.0.0.1", port_);
  14443. cli.enable_server_certificate_verification(false);
  14444. auto handle = cli.open_stream("GET", "/chunked");
  14445. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14446. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14447. "Transfer-Encoding") == "chunked");
  14448. auto body = read_all(handle);
  14449. EXPECT_EQ("chunkchunkchunk", body);
  14450. }
  14451. TEST_F(SSLOpenStreamTest, Post) {
  14452. SSLClient cli("127.0.0.1", port_);
  14453. cli.enable_server_certificate_verification(false);
  14454. auto handle =
  14455. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14456. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14457. EXPECT_EQ(200, handle.response->status);
  14458. auto body = read_all(handle);
  14459. EXPECT_EQ("Hello SSL POST", body);
  14460. }
  14461. TEST_F(SSLOpenStreamTest, PostChunked) {
  14462. SSLClient cli("127.0.0.1", port_);
  14463. cli.enable_server_certificate_verification(false);
  14464. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14465. "Chunked SSL Data", "text/plain");
  14466. ASSERT_TRUE(handle.is_valid());
  14467. EXPECT_EQ(200, handle.response->status);
  14468. auto body = read_all(handle);
  14469. EXPECT_EQ("Chunked SSL Data", body);
  14470. }
  14471. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14472. // Content-Length is terminated by the server closing the connection. When the
  14473. // SSL peer sends a close_notify after the body, the client must treat it as a
  14474. // clean EOF and return a successful response rather than an error.
  14475. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14477. ASSERT_TRUE(svr.is_valid());
  14478. svr.set_keep_alive_max_count(1);
  14479. const std::string expected_body = "Hello from connection-close response!";
  14480. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14481. res.set_content_provider("text/plain",
  14482. [&](size_t offset, DataSink &sink) -> bool {
  14483. if (offset < expected_body.size()) {
  14484. sink.write(expected_body.data() + offset,
  14485. expected_body.size() - offset);
  14486. }
  14487. sink.done();
  14488. return true;
  14489. });
  14490. });
  14491. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14492. auto se = detail::scope_exit([&] {
  14493. svr.stop();
  14494. listen_thread.join();
  14495. ASSERT_FALSE(svr.is_running());
  14496. });
  14497. svr.wait_until_ready();
  14498. SSLClient cli(HOST, PORT);
  14499. cli.enable_server_certificate_verification(false);
  14500. auto res = cli.Get("/no-content-length");
  14501. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14502. EXPECT_EQ(StatusCode::OK_200, res->status);
  14503. EXPECT_EQ(expected_body, res->body);
  14504. }
  14505. #endif // CPPHTTPLIB_SSL_ENABLED
  14506. //==============================================================================
  14507. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14508. // results for various scenarios.
  14509. //==============================================================================
  14510. TEST(ParityTest, GetVsOpenStream) {
  14511. Server svr;
  14512. const std::string path = "/parity";
  14513. const std::string content = "Parity test content: hello world";
  14514. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14515. res.set_content(content, "text/plain");
  14516. });
  14517. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14518. auto se = detail::scope_exit([&] {
  14519. svr.stop();
  14520. t.join();
  14521. ASSERT_FALSE(svr.is_running());
  14522. });
  14523. svr.wait_until_ready();
  14524. Client cli(HOST, PORT);
  14525. // Non-stream path
  14526. auto r1 = cli.Get(path);
  14527. ASSERT_TRUE(r1);
  14528. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14529. // Stream path
  14530. auto h = cli.open_stream("GET", path);
  14531. ASSERT_TRUE(h.is_valid());
  14532. EXPECT_EQ(r1->body, read_all(h));
  14533. }
  14534. // Helper to compress data with provided compressor type T
  14535. template <typename Compressor>
  14536. static std::string compress_payload_for_parity(const std::string &in) {
  14537. std::string out;
  14538. Compressor compressor;
  14539. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14540. [&](const char *data, size_t n) {
  14541. out.append(data, n);
  14542. return true;
  14543. });
  14544. EXPECT_TRUE(ok);
  14545. return out;
  14546. }
  14547. // Helper function for compression parity tests
  14548. template <typename Compressor>
  14549. static void test_compression_parity(const std::string &original,
  14550. const std::string &path,
  14551. const std::string &encoding) {
  14552. const std::string compressed =
  14553. compress_payload_for_parity<Compressor>(original);
  14554. Server svr;
  14555. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14556. res.set_content(compressed, "application/octet-stream");
  14557. res.set_header("Content-Encoding", encoding);
  14558. });
  14559. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14560. auto se = detail::scope_exit([&] {
  14561. svr.stop();
  14562. t.join();
  14563. ASSERT_FALSE(svr.is_running());
  14564. });
  14565. svr.wait_until_ready();
  14566. Client cli(HOST, PORT);
  14567. // Non-streaming
  14568. {
  14569. auto res = cli.Get(path);
  14570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14571. EXPECT_EQ(StatusCode::OK_200, res->status);
  14572. EXPECT_EQ(original, res->body);
  14573. }
  14574. // Streaming
  14575. {
  14576. auto h = cli.open_stream("GET", path);
  14577. ASSERT_TRUE(h.is_valid());
  14578. EXPECT_EQ(original, read_all(h));
  14579. }
  14580. }
  14581. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14582. TEST(ParityTest, Gzip) {
  14583. test_compression_parity<detail::gzip_compressor>(
  14584. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14585. }
  14586. #endif
  14587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14588. TEST(ParityTest, Brotli) {
  14589. test_compression_parity<detail::brotli_compressor>(
  14590. "Hello, brotli parity test payload", "/parity-br", "br");
  14591. }
  14592. #endif
  14593. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14594. TEST(ParityTest, Zstd) {
  14595. test_compression_parity<detail::zstd_compressor>(
  14596. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14597. }
  14598. #endif
  14599. //==============================================================================
  14600. // New Stream API Tests
  14601. //==============================================================================
  14602. inline std::string read_body(httplib::stream::Result &result) {
  14603. std::string body;
  14604. while (result.next()) {
  14605. body.append(result.data(), result.size());
  14606. }
  14607. return body;
  14608. }
  14609. TEST(ClientConnectionTest, Basic) {
  14610. httplib::ClientConnection conn;
  14611. EXPECT_FALSE(conn.is_open());
  14612. conn.sock = 1;
  14613. EXPECT_TRUE(conn.is_open());
  14614. httplib::ClientConnection conn2(std::move(conn));
  14615. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14616. conn2.sock = INVALID_SOCKET;
  14617. }
  14618. // Unified test server for all stream::* tests
  14619. class StreamApiTest : public ::testing::Test {
  14620. protected:
  14621. void SetUp() override {
  14622. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14623. res.set_content("Hello World!", "text/plain");
  14624. });
  14625. svr_.Get("/echo-params",
  14626. [](const httplib::Request &req, httplib::Response &res) {
  14627. std::string r;
  14628. for (const auto &p : req.params) {
  14629. if (!r.empty()) r += "&";
  14630. r += p.first + "=" + p.second;
  14631. }
  14632. res.set_content(r, "text/plain");
  14633. });
  14634. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14635. res.set_content(req.body, req.get_header_value("Content-Type"));
  14636. });
  14637. svr_.Post("/echo-headers",
  14638. [](const httplib::Request &req, httplib::Response &res) {
  14639. std::string r;
  14640. for (const auto &h : req.headers)
  14641. r += h.first + ": " + h.second + "\n";
  14642. res.set_content(r, "text/plain");
  14643. });
  14644. svr_.Post("/echo-params",
  14645. [](const httplib::Request &req, httplib::Response &res) {
  14646. std::string r = "params:";
  14647. for (const auto &p : req.params)
  14648. r += p.first + "=" + p.second + ";";
  14649. res.set_content(r + " body:" + req.body, "text/plain");
  14650. });
  14651. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14652. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14653. });
  14654. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14655. res.set_content("PUT:" + req.body, "text/plain");
  14656. });
  14657. svr_.Patch("/echo",
  14658. [](const httplib::Request &req, httplib::Response &res) {
  14659. res.set_content("PATCH:" + req.body, "text/plain");
  14660. });
  14661. svr_.Delete(
  14662. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14663. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14664. "text/plain");
  14665. });
  14666. svr_.Get("/head-test",
  14667. [](const httplib::Request &, httplib::Response &res) {
  14668. res.set_content("body for HEAD", "text/plain");
  14669. });
  14670. svr_.Options("/options",
  14671. [](const httplib::Request &, httplib::Response &res) {
  14672. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14673. });
  14674. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14675. svr_.wait_until_ready();
  14676. }
  14677. void TearDown() override {
  14678. svr_.stop();
  14679. if (thread_.joinable()) thread_.join();
  14680. }
  14681. httplib::Server svr_;
  14682. std::thread thread_;
  14683. };
  14684. // stream::Get tests
  14685. TEST_F(StreamApiTest, GetBasic) {
  14686. httplib::Client cli(HOST, PORT);
  14687. auto result = httplib::stream::Get(cli, "/hello");
  14688. ASSERT_TRUE(result.is_valid());
  14689. EXPECT_EQ(200, result.status());
  14690. EXPECT_EQ("Hello World!", read_body(result));
  14691. }
  14692. TEST_F(StreamApiTest, GetWithParams) {
  14693. httplib::Client cli(HOST, PORT);
  14694. httplib::Params params{{"foo", "bar"}};
  14695. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14696. ASSERT_TRUE(result.is_valid());
  14697. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14698. }
  14699. TEST_F(StreamApiTest, GetConnectionError) {
  14700. httplib::Client cli(HOST, 9999);
  14701. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14702. }
  14703. TEST_F(StreamApiTest, Get404) {
  14704. httplib::Client cli(HOST, PORT);
  14705. auto result = httplib::stream::Get(cli, "/nonexistent");
  14706. EXPECT_TRUE(result.is_valid());
  14707. EXPECT_EQ(404, result.status());
  14708. }
  14709. // stream::Post tests
  14710. TEST_F(StreamApiTest, PostBasic) {
  14711. httplib::Client cli(HOST, PORT);
  14712. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14713. "application/json");
  14714. ASSERT_TRUE(result.is_valid());
  14715. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14716. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14717. }
  14718. TEST_F(StreamApiTest, PostWithHeaders) {
  14719. httplib::Client cli(HOST, PORT);
  14720. httplib::Headers headers{{"X-Custom", "value"}};
  14721. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14722. "text/plain");
  14723. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14724. }
  14725. TEST_F(StreamApiTest, PostWithParams) {
  14726. httplib::Client cli(HOST, PORT);
  14727. httplib::Params params{{"k", "v"}};
  14728. auto result =
  14729. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14730. auto body = read_body(result);
  14731. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14732. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14733. }
  14734. TEST_F(StreamApiTest, PostLarge) {
  14735. httplib::Client cli(HOST, PORT);
  14736. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14737. size_t total = 0;
  14738. while (result.next()) {
  14739. total += result.size();
  14740. }
  14741. EXPECT_EQ(100u * 1024u, total);
  14742. }
  14743. // stream::Put/Patch tests
  14744. TEST_F(StreamApiTest, PutAndPatch) {
  14745. httplib::Client cli(HOST, PORT);
  14746. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14747. EXPECT_EQ("PUT:test", read_body(put));
  14748. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14749. EXPECT_EQ("PATCH:test", read_body(patch));
  14750. }
  14751. // stream::Delete tests
  14752. TEST_F(StreamApiTest, Delete) {
  14753. httplib::Client cli(HOST, PORT);
  14754. auto del1 = httplib::stream::Delete(cli, "/resource");
  14755. EXPECT_EQ("Deleted", read_body(del1));
  14756. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14757. EXPECT_EQ("Deleted:data", read_body(del2));
  14758. }
  14759. // stream::Head/Options tests
  14760. TEST_F(StreamApiTest, HeadAndOptions) {
  14761. httplib::Client cli(HOST, PORT);
  14762. auto head = httplib::stream::Head(cli, "/head-test");
  14763. EXPECT_TRUE(head.is_valid());
  14764. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14765. auto opts = httplib::stream::Options(cli, "/options");
  14766. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14767. }
  14768. // SSL stream::* tests
  14769. #ifdef CPPHTTPLIB_SSL_ENABLED
  14770. class SSLStreamApiTest : public ::testing::Test {
  14771. protected:
  14772. void SetUp() override {
  14773. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14774. res.set_content("Hello SSL!", "text/plain");
  14775. });
  14776. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14777. res.set_content(req.body, "text/plain");
  14778. });
  14779. port_ = svr_.bind_to_any_port("127.0.0.1");
  14780. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14781. svr_.wait_until_ready();
  14782. }
  14783. void TearDown() override {
  14784. svr_.stop();
  14785. if (thread_.joinable()) thread_.join();
  14786. }
  14787. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14788. std::thread thread_;
  14789. int port_ = 0;
  14790. };
  14791. TEST_F(SSLStreamApiTest, GetAndPost) {
  14792. httplib::SSLClient cli("127.0.0.1", port_);
  14793. cli.enable_server_certificate_verification(false);
  14794. auto get = httplib::stream::Get(cli, "/hello");
  14795. EXPECT_EQ("Hello SSL!", read_body(get));
  14796. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14797. EXPECT_EQ("test", read_body(post));
  14798. }
  14799. #endif
  14800. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14801. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14802. // BodyReader
  14803. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14804. // Test that read timeout during streaming is detected
  14805. // Use a large content-length response where server delays mid-stream
  14806. Server svr;
  14807. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14808. // Send a large response with delay in the middle
  14809. res.set_content_provider(
  14810. 1000, // content_length
  14811. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14812. if (offset < 100) {
  14813. // Send first 100 bytes immediately
  14814. std::string data(100, 'A');
  14815. sink.write(data.c_str(), data.size());
  14816. return true;
  14817. }
  14818. // Then delay longer than client timeout
  14819. std::this_thread::sleep_for(std::chrono::seconds(3));
  14820. std::string data(900, 'B');
  14821. sink.write(data.c_str(), data.size());
  14822. return true;
  14823. });
  14824. });
  14825. auto port = 8091;
  14826. std::thread t([&]() { svr.listen("localhost", port); });
  14827. svr.wait_until_ready();
  14828. Client cli("localhost", port);
  14829. cli.set_read_timeout(1, 0); // 1 second timeout
  14830. auto handle = cli.open_stream("GET", "/slow-stream");
  14831. ASSERT_TRUE(handle.is_valid());
  14832. char buf[256];
  14833. ssize_t total = 0;
  14834. ssize_t n;
  14835. bool got_error = false;
  14836. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14837. total += n;
  14838. }
  14839. if (n < 0) {
  14840. got_error = true;
  14841. // Should be timeout or read error
  14842. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14843. handle.get_read_error() == Error::Read)
  14844. << "Actual error: " << to_string(handle.get_read_error());
  14845. }
  14846. // Either we got an error, or we got less data than expected
  14847. EXPECT_TRUE(got_error || total < 1000)
  14848. << "Expected timeout but got all " << total << " bytes";
  14849. svr.stop();
  14850. t.join();
  14851. }
  14852. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14853. // Test connection closed detection via BodyReader
  14854. Server svr;
  14855. std::atomic<bool> close_now{false};
  14856. svr.Get("/will-close", [&](const Request &, Response &res) {
  14857. res.set_content_provider(
  14858. 10000, // Large content_length that we won't fully send
  14859. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14860. if (offset < 100) {
  14861. std::string data(100, 'X');
  14862. sink.write(data.c_str(), data.size());
  14863. return true;
  14864. }
  14865. // Wait for signal then abort
  14866. while (!close_now) {
  14867. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14868. }
  14869. return false; // Abort - server will close connection
  14870. });
  14871. });
  14872. auto port = 8092;
  14873. std::thread t([&]() { svr.listen("localhost", port); });
  14874. svr.wait_until_ready();
  14875. Client cli("localhost", port);
  14876. auto handle = cli.open_stream("GET", "/will-close");
  14877. ASSERT_TRUE(handle.is_valid());
  14878. char buf[256];
  14879. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14880. EXPECT_GT(n, 0) << "First read should succeed";
  14881. // Signal server to close
  14882. close_now = true;
  14883. // Keep reading until error or EOF
  14884. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14885. // Keep reading
  14886. }
  14887. // Should get an error since content_length wasn't satisfied
  14888. if (n < 0) {
  14889. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14890. handle.get_read_error() == Error::Read)
  14891. << "Actual error: " << to_string(handle.get_read_error());
  14892. }
  14893. svr.stop();
  14894. t.join();
  14895. }
  14896. #ifdef CPPHTTPLIB_SSL_ENABLED
  14897. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14898. // Test that read timeout during SSL streaming is detected
  14899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14900. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14901. res.set_content_provider(
  14902. 1000, "text/plain",
  14903. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14904. if (offset < 100) {
  14905. std::string data(100, 'A');
  14906. sink.write(data.c_str(), data.size());
  14907. return true;
  14908. }
  14909. std::this_thread::sleep_for(std::chrono::seconds(3));
  14910. std::string data(900, 'B');
  14911. sink.write(data.c_str(), data.size());
  14912. return true;
  14913. });
  14914. });
  14915. auto port = 8093;
  14916. std::thread t([&]() { svr.listen("localhost", port); });
  14917. svr.wait_until_ready();
  14918. SSLClient cli("localhost", port);
  14919. cli.enable_server_certificate_verification(false);
  14920. cli.set_read_timeout(1, 0); // 1 second timeout
  14921. auto handle = cli.open_stream("GET", "/slow-stream");
  14922. ASSERT_TRUE(handle.is_valid());
  14923. char buf[256];
  14924. ssize_t total = 0;
  14925. ssize_t n;
  14926. bool got_error = false;
  14927. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14928. total += n;
  14929. }
  14930. if (n < 0) {
  14931. got_error = true;
  14932. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14933. handle.get_read_error() == Error::Read)
  14934. << "Actual error: " << to_string(handle.get_read_error());
  14935. }
  14936. EXPECT_TRUE(got_error || total < 1000)
  14937. << "Expected timeout but got all " << total << " bytes";
  14938. svr.stop();
  14939. t.join();
  14940. }
  14941. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14942. // Test SSL connection closed detection
  14943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14944. std::atomic<bool> close_now{false};
  14945. svr.Get("/will-close", [&](const Request &, Response &res) {
  14946. res.set_content_provider(
  14947. 10000, "text/plain",
  14948. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14949. if (offset < 100) {
  14950. std::string data(100, 'X');
  14951. sink.write(data.c_str(), data.size());
  14952. return true;
  14953. }
  14954. while (!close_now) {
  14955. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14956. }
  14957. return false;
  14958. });
  14959. });
  14960. auto port = 8094;
  14961. std::thread t([&]() { svr.listen("localhost", port); });
  14962. svr.wait_until_ready();
  14963. SSLClient cli("localhost", port);
  14964. cli.enable_server_certificate_verification(false);
  14965. auto handle = cli.open_stream("GET", "/will-close");
  14966. ASSERT_TRUE(handle.is_valid());
  14967. char buf[256];
  14968. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14969. EXPECT_GT(n, 0);
  14970. // Signal server to close
  14971. close_now = true;
  14972. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14973. // Keep reading
  14974. }
  14975. if (n < 0) {
  14976. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14977. handle.get_read_error() == Error::Read)
  14978. << "Actual error: " << to_string(handle.get_read_error());
  14979. }
  14980. svr.stop();
  14981. t.join();
  14982. }
  14983. #endif
  14984. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14985. using namespace httplib;
  14986. // Create a test file
  14987. const char *fname = "etag_testfile.txt";
  14988. const char *content = "etag-content";
  14989. {
  14990. std::ofstream ofs(fname);
  14991. ofs << content;
  14992. ASSERT_TRUE(ofs.good());
  14993. }
  14994. Server svr;
  14995. svr.set_mount_point("/static", ".");
  14996. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14997. svr.wait_until_ready();
  14998. Client cli(HOST, PORT);
  14999. // First request: should get 200 with ETag header
  15000. auto res1 = cli.Get("/static/etag_testfile.txt");
  15001. ASSERT_TRUE(res1);
  15002. ASSERT_EQ(200, res1->status);
  15003. ASSERT_TRUE(res1->has_header("ETag"));
  15004. std::string etag = res1->get_header_value("ETag");
  15005. EXPECT_FALSE(etag.empty());
  15006. // Verify ETag format: W/"hex-hex"
  15007. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15008. EXPECT_EQ('W', etag[0]);
  15009. EXPECT_EQ('/', etag[1]);
  15010. EXPECT_EQ('"', etag[2]);
  15011. EXPECT_EQ('"', etag.back());
  15012. // Exact match: expect 304 Not Modified
  15013. Headers h2 = {{"If-None-Match", etag}};
  15014. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15015. ASSERT_TRUE(res2);
  15016. EXPECT_EQ(304, res2->status);
  15017. // Wildcard match: expect 304 Not Modified
  15018. Headers h3 = {{"If-None-Match", "*"}};
  15019. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15020. ASSERT_TRUE(res3);
  15021. EXPECT_EQ(304, res3->status);
  15022. // Non-matching ETag: expect 200
  15023. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15024. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15025. ASSERT_TRUE(res4);
  15026. EXPECT_EQ(200, res4->status);
  15027. // Multiple ETags with one matching: expect 304
  15028. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15029. auto res5 = cli.Get("/static/etag_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, StaticFileETagIfNoneMatchStarNotFound) {
  15037. using namespace httplib;
  15038. Server svr;
  15039. svr.set_mount_point("/static", ".");
  15040. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15041. svr.wait_until_ready();
  15042. Client cli(HOST, PORT);
  15043. // Send If-None-Match: * to a non-existent file
  15044. Headers h = {{"If-None-Match", "*"}};
  15045. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15047. EXPECT_EQ(404, res->status);
  15048. svr.stop();
  15049. t.join();
  15050. }
  15051. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15052. using namespace httplib;
  15053. // Create a test file
  15054. const char *fname = "etag_boundary_testfile.txt";
  15055. const char *content = "boundary-test";
  15056. {
  15057. std::ofstream ofs(fname);
  15058. ofs << content;
  15059. ASSERT_TRUE(ofs.good());
  15060. }
  15061. Server svr;
  15062. svr.set_mount_point("/static", ".");
  15063. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15064. svr.wait_until_ready();
  15065. Client cli(HOST, PORT);
  15066. // Get the actual ETag
  15067. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15068. ASSERT_TRUE(res1);
  15069. ASSERT_EQ(200, res1->status);
  15070. ASSERT_TRUE(res1->has_header("ETag"));
  15071. std::string etag = res1->get_header_value("ETag");
  15072. // Test 1: Very long ETag value (longer than actual ETag)
  15073. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15074. Headers h1 = {{"If-None-Match", "W/"
  15075. "\"very-long-etag-value-that-is-much-longer-"
  15076. "than-the-actual-etag-value\""}};
  15077. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15078. ASSERT_TRUE(res2);
  15079. EXPECT_EQ(200, res2->status); // Should not match
  15080. // Test 2: Long string followed by wildcard
  15081. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15082. // string)
  15083. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15084. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15085. ASSERT_TRUE(res3);
  15086. EXPECT_EQ(304, res3->status); // Should match on "*"
  15087. // Test 3: Wildcard followed by long string
  15088. // Should match on "*" immediately and return 304
  15089. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15090. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15091. ASSERT_TRUE(res4);
  15092. EXPECT_EQ(304, res4->status); // Should match on "*"
  15093. // Test 4: Multiple long non-matching values
  15094. // Should NOT match and return 200 (test that all comparisons are safe)
  15095. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15096. "W/\"second-long-non-matching-value\", "
  15097. "W/\"third-long-non-matching-value\""}};
  15098. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15099. ASSERT_TRUE(res5);
  15100. EXPECT_EQ(200, res5->status); // Should not match
  15101. // Test 5: Single character that is not "*" (edge case)
  15102. Headers h5 = {{"If-None-Match", "X"}};
  15103. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15104. ASSERT_TRUE(res6);
  15105. EXPECT_EQ(200, res6->status); // Should not match
  15106. svr.stop();
  15107. t.join();
  15108. std::remove(fname);
  15109. }
  15110. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15111. using namespace httplib;
  15112. // Create a test file
  15113. const char *fname = "ims_testfile.txt";
  15114. const char *content = "if-modified-since-test";
  15115. {
  15116. std::ofstream ofs(fname);
  15117. ofs << content;
  15118. ASSERT_TRUE(ofs.good());
  15119. }
  15120. Server svr;
  15121. svr.set_mount_point("/static", ".");
  15122. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15123. svr.wait_until_ready();
  15124. Client cli(HOST, PORT);
  15125. // First request: should get 200 with Last-Modified header
  15126. auto res1 = cli.Get("/static/ims_testfile.txt");
  15127. ASSERT_TRUE(res1);
  15128. ASSERT_EQ(200, res1->status);
  15129. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15130. std::string last_modified = res1->get_header_value("Last-Modified");
  15131. EXPECT_FALSE(last_modified.empty());
  15132. // If-Modified-Since with same time: expect 304
  15133. Headers h2 = {{"If-Modified-Since", last_modified}};
  15134. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15135. ASSERT_TRUE(res2);
  15136. EXPECT_EQ(304, res2->status);
  15137. // If-Modified-Since with future time: expect 304
  15138. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15139. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15140. ASSERT_TRUE(res3);
  15141. EXPECT_EQ(304, res3->status);
  15142. // If-Modified-Since with past time: expect 200
  15143. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15144. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15145. ASSERT_TRUE(res4);
  15146. EXPECT_EQ(200, res4->status);
  15147. // If-None-Match takes precedence over If-Modified-Since
  15148. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15149. ASSERT_TRUE(res1->has_header("ETag"));
  15150. std::string etag = res1->get_header_value("ETag");
  15151. Headers h5 = {{"If-None-Match", etag},
  15152. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15153. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15154. ASSERT_TRUE(res5);
  15155. EXPECT_EQ(304, res5->status);
  15156. svr.stop();
  15157. t.join();
  15158. std::remove(fname);
  15159. }
  15160. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15161. using namespace httplib;
  15162. Server svr;
  15163. // Endpoint that returns compressible content
  15164. svr.Get("/compressible", [](const Request &, Response &res) {
  15165. // Return a large enough body to trigger compression
  15166. std::string body(1000, 'a');
  15167. res.set_content(body, "text/plain");
  15168. });
  15169. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15170. svr.wait_until_ready();
  15171. Client cli(HOST, PORT);
  15172. // Request with gzip support: should get Vary header when compressed
  15173. cli.set_compress(true);
  15174. auto res1 = cli.Get("/compressible");
  15175. ASSERT_TRUE(res1);
  15176. EXPECT_EQ(200, res1->status);
  15177. // If Content-Encoding is set, Vary should also be set
  15178. if (res1->has_header("Content-Encoding")) {
  15179. EXPECT_TRUE(res1->has_header("Vary"));
  15180. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15181. }
  15182. // Request without Accept-Encoding header: should not have compression
  15183. Headers h_no_compress;
  15184. auto res2 = cli.Get("/compressible", h_no_compress);
  15185. ASSERT_TRUE(res2);
  15186. EXPECT_EQ(200, res2->status);
  15187. // Verify Vary header is present when compression is applied
  15188. // (the exact behavior depends on server configuration)
  15189. svr.stop();
  15190. t.join();
  15191. }
  15192. TEST(ETagTest, IfRangeWithETag) {
  15193. using namespace httplib;
  15194. // Create a test file with known content
  15195. const char *fname = "if_range_testfile.txt";
  15196. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15197. {
  15198. std::ofstream ofs(fname);
  15199. ofs << content;
  15200. ASSERT_TRUE(ofs.good());
  15201. }
  15202. Server svr;
  15203. svr.set_mount_point("/static", ".");
  15204. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15205. svr.wait_until_ready();
  15206. Client cli(HOST, PORT);
  15207. // First request: get ETag
  15208. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15209. ASSERT_TRUE(res1);
  15210. ASSERT_EQ(200, res1->status);
  15211. ASSERT_TRUE(res1->has_header("ETag"));
  15212. std::string etag = res1->get_header_value("ETag");
  15213. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15214. // Since our server generates weak ETags (W/"..."), If-Range with our
  15215. // ETag should NOT result in partial content - it should return full content.
  15216. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15217. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15218. ASSERT_TRUE(res2);
  15219. // Weak ETag in If-Range -> full content (200), not partial (206)
  15220. EXPECT_EQ(200, res2->status);
  15221. EXPECT_EQ(content, res2->body);
  15222. EXPECT_FALSE(res2->has_header("Content-Range"));
  15223. // Range request with non-matching If-Range (ETag): should get 200 (full
  15224. // content)
  15225. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15226. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15227. ASSERT_TRUE(res3);
  15228. EXPECT_EQ(200, res3->status);
  15229. EXPECT_EQ(content, res3->body);
  15230. EXPECT_FALSE(res3->has_header("Content-Range"));
  15231. // Range request with strong ETag (hypothetical - our server doesn't generate
  15232. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15233. // should return full content)
  15234. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15235. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15236. ASSERT_TRUE(res4);
  15237. EXPECT_EQ(200, res4->status);
  15238. EXPECT_EQ(content, res4->body);
  15239. EXPECT_FALSE(res4->has_header("Content-Range"));
  15240. svr.stop();
  15241. t.join();
  15242. std::remove(fname);
  15243. }
  15244. TEST(ETagTest, IfRangeWithDate) {
  15245. using namespace httplib;
  15246. // Create a test file
  15247. const char *fname = "if_range_date_testfile.txt";
  15248. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15249. {
  15250. std::ofstream ofs(fname);
  15251. ofs << content;
  15252. ASSERT_TRUE(ofs.good());
  15253. }
  15254. Server svr;
  15255. svr.set_mount_point("/static", ".");
  15256. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15257. svr.wait_until_ready();
  15258. Client cli(HOST, PORT);
  15259. // First request: get Last-Modified
  15260. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15261. ASSERT_TRUE(res1);
  15262. ASSERT_EQ(200, res1->status);
  15263. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15264. std::string last_modified = res1->get_header_value("Last-Modified");
  15265. // Range request with matching If-Range (date): should get 206
  15266. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15267. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15268. ASSERT_TRUE(res2);
  15269. EXPECT_EQ(206, res2->status);
  15270. EXPECT_EQ("FGHIJ", res2->body);
  15271. // Range request with old If-Range date: should get 200 (full content)
  15272. Headers h3 = {{"Range", "bytes=5-9"},
  15273. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15274. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15275. ASSERT_TRUE(res3);
  15276. EXPECT_EQ(200, res3->status);
  15277. EXPECT_EQ(content, res3->body);
  15278. // Range request with future If-Range date: should get 206
  15279. Headers h4 = {{"Range", "bytes=0-4"},
  15280. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15281. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15282. ASSERT_TRUE(res4);
  15283. EXPECT_EQ(206, res4->status);
  15284. EXPECT_EQ("ABCDE", res4->body);
  15285. svr.stop();
  15286. t.join();
  15287. std::remove(fname);
  15288. }
  15289. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15290. using namespace httplib;
  15291. const char *fname = "etag_malformed.txt";
  15292. const char *content = "malformed-etag";
  15293. {
  15294. std::ofstream ofs(fname);
  15295. ofs << content;
  15296. ASSERT_TRUE(ofs.good());
  15297. }
  15298. Server svr;
  15299. svr.set_mount_point("/static", ".");
  15300. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15301. svr.wait_until_ready();
  15302. Client cli(HOST, PORT);
  15303. // baseline: should get 200 and an ETag
  15304. auto res1 = cli.Get("/static/etag_malformed.txt");
  15305. ASSERT_TRUE(res1);
  15306. ASSERT_EQ(200, res1->status);
  15307. ASSERT_TRUE(res1->has_header("ETag"));
  15308. // Malformed ETag value (missing quotes) should be treated as non-matching
  15309. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15310. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15311. ASSERT_TRUE(res_bad);
  15312. EXPECT_EQ(200, res_bad->status);
  15313. // Whitespace-only header value should be considered invalid / non-matching
  15314. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15315. "Host: localhost\r\n"
  15316. "If-None-Match: \r\n"
  15317. "Connection: close\r\n"
  15318. "\r\n";
  15319. std::string out;
  15320. ASSERT_TRUE(send_request(5, raw_req, &out));
  15321. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15322. svr.stop();
  15323. t.join();
  15324. std::remove(fname);
  15325. }
  15326. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15327. using namespace httplib;
  15328. const char *fname = "ims_invalid_format.txt";
  15329. const char *content = "ims-bad-format";
  15330. {
  15331. std::ofstream ofs(fname);
  15332. ofs << content;
  15333. ASSERT_TRUE(ofs.good());
  15334. }
  15335. Server svr;
  15336. svr.set_mount_point("/static", ".");
  15337. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15338. svr.wait_until_ready();
  15339. Client cli(HOST, PORT);
  15340. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15341. ASSERT_TRUE(res1);
  15342. ASSERT_EQ(200, res1->status);
  15343. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15344. // If-Modified-Since with invalid format should not result in 304
  15345. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15346. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15347. ASSERT_TRUE(res_bad);
  15348. EXPECT_EQ(200, res_bad->status);
  15349. // If-Range with invalid date format should be treated as mismatch -> full
  15350. // content (200)
  15351. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15352. {"If-Range", "invalid-date"}};
  15353. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15354. ASSERT_TRUE(res_ifrange);
  15355. EXPECT_EQ(200, res_ifrange->status);
  15356. svr.stop();
  15357. t.join();
  15358. std::remove(fname);
  15359. }
  15360. TEST(ETagTest, IfRangeWithMalformedETag) {
  15361. using namespace httplib;
  15362. const char *fname = "ifrange_malformed.txt";
  15363. const std::string content = "0123456789";
  15364. {
  15365. std::ofstream ofs(fname);
  15366. ofs << content;
  15367. ASSERT_TRUE(ofs.good());
  15368. }
  15369. Server svr;
  15370. svr.set_mount_point("/static", ".");
  15371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15372. svr.wait_until_ready();
  15373. Client cli(HOST, PORT);
  15374. // First request: get ETag
  15375. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15376. ASSERT_TRUE(res1);
  15377. ASSERT_EQ(200, res1->status);
  15378. ASSERT_TRUE(res1->has_header("ETag"));
  15379. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15380. // full content (200)
  15381. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15382. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15383. ASSERT_TRUE(res2);
  15384. EXPECT_EQ(200, res2->status);
  15385. EXPECT_EQ(content, res2->body);
  15386. svr.stop();
  15387. t.join();
  15388. std::remove(fname);
  15389. }
  15390. TEST(ETagTest, ExtremeLargeDateValues) {
  15391. using namespace httplib;
  15392. const char *fname = "ims_extreme_date.txt";
  15393. const char *content = "ims-extreme-date";
  15394. {
  15395. std::ofstream ofs(fname);
  15396. ofs << content;
  15397. ASSERT_TRUE(ofs.good());
  15398. }
  15399. Server svr;
  15400. svr.set_mount_point("/static", ".");
  15401. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15402. svr.wait_until_ready();
  15403. Client cli(HOST, PORT);
  15404. auto res1 = cli.Get(std::string("/static/") + fname);
  15405. ASSERT_TRUE(res1);
  15406. ASSERT_EQ(200, res1->status);
  15407. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15408. // Extremely large year that may overflow date parsing routines.
  15409. Headers h_large_date = {
  15410. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15411. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15412. ASSERT_TRUE(res_bad);
  15413. // Expect server to treat this as invalid/mismatch and return full content
  15414. EXPECT_EQ(200, res_bad->status);
  15415. // If-Range with extremely large date should be treated as mismatch -> full
  15416. // content (200)
  15417. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15418. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15419. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15420. ASSERT_TRUE(res_ifrange);
  15421. EXPECT_EQ(200, res_ifrange->status);
  15422. svr.stop();
  15423. t.join();
  15424. std::remove(fname);
  15425. }
  15426. TEST(ETagTest, NegativeFileModificationTime) {
  15427. using namespace httplib;
  15428. const char *fname = "ims_negative_mtime.txt";
  15429. const std::string content = "negative-mtime";
  15430. {
  15431. std::ofstream ofs(fname);
  15432. ofs << content;
  15433. ASSERT_TRUE(ofs.good());
  15434. }
  15435. // Try to set file mtime to a negative value. This may fail on some
  15436. // platforms/filesystems; if it fails, the test will still verify server
  15437. // behaves safely by performing a regular conditional request.
  15438. #if defined(__APPLE__) || defined(__linux__)
  15439. bool set_negative = false;
  15440. do {
  15441. struct timeval times[2];
  15442. // access time: now
  15443. times[0].tv_sec = time(nullptr);
  15444. times[0].tv_usec = 0;
  15445. // modification time: negative (e.g., -1)
  15446. times[1].tv_sec = -1;
  15447. times[1].tv_usec = 0;
  15448. if (utimes(fname, times) == 0) { set_negative = true; }
  15449. } while (0);
  15450. #else
  15451. bool set_negative = false;
  15452. #endif
  15453. Server svr;
  15454. svr.set_mount_point("/static", ".");
  15455. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15456. svr.wait_until_ready();
  15457. Client cli(HOST, PORT);
  15458. auto res1 = cli.Get(std::string("/static/") + fname);
  15459. ASSERT_TRUE(res1);
  15460. ASSERT_EQ(200, res1->status);
  15461. bool has_last_modified = res1->has_header("Last-Modified");
  15462. std::string last_modified;
  15463. if (has_last_modified) {
  15464. last_modified = res1->get_header_value("Last-Modified");
  15465. }
  15466. if (set_negative) {
  15467. // If we successfully set a negative mtime, ensure server returns a
  15468. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15469. // with an old date and ensure server handles it without crash.
  15470. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15471. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15472. ASSERT_TRUE(res2);
  15473. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15474. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15475. } else {
  15476. // Could not set negative mtime on this platform; fall back to verifying
  15477. // that normal invalid/malformed dates are treated safely (non-304).
  15478. Headers h_bad_date = {
  15479. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15480. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15481. ASSERT_TRUE(res_bad);
  15482. EXPECT_EQ(200, res_bad->status);
  15483. }
  15484. svr.stop();
  15485. t.join();
  15486. std::remove(fname);
  15487. }
  15488. //==============================================================================
  15489. // SSE Parsing Tests
  15490. //==============================================================================
  15491. class SSEParsingTest : public ::testing::Test {
  15492. protected:
  15493. // Test helper that mimics SSE parsing behavior
  15494. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15495. int &retry_ms) {
  15496. // Blank line signals end of event
  15497. if (line.empty() || line == "\r") { return true; }
  15498. // Lines starting with ':' are comments (ignored)
  15499. if (!line.empty() && line[0] == ':') { return false; }
  15500. // Find the colon separator
  15501. auto colon_pos = line.find(':');
  15502. if (colon_pos == std::string::npos) {
  15503. // Line with no colon is treated as field name with empty value
  15504. return false;
  15505. }
  15506. std::string field = line.substr(0, colon_pos);
  15507. std::string value;
  15508. // Value starts after colon, skip optional single space
  15509. if (colon_pos + 1 < line.size()) {
  15510. size_t value_start = colon_pos + 1;
  15511. if (line[value_start] == ' ') { value_start++; }
  15512. value = line.substr(value_start);
  15513. // Remove trailing \r if present
  15514. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15515. }
  15516. // Handle known fields
  15517. if (field == "event") {
  15518. msg.event = value;
  15519. } else if (field == "data") {
  15520. // Multiple data lines are concatenated with newlines
  15521. if (!msg.data.empty()) { msg.data += "\n"; }
  15522. msg.data += value;
  15523. } else if (field == "id") {
  15524. // Empty id is valid (clears the last event ID)
  15525. msg.id = value;
  15526. } else if (field == "retry") {
  15527. // Parse retry interval in milliseconds
  15528. {
  15529. int v = 0;
  15530. auto res =
  15531. detail::from_chars(value.data(), value.data() + value.size(), v);
  15532. if (res.ec == std::errc{}) { retry_ms = v; }
  15533. }
  15534. }
  15535. // Unknown fields are ignored per SSE spec
  15536. return false;
  15537. }
  15538. };
  15539. // Test: Single-line data
  15540. TEST_F(SSEParsingTest, SingleLineData) {
  15541. sse::SSEMessage msg;
  15542. int retry_ms = 3000;
  15543. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15544. EXPECT_EQ(msg.data, "hello");
  15545. EXPECT_EQ(msg.event, "message");
  15546. // Blank line ends event
  15547. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15548. }
  15549. // Test: Multi-line data
  15550. TEST_F(SSEParsingTest, MultiLineData) {
  15551. sse::SSEMessage msg;
  15552. int retry_ms = 3000;
  15553. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15554. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15555. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15556. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15557. }
  15558. // Test: Custom event types
  15559. TEST_F(SSEParsingTest, CustomEventType) {
  15560. sse::SSEMessage msg;
  15561. int retry_ms = 3000;
  15562. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15563. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15564. EXPECT_EQ(msg.event, "update");
  15565. EXPECT_EQ(msg.data, "payload");
  15566. }
  15567. // Test: Event ID handling
  15568. TEST_F(SSEParsingTest, EventIdHandling) {
  15569. sse::SSEMessage msg;
  15570. int retry_ms = 3000;
  15571. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15572. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15573. EXPECT_EQ(msg.id, "12345");
  15574. }
  15575. // Test: Empty event ID (clears last event ID)
  15576. TEST_F(SSEParsingTest, EmptyEventId) {
  15577. sse::SSEMessage msg;
  15578. msg.id = "previous";
  15579. int retry_ms = 3000;
  15580. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15581. EXPECT_EQ(msg.id, "");
  15582. }
  15583. // Test: Retry field parsing
  15584. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15585. sse::SSEMessage msg;
  15586. int retry_ms = 3000;
  15587. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15588. EXPECT_EQ(retry_ms, 5000);
  15589. }
  15590. // Test: Invalid retry value
  15591. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15592. sse::SSEMessage msg;
  15593. int retry_ms = 3000;
  15594. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15595. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15596. }
  15597. // Test: Comments (lines starting with :)
  15598. TEST_F(SSEParsingTest, CommentsIgnored) {
  15599. sse::SSEMessage msg;
  15600. int retry_ms = 3000;
  15601. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15602. EXPECT_EQ(msg.data, "");
  15603. EXPECT_EQ(msg.event, "message");
  15604. }
  15605. // Test: Colon in value
  15606. TEST_F(SSEParsingTest, ColonInValue) {
  15607. sse::SSEMessage msg;
  15608. int retry_ms = 3000;
  15609. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15610. EXPECT_EQ(msg.data, "hello:world:test");
  15611. }
  15612. // Test: Line with no colon (field name only)
  15613. TEST_F(SSEParsingTest, FieldNameOnly) {
  15614. sse::SSEMessage msg;
  15615. int retry_ms = 3000;
  15616. // According to SSE spec, this is treated as field name with empty value
  15617. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15618. // Since we don't recognize "data" without colon, data should be empty
  15619. EXPECT_EQ(msg.data, "");
  15620. }
  15621. // Test: Trailing \r handling
  15622. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15623. sse::SSEMessage msg;
  15624. int retry_ms = 3000;
  15625. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15626. EXPECT_EQ(msg.data, "hello");
  15627. }
  15628. // Test: Unknown fields ignored
  15629. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15630. sse::SSEMessage msg;
  15631. int retry_ms = 3000;
  15632. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15633. EXPECT_EQ(msg.data, "");
  15634. EXPECT_EQ(msg.event, "message");
  15635. }
  15636. // Test: Space after colon is optional
  15637. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15638. sse::SSEMessage msg1, msg2;
  15639. int retry_ms = 3000;
  15640. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15641. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15642. EXPECT_EQ(msg1.data, "hello");
  15643. EXPECT_EQ(msg2.data, "hello");
  15644. }
  15645. // Test: SSEMessage clear
  15646. TEST_F(SSEParsingTest, MessageClear) {
  15647. sse::SSEMessage msg;
  15648. msg.event = "custom";
  15649. msg.data = "some data";
  15650. msg.id = "123";
  15651. msg.clear();
  15652. EXPECT_EQ(msg.event, "message");
  15653. EXPECT_EQ(msg.data, "");
  15654. EXPECT_EQ(msg.id, "");
  15655. }
  15656. // Test: Complete event parsing
  15657. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15658. sse::SSEMessage msg;
  15659. int retry_ms = 3000;
  15660. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15661. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15662. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15663. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15664. // Blank line ends event
  15665. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15666. EXPECT_EQ(msg.event, "notification");
  15667. EXPECT_EQ(msg.id, "evt-42");
  15668. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15669. EXPECT_EQ(retry_ms, 1000);
  15670. }
  15671. //==============================================================================
  15672. // Integration Tests with Server
  15673. //==============================================================================
  15674. class SSEIntegrationTest : public ::testing::Test {
  15675. protected:
  15676. void SetUp() override {
  15677. stop_server_.store(false);
  15678. events_.clear();
  15679. server_ = httplib::detail::make_unique<Server>();
  15680. setup_server();
  15681. start_server();
  15682. }
  15683. void TearDown() override {
  15684. stop_server_.store(true);
  15685. event_cv_.notify_all();
  15686. server_->stop();
  15687. if (server_thread_.joinable()) { server_thread_.join(); }
  15688. }
  15689. void setup_server() {
  15690. // Simple SSE endpoint
  15691. server_->Get("/events", [this](const Request &req, Response &res) {
  15692. auto last_id = req.get_header_value("Last-Event-ID");
  15693. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15694. res.set_chunked_content_provider(
  15695. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15696. std::unique_lock<std::mutex> lock(event_mutex_);
  15697. if (event_cv_.wait_for(
  15698. lock, std::chrono::milliseconds(200), [this] {
  15699. return !events_.empty() || stop_server_.load();
  15700. })) {
  15701. if (stop_server_.load()) { return false; }
  15702. if (!events_.empty()) {
  15703. std::string event = events_.front();
  15704. events_.erase(events_.begin());
  15705. sink.write(event.data(), event.size());
  15706. return true;
  15707. }
  15708. }
  15709. return !stop_server_.load();
  15710. });
  15711. });
  15712. // Endpoint that returns error
  15713. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15714. res.status = 500;
  15715. res.set_content("Internal Server Error", "text/plain");
  15716. });
  15717. // Endpoint for custom event types
  15718. server_->Get("/custom-events", [](const Request &, Response &res) {
  15719. res.set_chunked_content_provider(
  15720. "text/event-stream", [](size_t offset, DataSink &sink) {
  15721. if (offset == 0) {
  15722. std::string event = "event: update\ndata: updated\n\n"
  15723. "event: delete\ndata: deleted\n\n";
  15724. sink.write(event.data(), event.size());
  15725. }
  15726. return false; // End stream after sending
  15727. });
  15728. });
  15729. }
  15730. void start_server() {
  15731. port_ = server_->bind_to_any_port(HOST);
  15732. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15733. // Wait for server to start
  15734. while (!server_->is_running()) {
  15735. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15736. }
  15737. }
  15738. int get_port() const { return port_; }
  15739. void send_event(const std::string &event) {
  15740. std::lock_guard<std::mutex> lock(event_mutex_);
  15741. events_.push_back(event);
  15742. event_cv_.notify_all();
  15743. }
  15744. std::unique_ptr<Server> server_;
  15745. std::thread server_thread_;
  15746. std::mutex event_mutex_;
  15747. std::condition_variable event_cv_;
  15748. std::vector<std::string> events_;
  15749. std::atomic<bool> stop_server_{false};
  15750. std::string last_received_event_id_;
  15751. int port_ = 0;
  15752. };
  15753. // Test: Successful connection and on_open callback
  15754. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15755. // Add a simple endpoint that sends one event and closes
  15756. server_->Get("/simple-event", [](const Request &, Response &res) {
  15757. res.set_chunked_content_provider(
  15758. "text/event-stream", [](size_t offset, DataSink &sink) {
  15759. if (offset == 0) {
  15760. std::string event = "data: hello\n\n";
  15761. sink.write(event.data(), event.size());
  15762. }
  15763. return false; // Close stream after sending
  15764. });
  15765. });
  15766. Client client("localhost", get_port());
  15767. sse::SSEClient sse(client, "/simple-event");
  15768. std::atomic<bool> open_called{false};
  15769. std::atomic<bool> message_received{false};
  15770. sse.on_open([&open_called]() { open_called.store(true); });
  15771. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15772. if (msg.data == "hello") { message_received.store(true); }
  15773. });
  15774. sse.set_reconnect_interval(100);
  15775. sse.set_max_reconnect_attempts(1);
  15776. // Start async
  15777. sse.start_async();
  15778. // Wait for message to be processed
  15779. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15780. sse.stop();
  15781. EXPECT_TRUE(open_called.load());
  15782. EXPECT_TRUE(message_received.load());
  15783. }
  15784. // Test: on_message callback
  15785. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15786. // Endpoint that sends multiple events then closes
  15787. server_->Get("/multi-event", [](const Request &, Response &res) {
  15788. res.set_chunked_content_provider(
  15789. "text/event-stream", [](size_t offset, DataSink &sink) {
  15790. if (offset == 0) {
  15791. std::string events = "data: message1\n\ndata: message2\n\n";
  15792. sink.write(events.data(), events.size());
  15793. }
  15794. return false;
  15795. });
  15796. });
  15797. Client client("localhost", get_port());
  15798. sse::SSEClient sse(client, "/multi-event");
  15799. std::vector<std::string> received_messages;
  15800. std::mutex messages_mutex;
  15801. sse.on_message([&](const sse::SSEMessage &msg) {
  15802. std::lock_guard<std::mutex> lock(messages_mutex);
  15803. received_messages.push_back(msg.data);
  15804. });
  15805. sse.set_reconnect_interval(100);
  15806. sse.set_max_reconnect_attempts(1);
  15807. sse.start_async();
  15808. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15809. sse.stop();
  15810. std::lock_guard<std::mutex> lock(messages_mutex);
  15811. EXPECT_GE(received_messages.size(), 2u);
  15812. if (received_messages.size() >= 2) {
  15813. EXPECT_EQ(received_messages[0], "message1");
  15814. EXPECT_EQ(received_messages[1], "message2");
  15815. }
  15816. }
  15817. // Test: on_event for specific types
  15818. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15819. Client client("localhost", get_port());
  15820. sse::SSEClient sse(client, "/custom-events");
  15821. std::atomic<bool> update_received{false};
  15822. std::atomic<bool> delete_received{false};
  15823. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15824. if (msg.data == "updated") { update_received.store(true); }
  15825. });
  15826. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15827. if (msg.data == "deleted") { delete_received.store(true); }
  15828. });
  15829. sse.set_max_reconnect_attempts(1);
  15830. sse.start_async();
  15831. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15832. sse.stop();
  15833. EXPECT_TRUE(update_received.load());
  15834. EXPECT_TRUE(delete_received.load());
  15835. }
  15836. // Test: on_error callback on connection failure
  15837. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15838. // Connect to a non-existent port
  15839. Client client("localhost", 59999);
  15840. sse::SSEClient sse(client, "/events");
  15841. std::atomic<bool> error_called{false};
  15842. Error received_error = Error::Success;
  15843. sse.on_error([&](Error err) {
  15844. error_called.store(true);
  15845. received_error = err;
  15846. });
  15847. sse.set_reconnect_interval(50);
  15848. sse.set_max_reconnect_attempts(1);
  15849. sse.start_async();
  15850. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15851. sse.stop();
  15852. EXPECT_TRUE(error_called.load());
  15853. EXPECT_NE(received_error, Error::Success);
  15854. }
  15855. // Test: Last-Event-ID header sent on reconnect
  15856. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15857. // Endpoint that sends event with ID
  15858. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15859. res.set_chunked_content_provider(
  15860. "text/event-stream", [](size_t offset, DataSink &sink) {
  15861. if (offset == 0) {
  15862. std::string event = "id: evt-123\ndata: test\n\n";
  15863. sink.write(event.data(), event.size());
  15864. }
  15865. return false;
  15866. });
  15867. });
  15868. Client client("localhost", get_port());
  15869. sse::SSEClient sse(client, "/event-with-id");
  15870. std::atomic<bool> id_received{false};
  15871. sse.on_message([&](const sse::SSEMessage &msg) {
  15872. if (!msg.id.empty()) { id_received.store(true); }
  15873. });
  15874. sse.set_reconnect_interval(100);
  15875. sse.set_max_reconnect_attempts(1);
  15876. sse.start_async();
  15877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15878. sse.stop();
  15879. EXPECT_TRUE(id_received.load());
  15880. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15881. }
  15882. // Test: Manual stop
  15883. TEST_F(SSEIntegrationTest, ManualStop) {
  15884. // Endpoint that sends one event and stays open briefly
  15885. std::atomic<bool> handler_running{true};
  15886. server_->Get("/stay-open", [&handler_running](const Request &,
  15887. Response &res) {
  15888. res.set_chunked_content_provider(
  15889. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15890. if (offset == 0) {
  15891. std::string event = "data: connected\n\n";
  15892. sink.write(event.data(), event.size());
  15893. }
  15894. // Keep connection open while handler_running is true
  15895. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15896. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15897. }
  15898. return false;
  15899. });
  15900. });
  15901. Client client("localhost", get_port());
  15902. sse::SSEClient sse(client, "/stay-open");
  15903. std::atomic<bool> connected{false};
  15904. sse.on_open([&connected]() { connected.store(true); });
  15905. sse.set_reconnect_interval(100);
  15906. sse.set_max_reconnect_attempts(1);
  15907. sse.start_async();
  15908. // Wait for connection to establish
  15909. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15910. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15911. }
  15912. EXPECT_TRUE(connected.load());
  15913. EXPECT_TRUE(sse.is_connected());
  15914. // Signal handler to stop
  15915. handler_running.store(false);
  15916. // Stop SSE client
  15917. sse.stop();
  15918. EXPECT_FALSE(sse.is_connected());
  15919. }
  15920. // Test: SSEClient with custom headers
  15921. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15922. // Setup a server endpoint that checks for custom header
  15923. std::atomic<bool> header_received{false};
  15924. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15925. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15926. header_received.store(true);
  15927. }
  15928. res.set_chunked_content_provider("text/event-stream",
  15929. [](size_t, DataSink &) { return false; });
  15930. });
  15931. Client client("localhost", get_port());
  15932. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15933. sse::SSEClient sse(client, "/header-check", headers);
  15934. sse.set_max_reconnect_attempts(1);
  15935. sse.start_async();
  15936. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15937. sse.stop();
  15938. EXPECT_TRUE(header_received.load());
  15939. }
  15940. // Test: Reconnect interval configuration
  15941. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15942. Client client("localhost", get_port());
  15943. sse::SSEClient sse(client, "/events");
  15944. auto &result = sse.set_reconnect_interval(500);
  15945. // Builder pattern should return reference to self
  15946. EXPECT_EQ(&result, &sse);
  15947. }
  15948. // Test: Max reconnect attempts
  15949. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15950. // Connect to non-existent port to force reconnects
  15951. Client client("localhost", 59998);
  15952. sse::SSEClient sse(client, "/events");
  15953. std::atomic<int> error_count{0};
  15954. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15955. sse.set_reconnect_interval(50);
  15956. sse.set_max_reconnect_attempts(2);
  15957. auto start = std::chrono::steady_clock::now();
  15958. sse.start(); // Blocking call
  15959. auto end = std::chrono::steady_clock::now();
  15960. // Should have stopped after 2 failed attempts
  15961. EXPECT_GE(error_count.load(), 2);
  15962. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15963. auto duration =
  15964. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15965. #ifdef _WIN32
  15966. // Windows is much slower for socket connection failures
  15967. EXPECT_LT(duration.count(), 7000);
  15968. #else
  15969. EXPECT_LT(duration.count(), 1000);
  15970. #endif
  15971. }
  15972. // Test: Multi-line data in integration
  15973. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15974. // Endpoint with multi-line data
  15975. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15976. res.set_chunked_content_provider(
  15977. "text/event-stream", [](size_t offset, DataSink &sink) {
  15978. if (offset == 0) {
  15979. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15980. sink.write(event.data(), event.size());
  15981. }
  15982. return false;
  15983. });
  15984. });
  15985. Client client("localhost", get_port());
  15986. sse::SSEClient sse(client, "/multiline-data");
  15987. std::string received_data;
  15988. std::mutex data_mutex;
  15989. sse.on_message([&](const sse::SSEMessage &msg) {
  15990. std::lock_guard<std::mutex> lock(data_mutex);
  15991. received_data = msg.data;
  15992. });
  15993. sse.set_reconnect_interval(100);
  15994. sse.set_max_reconnect_attempts(1);
  15995. sse.start_async();
  15996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15997. sse.stop();
  15998. std::lock_guard<std::mutex> lock(data_mutex);
  15999. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16000. }
  16001. // Test: Auto-reconnect after server disconnection
  16002. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16003. std::atomic<int> connection_count{0};
  16004. std::atomic<int> message_count{0};
  16005. // Endpoint that sends one event and closes, forcing reconnect
  16006. server_->Get("/reconnect-test",
  16007. [&connection_count](const Request &, Response &res) {
  16008. connection_count.fetch_add(1);
  16009. res.set_chunked_content_provider(
  16010. "text/event-stream", [](size_t offset, DataSink &sink) {
  16011. if (offset == 0) {
  16012. std::string event = "data: hello\n\n";
  16013. sink.write(event.data(), event.size());
  16014. }
  16015. return false; // Close connection after sending
  16016. });
  16017. });
  16018. Client client("localhost", get_port());
  16019. sse::SSEClient sse(client, "/reconnect-test");
  16020. sse.on_message([&message_count](const sse::SSEMessage &) {
  16021. message_count.fetch_add(1);
  16022. });
  16023. sse.set_reconnect_interval(100);
  16024. sse.set_max_reconnect_attempts(3);
  16025. sse.start_async();
  16026. // Wait long enough for multiple reconnects
  16027. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16028. sse.stop();
  16029. // Should have connected multiple times (initial + reconnects)
  16030. EXPECT_GE(connection_count.load(), 2);
  16031. // Should have received messages from multiple connections
  16032. EXPECT_GE(message_count.load(), 2);
  16033. }
  16034. // Test: Last-Event-ID sent on reconnect
  16035. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16036. std::atomic<int> connection_count{0};
  16037. std::vector<std::string> received_last_event_ids;
  16038. std::mutex id_mutex;
  16039. // Endpoint that checks Last-Event-ID header and sends event with ID
  16040. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16041. int conn = connection_count.fetch_add(1);
  16042. // Capture the Last-Event-ID header from each connection
  16043. {
  16044. std::lock_guard<std::mutex> lock(id_mutex);
  16045. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16046. }
  16047. res.set_chunked_content_provider(
  16048. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16049. if (offset == 0) {
  16050. std::string event =
  16051. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16052. sink.write(event.data(), event.size());
  16053. }
  16054. return false;
  16055. });
  16056. });
  16057. Client client("localhost", get_port());
  16058. sse::SSEClient sse(client, "/reconnect-with-id");
  16059. sse.set_reconnect_interval(100);
  16060. sse.set_max_reconnect_attempts(3);
  16061. sse.start_async();
  16062. // Wait for at least 2 connections
  16063. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16064. sse.stop();
  16065. // Verify behavior
  16066. std::lock_guard<std::mutex> lock(id_mutex);
  16067. EXPECT_GE(received_last_event_ids.size(), 2u);
  16068. // First connection should have no Last-Event-ID
  16069. if (!received_last_event_ids.empty()) {
  16070. EXPECT_EQ(received_last_event_ids[0], "");
  16071. }
  16072. // Second connection should have Last-Event-ID from first connection
  16073. if (received_last_event_ids.size() >= 2) {
  16074. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16075. }
  16076. }
  16077. // Test: set_headers updates headers used on reconnect
  16078. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16079. std::vector<std::string> received_tokens;
  16080. std::mutex token_mutex;
  16081. // Endpoint that captures Authorization header
  16082. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16083. {
  16084. std::lock_guard<std::mutex> lock(token_mutex);
  16085. received_tokens.push_back(req.get_header_value("Authorization"));
  16086. }
  16087. res.set_chunked_content_provider(
  16088. "text/event-stream", [](size_t offset, DataSink &sink) {
  16089. if (offset == 0) {
  16090. std::string event = "data: hello\n\n";
  16091. sink.write(event.data(), event.size());
  16092. }
  16093. return false; // Close connection to trigger reconnect
  16094. });
  16095. });
  16096. Client client("localhost", get_port());
  16097. Headers headers = {{"Authorization", "Bearer old-token"}};
  16098. sse::SSEClient sse(client, "/auth-check", headers);
  16099. // Update headers on each successful connection
  16100. sse.on_open(
  16101. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16102. sse.set_reconnect_interval(100);
  16103. sse.set_max_reconnect_attempts(3);
  16104. sse.start_async();
  16105. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16106. sse.stop();
  16107. std::lock_guard<std::mutex> lock(token_mutex);
  16108. ASSERT_GE(received_tokens.size(), 2u);
  16109. // First connection uses original header
  16110. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16111. // Second connection uses updated header from set_headers
  16112. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16113. }
  16114. // Test: 401 allows reconnection (so on_error can refresh headers)
  16115. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16116. std::atomic<int> connection_count{0};
  16117. // Endpoint: returns 401 on first attempt, 200 on second
  16118. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16119. int conn = connection_count.fetch_add(1);
  16120. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16121. res.status = StatusCode::Unauthorized_401;
  16122. res.set_content("Unauthorized", "text/plain");
  16123. return;
  16124. }
  16125. res.set_chunked_content_provider(
  16126. "text/event-stream", [](size_t offset, DataSink &sink) {
  16127. if (offset == 0) {
  16128. std::string event = "data: authenticated\n\n";
  16129. sink.write(event.data(), event.size());
  16130. }
  16131. return false;
  16132. });
  16133. });
  16134. Client client("localhost", get_port());
  16135. Headers headers = {{"Authorization", "Bearer expired"}};
  16136. sse::SSEClient sse(client, "/auth-retry", headers);
  16137. std::atomic<bool> message_received{false};
  16138. // Refresh token on error
  16139. sse.on_error(
  16140. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16141. sse.on_message([&](const sse::SSEMessage &msg) {
  16142. if (msg.data == "authenticated") { message_received.store(true); }
  16143. });
  16144. sse.set_reconnect_interval(100);
  16145. sse.set_max_reconnect_attempts(3);
  16146. sse.start_async();
  16147. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16148. sse.stop();
  16149. // Should have reconnected after 401 and succeeded with new token
  16150. EXPECT_GE(connection_count.load(), 2);
  16151. EXPECT_TRUE(message_received.load());
  16152. }
  16153. TEST(Issue2318Test, EmptyHostString) {
  16154. {
  16155. httplib::Client cli_empty("", PORT);
  16156. auto res = cli_empty.Get("/");
  16157. ASSERT_FALSE(res);
  16158. EXPECT_EQ(httplib::Error::Connection, res.error());
  16159. }
  16160. {
  16161. httplib::Client cli(" ", PORT);
  16162. auto res = cli.Get("/");
  16163. ASSERT_FALSE(res);
  16164. EXPECT_EQ(httplib::Error::Connection, res.error());
  16165. }
  16166. }
  16167. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16168. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16169. Server svr;
  16170. // Set a small payload limit (1KB)
  16171. svr.set_payload_max_length(1024);
  16172. svr.Post("/test", [&](const Request &req, Response &res) {
  16173. res.set_content("Body size: " + std::to_string(req.body.size()),
  16174. "text/plain");
  16175. });
  16176. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16177. auto se = detail::scope_exit([&] {
  16178. svr.stop();
  16179. listen_thread.join();
  16180. });
  16181. svr.wait_until_ready();
  16182. // Create data that compresses well but exceeds limit when decompressed
  16183. // 8KB of repeated null bytes compresses to a very small size
  16184. std::string original_data(8 * 1024, '\0');
  16185. // Compress the data using gzip
  16186. std::string compressed_data;
  16187. detail::gzip_compressor compressor;
  16188. compressor.compress(original_data.data(), original_data.size(), true,
  16189. [&](const char *data, size_t size) {
  16190. compressed_data.append(data, size);
  16191. return true;
  16192. });
  16193. // Verify compression worked (compressed should be much smaller)
  16194. ASSERT_LT(compressed_data.size(), original_data.size());
  16195. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16196. // Send compressed data with Content-Encoding: gzip
  16197. Client cli(HOST, PORT);
  16198. Headers headers = {{"Content-Encoding", "gzip"}};
  16199. auto res =
  16200. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16201. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16203. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16204. }
  16205. #endif
  16206. // ============================================================================
  16207. // OpenSSL-Specific Tests
  16208. // ============================================================================
  16209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16210. X509 *readCertificate(const std::string &strFileName) {
  16211. std::ifstream inStream(strFileName);
  16212. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16213. std::istreambuf_iterator<char>());
  16214. if (strCertPEM.empty()) return (nullptr);
  16215. BIO *pbCert = BIO_new(BIO_s_mem());
  16216. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16217. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16218. BIO_free(pbCert);
  16219. return (pCert);
  16220. }
  16221. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16222. std::ifstream inStream(strFileName);
  16223. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16224. std::istreambuf_iterator<char>());
  16225. if (strPrivateKeyPEM.empty()) return (nullptr);
  16226. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16227. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16228. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16229. BIO_free(pbPrivKey);
  16230. return (pPrivateKey);
  16231. }
  16232. TEST(BindServerTest, UpdateCerts) {
  16233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16234. int port = svr.bind_to_any_port("0.0.0.0");
  16235. ASSERT_TRUE(svr.is_valid());
  16236. ASSERT_TRUE(port > 0);
  16237. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16238. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16239. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16240. ASSERT_TRUE(cert != nullptr);
  16241. ASSERT_TRUE(ca_cert != nullptr);
  16242. ASSERT_TRUE(key != nullptr);
  16243. X509_STORE *cert_store = X509_STORE_new();
  16244. X509_STORE_add_cert(cert_store, ca_cert);
  16245. // svr.update_certs(cert, key, cert_store); // deprecated
  16246. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16247. CLIENT_CA_CERT_FILE);
  16248. ASSERT_TRUE(svr.is_valid());
  16249. svr.stop();
  16250. X509_STORE_free(cert_store);
  16251. X509_free(cert);
  16252. X509_free(ca_cert);
  16253. EVP_PKEY_free(key);
  16254. }
  16255. // Test that update_certs() updates client CA list correctly
  16256. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16257. // Start with file-based constructor
  16258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16259. ASSERT_TRUE(svr.is_valid());
  16260. // Initially no client CA list should be set
  16261. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16262. ASSERT_TRUE(ssl_ctx != nullptr);
  16263. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16264. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16265. EXPECT_EQ(0, count_before);
  16266. // Now update with client CA (PEM string)
  16267. std::string cert_pem, key_pem, ca_pem;
  16268. read_file(SERVER_CERT_FILE, cert_pem);
  16269. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16270. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16271. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16272. ASSERT_TRUE(svr.is_valid());
  16273. // Now client CA list should be set
  16274. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16275. ASSERT_TRUE(ca_list_after != nullptr);
  16276. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16277. }
  16278. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16279. // Test that the file-path SSLServer constructor properly sets the client CA
  16280. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16282. ASSERT_TRUE(svr.is_valid());
  16283. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16284. ASSERT_TRUE(ssl_ctx != nullptr);
  16285. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16286. ASSERT_TRUE(ca_list != nullptr);
  16287. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16288. }
  16289. #endif
  16290. // ============================================================================
  16291. // MbedTLS-Specific Tests
  16292. // ============================================================================
  16293. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16294. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16295. using namespace httplib::tls;
  16296. // Track if callback was invoked
  16297. bool callback_invoked = false;
  16298. // The callback receives void* ctx which is actually MbedTlsContext*
  16299. // We can access the mbedtls_ssl_config via the context
  16300. auto setup_callback = [&callback_invoked](void *ctx) {
  16301. callback_invoked = true;
  16302. // Cast to MbedTlsContext* to access the ssl config
  16303. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16304. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16305. // Use static variables to hold certificate data (simplified for test)
  16306. static mbedtls_x509_crt own_cert;
  16307. static mbedtls_pk_context own_key;
  16308. static mbedtls_x509_crt ca_chain;
  16309. static bool initialized = false;
  16310. if (!initialized) {
  16311. mbedtls_x509_crt_init(&own_cert);
  16312. mbedtls_pk_init(&own_key);
  16313. mbedtls_x509_crt_init(&ca_chain);
  16314. // Load server certificate
  16315. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16316. return false;
  16317. }
  16318. // Load server private key.
  16319. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16320. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16321. #if MBEDTLS_VERSION_MAJOR == 3
  16322. ,
  16323. mbedtls_ctr_drbg_random, nullptr
  16324. #endif
  16325. ) != 0) {
  16326. return false;
  16327. }
  16328. // Load CA chain for client verification
  16329. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16330. return false;
  16331. }
  16332. initialized = true;
  16333. }
  16334. // Configure the SSL config
  16335. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16336. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16337. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16338. // Set minimum TLS version using mbedTLS native API
  16339. #if MBEDTLS_VERSION_MAJOR >= 3
  16340. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16341. #else
  16342. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16343. MBEDTLS_SSL_MINOR_VERSION_3);
  16344. #endif
  16345. return true;
  16346. };
  16347. SSLServer svr(setup_callback);
  16348. ASSERT_TRUE(svr.is_valid());
  16349. ASSERT_TRUE(callback_invoked);
  16350. svr.Get("/test", [&](const Request &req, Response &res) {
  16351. res.set_content("test", "text/plain");
  16352. auto cert = req.peer_cert();
  16353. ASSERT_TRUE(static_cast<bool>(cert));
  16354. auto common_name = cert.subject_cn();
  16355. EXPECT_EQ("Common Name", common_name);
  16356. });
  16357. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16358. auto se = detail::scope_exit([&] {
  16359. svr.stop();
  16360. t.join();
  16361. ASSERT_FALSE(svr.is_running());
  16362. });
  16363. svr.wait_until_ready();
  16364. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16365. cli.enable_server_certificate_verification(false);
  16366. cli.set_connection_timeout(30);
  16367. auto res = cli.Get("/test");
  16368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16369. ASSERT_EQ(StatusCode::OK_200, res->status);
  16370. }
  16371. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16372. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16373. // keep-alive SSL session, which reads through that config in
  16374. // mbedtls_ssl_close_notify.
  16375. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16377. ASSERT_TRUE(svr.is_valid());
  16378. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16379. res.set_content("test", "text/plain");
  16380. });
  16381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16382. auto se = detail::scope_exit([&] {
  16383. svr.stop();
  16384. t.join();
  16385. ASSERT_FALSE(svr.is_running());
  16386. });
  16387. svr.wait_until_ready();
  16388. {
  16389. SSLClient cli(HOST, PORT);
  16390. cli.enable_server_certificate_verification(false);
  16391. cli.set_keep_alive(true);
  16392. auto res = cli.Get("/test");
  16393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16394. ASSERT_EQ(StatusCode::OK_200, res->status);
  16395. // cli is destructed here with the keep-alive SSL session still open.
  16396. }
  16397. }
  16398. #endif
  16399. // WebSocket Tests
  16400. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16401. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16402. // defining the meaning of these bits has been negotiated.
  16403. auto make_frame = [](uint8_t first_byte) {
  16404. std::string frame;
  16405. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16406. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16407. frame += "Hello";
  16408. return frame;
  16409. };
  16410. // RSV1 set (0x40)
  16411. {
  16412. detail::BufferStream strm;
  16413. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16414. ws::Opcode opcode;
  16415. std::string payload;
  16416. bool fin;
  16417. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16418. false, 1024));
  16419. }
  16420. // RSV2 set (0x20)
  16421. {
  16422. detail::BufferStream strm;
  16423. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16424. ws::Opcode opcode;
  16425. std::string payload;
  16426. bool fin;
  16427. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16428. false, 1024));
  16429. }
  16430. // RSV3 set (0x10)
  16431. {
  16432. detail::BufferStream strm;
  16433. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16434. ws::Opcode opcode;
  16435. std::string payload;
  16436. bool fin;
  16437. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16438. false, 1024));
  16439. }
  16440. // No RSV bits set - should succeed
  16441. {
  16442. detail::BufferStream strm;
  16443. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16444. ws::Opcode opcode;
  16445. std::string payload;
  16446. bool fin;
  16447. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16448. false, 1024));
  16449. EXPECT_EQ(ws::Opcode::Text, opcode);
  16450. EXPECT_EQ("Hello", payload);
  16451. EXPECT_TRUE(fin);
  16452. }
  16453. }
  16454. TEST(WebSocketTest, ControlFrameValidation) {
  16455. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16456. // payload length <= 125.
  16457. // Ping with FIN=0 - must be rejected
  16458. {
  16459. detail::BufferStream strm;
  16460. std::string frame;
  16461. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16462. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16463. strm.write(frame.data(), frame.size());
  16464. ws::Opcode opcode;
  16465. std::string payload;
  16466. bool fin;
  16467. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16468. false, 1024));
  16469. }
  16470. // Close with FIN=0 - must be rejected
  16471. {
  16472. detail::BufferStream strm;
  16473. std::string frame;
  16474. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16475. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16476. strm.write(frame.data(), frame.size());
  16477. ws::Opcode opcode;
  16478. std::string payload;
  16479. bool fin;
  16480. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16481. false, 1024));
  16482. }
  16483. // Ping with payload_len=126 (extended length) - must be rejected
  16484. {
  16485. detail::BufferStream strm;
  16486. std::string frame;
  16487. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16488. frame += static_cast<char>(126); // payload_len=126 (>125)
  16489. frame += static_cast<char>(0x00); // extended length high byte
  16490. frame += static_cast<char>(126); // extended length low byte
  16491. frame += std::string(126, 'x');
  16492. strm.write(frame.data(), frame.size());
  16493. ws::Opcode opcode;
  16494. std::string payload;
  16495. bool fin;
  16496. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16497. false, 1024));
  16498. }
  16499. // Ping with FIN=1 and payload_len=125 - should succeed
  16500. {
  16501. detail::BufferStream strm;
  16502. std::string frame;
  16503. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16504. frame += static_cast<char>(125); // payload_len=125
  16505. frame += std::string(125, 'x');
  16506. strm.write(frame.data(), frame.size());
  16507. ws::Opcode opcode;
  16508. std::string payload;
  16509. bool fin;
  16510. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16511. false, 1024));
  16512. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16513. EXPECT_EQ(125u, payload.size());
  16514. EXPECT_TRUE(fin);
  16515. }
  16516. }
  16517. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16518. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16519. // length MUST be 0.
  16520. // MSB set - must be rejected
  16521. {
  16522. detail::BufferStream strm;
  16523. std::string frame;
  16524. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16525. frame += static_cast<char>(127); // 64-bit extended length
  16526. frame += static_cast<char>(0x80); // MSB set (invalid)
  16527. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16528. strm.write(frame.data(), frame.size());
  16529. ws::Opcode opcode;
  16530. std::string payload;
  16531. bool fin;
  16532. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16533. false, 1024));
  16534. }
  16535. // MSB clear - should pass length parsing (will be rejected by max_len,
  16536. // but that's a different check; use a small length to verify)
  16537. {
  16538. detail::BufferStream strm;
  16539. std::string frame;
  16540. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16541. frame += static_cast<char>(127); // 64-bit extended length
  16542. frame += std::string(7, '\0'); // high bytes = 0
  16543. frame += static_cast<char>(0x03); // length = 3
  16544. frame += "abc";
  16545. strm.write(frame.data(), frame.size());
  16546. ws::Opcode opcode;
  16547. std::string payload;
  16548. bool fin;
  16549. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16550. false, 1024));
  16551. EXPECT_EQ(ws::Opcode::Text, opcode);
  16552. EXPECT_EQ("abc", payload);
  16553. }
  16554. }
  16555. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16556. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16557. // Valid UTF-8
  16558. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16559. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16560. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16561. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16562. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16563. // Invalid UTF-8
  16564. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16565. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16566. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16567. EXPECT_FALSE(
  16568. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16569. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16570. }
  16571. TEST(WebSocketTest, ConnectAndDisconnect) {
  16572. Server svr;
  16573. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16574. std::string msg;
  16575. while (ws.read(msg)) {}
  16576. });
  16577. auto port = svr.bind_to_any_port(HOST);
  16578. std::thread t([&]() { svr.listen_after_bind(); });
  16579. svr.wait_until_ready();
  16580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16581. ASSERT_TRUE(client.connect());
  16582. EXPECT_TRUE(client.is_open());
  16583. client.close();
  16584. EXPECT_FALSE(client.is_open());
  16585. svr.stop();
  16586. t.join();
  16587. }
  16588. TEST(WebSocketTest, ValidURL) {
  16589. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16590. EXPECT_TRUE(ws1.is_valid());
  16591. ws::WebSocketClient ws2("ws://example.com/path");
  16592. EXPECT_TRUE(ws2.is_valid());
  16593. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16594. EXPECT_TRUE(ws3.is_valid());
  16595. #ifdef CPPHTTPLIB_SSL_ENABLED
  16596. ws::WebSocketClient wss1("wss://example.com/path");
  16597. EXPECT_TRUE(wss1.is_valid());
  16598. ws::WebSocketClient wss2("wss://example.com:443/path");
  16599. EXPECT_TRUE(wss2.is_valid());
  16600. #endif
  16601. }
  16602. TEST(WebSocketTest, InvalidURL) {
  16603. // No scheme
  16604. ws::WebSocketClient ws1("localhost:8080/path");
  16605. EXPECT_FALSE(ws1.is_valid());
  16606. // No path
  16607. ws::WebSocketClient ws2("ws://localhost:8080");
  16608. EXPECT_FALSE(ws2.is_valid());
  16609. // Empty string
  16610. ws::WebSocketClient ws3("");
  16611. EXPECT_FALSE(ws3.is_valid());
  16612. // Missing host
  16613. ws::WebSocketClient ws4("ws://:8080/path");
  16614. EXPECT_FALSE(ws4.is_valid());
  16615. // Port number overflow — should not crash
  16616. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16617. EXPECT_FALSE(ws5.is_valid());
  16618. // Port out of range
  16619. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16620. EXPECT_FALSE(ws6.is_valid());
  16621. }
  16622. TEST(WebSocketTest, UnsupportedScheme) {
  16623. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16624. ws::WebSocketClient ws1("http://localhost:8080/path");
  16625. EXPECT_FALSE(ws1.is_valid());
  16626. ws::WebSocketClient ws2("https://localhost:8080/path");
  16627. EXPECT_FALSE(ws2.is_valid());
  16628. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16629. EXPECT_FALSE(ws3.is_valid());
  16630. #else
  16631. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16632. std::invalid_argument);
  16633. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16634. std::invalid_argument);
  16635. #endif
  16636. }
  16637. TEST(WebSocketTest, ConnectWhenInvalid) {
  16638. ws::WebSocketClient ws("not a valid url");
  16639. EXPECT_FALSE(ws.is_valid());
  16640. EXPECT_FALSE(ws.connect());
  16641. }
  16642. TEST(WebSocketTest, DefaultPort) {
  16643. ws::WebSocketClient ws1("ws://example.com/path");
  16644. EXPECT_TRUE(ws1.is_valid());
  16645. // ws:// defaults to port 80 (verified by successful parse)
  16646. #ifdef CPPHTTPLIB_SSL_ENABLED
  16647. ws::WebSocketClient ws2("wss://example.com/path");
  16648. EXPECT_TRUE(ws2.is_valid());
  16649. // wss:// defaults to port 443 (verified by successful parse)
  16650. #endif
  16651. }
  16652. TEST(WebSocketTest, IPv6LiteralAddress) {
  16653. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16654. EXPECT_TRUE(ws1.is_valid());
  16655. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16656. EXPECT_TRUE(ws2.is_valid());
  16657. }
  16658. TEST(WebSocketTest, ComplexPath) {
  16659. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16660. EXPECT_TRUE(ws1.is_valid());
  16661. ws::WebSocketClient ws2("ws://localhost:8080/");
  16662. EXPECT_TRUE(ws2.is_valid());
  16663. }
  16664. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16665. Server svr;
  16666. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16667. std::string msg;
  16668. while (ws.read(msg)) {}
  16669. });
  16670. auto port = svr.bind_to_any_port(HOST);
  16671. std::thread t([&]() { svr.listen_after_bind(); });
  16672. svr.wait_until_ready();
  16673. auto another_host = "example.com";
  16674. auto wrong_ip = "192.0.2.1";
  16675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16676. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16677. ASSERT_TRUE(client.connect());
  16678. EXPECT_TRUE(client.is_open());
  16679. client.close();
  16680. svr.stop();
  16681. t.join();
  16682. }
  16683. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16684. Server svr;
  16685. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16686. std::string msg;
  16687. while (ws.read(msg)) {}
  16688. });
  16689. auto port = svr.bind_to_any_port(HOST);
  16690. std::thread t([&]() { svr.listen_after_bind(); });
  16691. svr.wait_until_ready();
  16692. auto wrong_ip = "192.0.2.1";
  16693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16694. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16695. client.set_connection_timeout(1);
  16696. client.set_read_timeout(1);
  16697. client.set_write_timeout(1);
  16698. EXPECT_FALSE(client.connect());
  16699. EXPECT_FALSE(client.is_open());
  16700. svr.stop();
  16701. t.join();
  16702. }
  16703. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16704. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16705. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16706. // (RFC 6761) is only a map key and the Host header value.
  16707. auto host = "target.invalid";
  16708. Server svr;
  16709. std::string received_host;
  16710. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16711. received_host = req.get_header_value("Host");
  16712. std::string msg;
  16713. while (ws.read(msg)) {}
  16714. });
  16715. auto port = svr.bind_to_any_port(HOST);
  16716. std::thread t([&]() { svr.listen_after_bind(); });
  16717. // ASSERT_* below returns from the test body, which would leave t joinable
  16718. // and make ~thread call std::terminate.
  16719. auto se = detail::scope_exit([&] {
  16720. svr.stop();
  16721. if (t.joinable()) { t.join(); }
  16722. });
  16723. svr.wait_until_ready();
  16724. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16725. std::to_string(port) + "/ws");
  16726. client.set_hostname_addr_map({{host, HOST}});
  16727. ASSERT_TRUE(client.connect());
  16728. EXPECT_TRUE(client.is_open());
  16729. client.close();
  16730. svr.stop();
  16731. t.join();
  16732. // The mapping only redirects the connection; the identity stays host_.
  16733. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16734. }
  16735. class WebSocketIntegrationTest : public ::testing::Test {
  16736. protected:
  16737. void SetUp() override {
  16738. server_ = httplib::detail::make_unique<Server>();
  16739. setup_server();
  16740. start_server();
  16741. }
  16742. void TearDown() override {
  16743. server_->stop();
  16744. if (server_thread_.joinable()) { server_thread_.join(); }
  16745. }
  16746. void setup_server() {
  16747. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16748. std::string msg;
  16749. ws::ReadResult ret;
  16750. while ((ret = ws.read(msg))) {
  16751. if (ret == ws::Binary) {
  16752. ws.send(msg.data(), msg.size());
  16753. } else {
  16754. ws.send(msg);
  16755. }
  16756. }
  16757. });
  16758. server_->WebSocket("/ws-echo-string",
  16759. [](const Request &, ws::WebSocket &ws) {
  16760. std::string msg;
  16761. while (ws.read(msg)) {
  16762. ws.send("echo: " + msg);
  16763. }
  16764. });
  16765. server_->WebSocket(
  16766. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16767. // Echo back request metadata
  16768. ws.send("path:" + req.path);
  16769. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16770. std::string msg;
  16771. while (ws.read(msg)) {}
  16772. });
  16773. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16774. std::string msg;
  16775. ws.read(msg); // wait for a message
  16776. ws.close();
  16777. });
  16778. server_->WebSocket("/ws-close-status",
  16779. [](const Request &, ws::WebSocket &ws) {
  16780. std::string msg;
  16781. ws.read(msg); // wait for a message
  16782. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16783. });
  16784. server_->WebSocket(
  16785. "/ws-subprotocol",
  16786. [](const Request &, ws::WebSocket &ws) {
  16787. std::string msg;
  16788. while (ws.read(msg)) {
  16789. ws.send(msg);
  16790. }
  16791. },
  16792. [](const std::vector<std::string> &protocols) -> std::string {
  16793. for (const auto &p : protocols) {
  16794. if (p == "graphql-ws") { return p; }
  16795. }
  16796. return "";
  16797. });
  16798. }
  16799. void start_server() {
  16800. port_ = server_->bind_to_any_port(HOST);
  16801. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16802. server_->wait_until_ready();
  16803. }
  16804. std::unique_ptr<Server> server_;
  16805. std::thread server_thread_;
  16806. int port_ = 0;
  16807. };
  16808. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16809. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16810. "/ws-echo");
  16811. ASSERT_TRUE(client.connect());
  16812. ASSERT_TRUE(client.is_open());
  16813. ASSERT_TRUE(client.send("Hello WebSocket"));
  16814. std::string msg;
  16815. EXPECT_EQ(ws::Text, client.read(msg));
  16816. EXPECT_EQ("Hello WebSocket", msg);
  16817. client.close();
  16818. }
  16819. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16820. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16821. "/ws-echo");
  16822. ASSERT_TRUE(client.connect());
  16823. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16824. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16825. std::string msg;
  16826. EXPECT_EQ(ws::Binary, client.read(msg));
  16827. EXPECT_EQ(binary_data, msg);
  16828. client.close();
  16829. }
  16830. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16831. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16832. "/ws-echo");
  16833. ASSERT_TRUE(client.connect());
  16834. for (int i = 0; i < 10; i++) {
  16835. auto text = "message " + std::to_string(i);
  16836. ASSERT_TRUE(client.send(text));
  16837. std::string msg;
  16838. ASSERT_TRUE(client.read(msg));
  16839. EXPECT_EQ(text, msg);
  16840. }
  16841. client.close();
  16842. }
  16843. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16844. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16845. "/ws-close");
  16846. ASSERT_TRUE(client.connect());
  16847. // Send a message to trigger the server to close
  16848. ASSERT_TRUE(client.send("trigger close"));
  16849. // The server will close, so read should return false
  16850. std::string msg;
  16851. EXPECT_FALSE(client.read(msg));
  16852. EXPECT_FALSE(client.is_open());
  16853. }
  16854. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16855. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16856. "/ws-echo");
  16857. ASSERT_TRUE(client.connect());
  16858. // 128KB message
  16859. std::string large_data(128 * 1024, 'X');
  16860. ASSERT_TRUE(client.send(large_data));
  16861. std::string msg;
  16862. ASSERT_TRUE(client.read(msg));
  16863. EXPECT_EQ(large_data, msg);
  16864. client.close();
  16865. }
  16866. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16868. "/ws-echo");
  16869. ASSERT_TRUE(client.connect());
  16870. const int num_threads = 4;
  16871. std::vector<std::thread> threads;
  16872. std::atomic<int> send_count{0};
  16873. for (int t = 0; t < num_threads; t++) {
  16874. threads.emplace_back([&client, &send_count, t]() {
  16875. for (int i = 0; i < 5; i++) {
  16876. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16877. if (client.send(text)) { send_count++; }
  16878. }
  16879. });
  16880. }
  16881. for (auto &th : threads) {
  16882. th.join();
  16883. }
  16884. int received = 0;
  16885. std::string msg;
  16886. while (received < send_count.load()) {
  16887. if (!client.read(msg)) { break; }
  16888. received++;
  16889. }
  16890. EXPECT_EQ(send_count.load(), received);
  16891. client.close();
  16892. }
  16893. TEST_F(WebSocketIntegrationTest, ReadString) {
  16894. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16895. "/ws-echo-string");
  16896. ASSERT_TRUE(client.connect());
  16897. ASSERT_TRUE(client.send("hello"));
  16898. std::string msg;
  16899. ASSERT_TRUE(client.read(msg));
  16900. EXPECT_EQ("echo: hello", msg);
  16901. ASSERT_TRUE(client.send("world"));
  16902. ASSERT_TRUE(client.read(msg));
  16903. EXPECT_EQ("echo: world", msg);
  16904. client.close();
  16905. }
  16906. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16907. Headers headers = {{"X-Test-Header", "test-value"}};
  16908. ws::WebSocketClient client(
  16909. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16910. ASSERT_TRUE(client.connect());
  16911. std::string msg;
  16912. ASSERT_TRUE(client.read(msg));
  16913. EXPECT_EQ("path:/ws-request-info", msg);
  16914. ASSERT_TRUE(client.read(msg));
  16915. EXPECT_EQ("header:test-value", msg);
  16916. client.close();
  16917. }
  16918. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16920. "/ws-echo");
  16921. client.set_read_timeout(1, 0); // 1 second
  16922. ASSERT_TRUE(client.connect());
  16923. // Don't send anything — server echo handler waits for a message,
  16924. // so read() should time out and return false.
  16925. std::string msg;
  16926. EXPECT_FALSE(client.read(msg));
  16927. }
  16928. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16929. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16930. "/ws-echo");
  16931. client.set_read_timeout(5, 0);
  16932. ASSERT_TRUE(client.connect());
  16933. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16934. // The server should reject it and close the connection.
  16935. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16936. client.send(oversized);
  16937. // The server's read() should have failed due to payload limit,
  16938. // so our read() should return false (connection closed).
  16939. std::string msg;
  16940. EXPECT_FALSE(client.read(msg));
  16941. }
  16942. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16944. "/ws-echo");
  16945. client.set_read_timeout(10, 0);
  16946. ASSERT_TRUE(client.connect());
  16947. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16948. // This should succeed.
  16949. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16950. ASSERT_TRUE(client.send(at_limit));
  16951. std::string msg;
  16952. ASSERT_TRUE(client.read(msg));
  16953. EXPECT_EQ(at_limit.size(), msg.size());
  16954. client.close();
  16955. }
  16956. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16958. "/nonexistent");
  16959. EXPECT_FALSE(client.connect());
  16960. EXPECT_FALSE(client.is_open());
  16961. }
  16962. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16963. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16964. "/ws-echo");
  16965. ASSERT_TRUE(client.connect());
  16966. ASSERT_TRUE(client.send(""));
  16967. std::string msg;
  16968. EXPECT_EQ(ws::Text, client.read(msg));
  16969. EXPECT_EQ("", msg);
  16970. client.close();
  16971. }
  16972. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16974. "/ws-echo");
  16975. // First connection
  16976. ASSERT_TRUE(client.connect());
  16977. ASSERT_TRUE(client.send("first"));
  16978. std::string msg;
  16979. ASSERT_TRUE(client.read(msg));
  16980. EXPECT_EQ("first", msg);
  16981. client.close();
  16982. EXPECT_FALSE(client.is_open());
  16983. // Reconnect using the same client object
  16984. ASSERT_TRUE(client.connect());
  16985. ASSERT_TRUE(client.is_open());
  16986. ASSERT_TRUE(client.send("second"));
  16987. ASSERT_TRUE(client.read(msg));
  16988. EXPECT_EQ("second", msg);
  16989. client.close();
  16990. }
  16991. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16992. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16993. "/ws-close-status");
  16994. ASSERT_TRUE(client.connect());
  16995. // Trigger the server to close with GoingAway status
  16996. ASSERT_TRUE(client.send("trigger"));
  16997. // read() should return false after receiving the close frame
  16998. std::string msg;
  16999. EXPECT_FALSE(client.read(msg));
  17000. EXPECT_FALSE(client.is_open());
  17001. }
  17002. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17004. "/ws-echo");
  17005. ASSERT_TRUE(client.connect());
  17006. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17007. EXPECT_FALSE(client.is_open());
  17008. }
  17009. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17010. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17011. ws::WebSocketClient client(
  17012. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17013. ASSERT_TRUE(client.connect());
  17014. // Server should have selected graphql-ws
  17015. EXPECT_EQ("graphql-ws", client.subprotocol());
  17016. client.close();
  17017. }
  17018. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17019. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17020. ws::WebSocketClient client(
  17021. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17022. ASSERT_TRUE(client.connect());
  17023. // Server should not have selected any subprotocol
  17024. EXPECT_TRUE(client.subprotocol().empty());
  17025. client.close();
  17026. }
  17027. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17028. // Connect without requesting any subprotocol
  17029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17030. "/ws-subprotocol");
  17031. ASSERT_TRUE(client.connect());
  17032. EXPECT_TRUE(client.subprotocol().empty());
  17033. client.close();
  17034. }
  17035. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17037. "/ws-echo");
  17038. client.set_tcp_nodelay(true);
  17039. client.set_connection_timeout(3, 0);
  17040. bool socket_options_called = false;
  17041. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17042. ASSERT_TRUE(client.connect());
  17043. ASSERT_TRUE(client.is_open());
  17044. EXPECT_TRUE(socket_options_called);
  17045. ASSERT_TRUE(client.send("hello"));
  17046. std::string msg;
  17047. auto result = client.read(msg);
  17048. EXPECT_EQ(result, ws::ReadResult::Text);
  17049. EXPECT_EQ(msg, "hello");
  17050. client.close();
  17051. }
  17052. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17053. Server svr;
  17054. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17055. if (!req.has_header("Authorization")) {
  17056. res.status = StatusCode::Unauthorized_401;
  17057. res.set_content("Unauthorized", "text/plain");
  17058. return Server::HandlerResponse::Handled;
  17059. }
  17060. return Server::HandlerResponse::Unhandled;
  17061. });
  17062. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17063. std::string msg;
  17064. while (ws.read(msg)) {
  17065. ws.send(msg);
  17066. }
  17067. });
  17068. auto port = svr.bind_to_any_port("localhost");
  17069. std::thread t([&]() { svr.listen_after_bind(); });
  17070. svr.wait_until_ready();
  17071. // Without Authorization header - should be rejected before upgrade
  17072. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17073. EXPECT_FALSE(client1.connect());
  17074. // With Authorization header - should succeed
  17075. Headers headers = {{"Authorization", "Bearer token123"}};
  17076. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17077. headers);
  17078. ASSERT_TRUE(client2.connect());
  17079. ASSERT_TRUE(client2.send("hello"));
  17080. std::string msg;
  17081. ASSERT_TRUE(client2.read(msg));
  17082. EXPECT_EQ("hello", msg);
  17083. client2.close();
  17084. svr.stop();
  17085. t.join();
  17086. }
  17087. TEST(WebSocketTest, QueryStringInHandshake) {
  17088. Server svr;
  17089. std::mutex mtx;
  17090. std::string received_target;
  17091. std::string received_token;
  17092. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17093. {
  17094. std::lock_guard<std::mutex> lock(mtx);
  17095. received_target = req.target;
  17096. if (req.has_param("token")) {
  17097. received_token = req.get_param_value("token");
  17098. }
  17099. }
  17100. std::string msg;
  17101. while (ws.read(msg)) {
  17102. ws.send(msg);
  17103. }
  17104. });
  17105. auto port = svr.bind_to_any_port("localhost");
  17106. std::thread t([&]() { svr.listen_after_bind(); });
  17107. svr.wait_until_ready();
  17108. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17109. "/ws?token=ABC&session=123");
  17110. ASSERT_TRUE(client.connect());
  17111. // Round-trip ensures the handler has run and captured the request.
  17112. ASSERT_TRUE(client.send("hello"));
  17113. std::string msg;
  17114. ASSERT_TRUE(client.read(msg));
  17115. EXPECT_EQ("hello", msg);
  17116. client.close();
  17117. {
  17118. std::lock_guard<std::mutex> lock(mtx);
  17119. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17120. EXPECT_EQ("ABC", received_token);
  17121. }
  17122. svr.stop();
  17123. t.join();
  17124. }
  17125. // Run a handshake against a throwaway server and hand the request the server
  17126. // received back to the caller, so tests can assert on the headers the client
  17127. // actually put on the wire.
  17128. static void capture_websocket_handshake_request(
  17129. const Headers &client_headers,
  17130. std::function<void(const Request &, int port)> verify) {
  17131. Server svr;
  17132. std::mutex mtx;
  17133. Request received;
  17134. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17135. {
  17136. std::lock_guard<std::mutex> lock(mtx);
  17137. received = req;
  17138. }
  17139. std::string msg;
  17140. while (ws.read(msg)) {
  17141. ws.send(msg);
  17142. }
  17143. });
  17144. auto port = svr.bind_to_any_port("localhost");
  17145. std::thread t([&]() { svr.listen_after_bind(); });
  17146. auto se = detail::scope_exit([&] {
  17147. svr.stop();
  17148. t.join();
  17149. });
  17150. svr.wait_until_ready();
  17151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17152. client_headers);
  17153. ASSERT_TRUE(client.connect());
  17154. ASSERT_TRUE(client.send("hello"));
  17155. std::string msg;
  17156. ASSERT_TRUE(client.read(msg));
  17157. client.close();
  17158. {
  17159. std::lock_guard<std::mutex> lock(mtx);
  17160. verify(received, port);
  17161. }
  17162. }
  17163. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17164. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17165. // Non-default port must be present in the Host header. Default ports
  17166. // (80/443) are omitted; that logic is covered by
  17167. // MakeHostAndPortStringTest.
  17168. EXPECT_EQ("localhost:" + std::to_string(port),
  17169. req.get_header_value("Host"));
  17170. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17171. req.get_header_value("User-Agent"));
  17172. EXPECT_FALSE(req.has_header("Accept"));
  17173. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17174. EXPECT_FALSE(req.has_header("Content-Length"));
  17175. });
  17176. }
  17177. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17178. capture_websocket_handshake_request(
  17179. {{"Host", "example.com"},
  17180. {"User-Agent", "custom-agent"},
  17181. {"X-Custom", "value"}},
  17182. [](const Request &req, int) {
  17183. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17184. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17185. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17186. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17187. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17188. });
  17189. }
  17190. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17191. capture_websocket_handshake_request(
  17192. {{"Upgrade", "bogus"},
  17193. {"Connection", "close"},
  17194. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17195. {"Sec-WebSocket-Version", "8"}},
  17196. [](const Request &req, int) {
  17197. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17198. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17199. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17200. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17201. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17202. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17203. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17204. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17205. req.get_header_value("Sec-WebSocket-Key"));
  17206. });
  17207. }
  17208. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17209. // A header the client refuses to send must abort the handshake before any
  17210. // part of it reaches the wire; a lone request line would otherwise sit in
  17211. // the peer's buffer as a truncated request.
  17212. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17213. ASSERT_NE(INVALID_SOCKET, srv);
  17214. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17215. sockaddr_in addr{};
  17216. addr.sin_family = AF_INET;
  17217. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17218. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17219. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17220. ASSERT_EQ(0, ::listen(srv, 1));
  17221. sockaddr_in bound{};
  17222. socklen_t bound_len = sizeof(bound);
  17223. ASSERT_EQ(
  17224. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17225. auto port = ntohs(bound.sin_port);
  17226. ssize_t received = -1;
  17227. std::thread t([&] {
  17228. // Bound every blocking call so a regression fails the test with a bad
  17229. // value instead of hanging the suite.
  17230. fd_set rfds;
  17231. FD_ZERO(&rfds);
  17232. FD_SET(srv, &rfds);
  17233. timeval tv{5, 0};
  17234. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17235. 0) {
  17236. return;
  17237. }
  17238. sockaddr_in cli_addr{};
  17239. socklen_t cli_len = sizeof(cli_addr);
  17240. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17241. if (cli == INVALID_SOCKET) { return; }
  17242. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17243. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17244. char buf[4096];
  17245. received = ::recv(cli, buf, sizeof(buf), 0);
  17246. });
  17247. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17248. // connect() has already shut the socket down by the time it returns false,
  17249. // so the peer sees EOF without waiting for the client to be destroyed.
  17250. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17251. {{"X-Bad", "a\r\nInjected: 1"}});
  17252. EXPECT_FALSE(client.connect());
  17253. t.join();
  17254. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17255. EXPECT_EQ(0, received);
  17256. }
  17257. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17258. // The socket path doubles as the URL host, so it must not contain '/'.
  17259. const char *shard = getenv("GTEST_SHARD_INDEX");
  17260. const std::string sock_path =
  17261. shard ? std::string("httplib-ws-") + shard + ".sock"
  17262. : std::string("httplib-ws.sock");
  17263. std::remove(sock_path.c_str());
  17264. Server svr;
  17265. std::mutex mtx;
  17266. std::string received_host;
  17267. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17268. {
  17269. std::lock_guard<std::mutex> lock(mtx);
  17270. received_host = req.get_header_value("Host");
  17271. }
  17272. std::string msg;
  17273. while (ws.read(msg)) {
  17274. ws.send(msg);
  17275. }
  17276. });
  17277. svr.set_address_family(AF_UNIX);
  17278. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17279. auto se = detail::scope_exit([&] {
  17280. svr.stop();
  17281. t.join();
  17282. std::remove(sock_path.c_str());
  17283. });
  17284. svr.wait_until_ready();
  17285. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17286. client.set_address_family(AF_UNIX);
  17287. ASSERT_TRUE(client.connect());
  17288. ASSERT_TRUE(client.send("hello"));
  17289. std::string msg;
  17290. ASSERT_TRUE(client.read(msg));
  17291. client.close();
  17292. {
  17293. std::lock_guard<std::mutex> lock(mtx);
  17294. // There is no host:port for a Unix socket, so the same "localhost"
  17295. // placeholder the HTTP client uses is expected.
  17296. EXPECT_EQ("localhost", received_host);
  17297. }
  17298. }
  17299. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17300. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17301. protected:
  17302. void SetUp() override {
  17303. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17304. SERVER_PRIVATE_KEY_FILE);
  17305. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17306. std::string msg;
  17307. ws::ReadResult ret;
  17308. while ((ret = ws.read(msg))) {
  17309. if (ret == ws::Binary) {
  17310. ws.send(msg.data(), msg.size());
  17311. } else {
  17312. ws.send(msg);
  17313. }
  17314. }
  17315. });
  17316. port_ = server_->bind_to_any_port(HOST);
  17317. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17318. server_->wait_until_ready();
  17319. }
  17320. void TearDown() override {
  17321. server_->stop();
  17322. if (server_thread_.joinable()) { server_thread_.join(); }
  17323. }
  17324. std::unique_ptr<SSLServer> server_;
  17325. std::thread server_thread_;
  17326. int port_ = 0;
  17327. };
  17328. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17329. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17330. "/ws-echo");
  17331. client.enable_server_certificate_verification(false);
  17332. ASSERT_TRUE(client.connect());
  17333. ASSERT_TRUE(client.is_open());
  17334. ASSERT_TRUE(client.send("Hello WSS"));
  17335. std::string msg;
  17336. EXPECT_EQ(ws::Text, client.read(msg));
  17337. EXPECT_EQ("Hello WSS", msg);
  17338. client.close();
  17339. }
  17340. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17341. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17342. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17343. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17344. // client (without calling close() first) is the only path that runs
  17345. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17346. // bug exactly.
  17347. //
  17348. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17349. // when linked against an instrumented libssl; run under Valgrind to catch it
  17350. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17351. // suite (the freed session otherwise stalls on the close handshake) — this test
  17352. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17353. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17354. {
  17355. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17356. "/ws-echo");
  17357. client.enable_server_certificate_verification(false);
  17358. client.set_read_timeout(2, 0);
  17359. client.set_write_timeout(2, 0);
  17360. ASSERT_TRUE(client.connect());
  17361. ASSERT_TRUE(client.is_open());
  17362. ASSERT_TRUE(client.send("still open"));
  17363. // Intentionally do NOT call client.close(): leaving scope runs
  17364. // shutdown_and_close() with the WebSocket still open, which must send the
  17365. // close frame while the TLS session is still alive.
  17366. }
  17367. }
  17368. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17369. // shutdown_and_close() at the start of connect(), reproducing the same
  17370. // use-after-free within the test body rather than at scope exit. The second
  17371. // connect must succeed and echo, proving the close handshake ran over a live
  17372. // session. See the note above about memory-tool requirements.
  17373. TEST_F(WebSocketSSLIntegrationTest,
  17374. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17375. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17376. "/ws-echo");
  17377. client.enable_server_certificate_verification(false);
  17378. client.set_read_timeout(2, 0);
  17379. client.set_write_timeout(2, 0);
  17380. ASSERT_TRUE(client.connect());
  17381. ASSERT_TRUE(client.is_open());
  17382. ASSERT_TRUE(client.send("still open"));
  17383. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17384. // the still-open connection, which must not touch a freed TLS session.
  17385. ASSERT_TRUE(client.connect());
  17386. ASSERT_TRUE(client.is_open());
  17387. ASSERT_TRUE(client.send("after reconnect"));
  17388. std::string msg;
  17389. EXPECT_EQ(ws::Text, client.read(msg));
  17390. EXPECT_EQ("after reconnect", msg);
  17391. client.close();
  17392. }
  17393. #endif
  17394. #ifdef CPPHTTPLIB_SSL_ENABLED
  17395. class WebSocketSSLCATest : public ::testing::Test {
  17396. protected:
  17397. void SetUp() override {
  17398. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17399. SERVER_PRIVATE_KEY_FILE);
  17400. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17401. std::string msg;
  17402. while (ws.read(msg)) {
  17403. ws.send(msg);
  17404. }
  17405. });
  17406. port_ = server_->bind_to_any_port("127.0.0.1");
  17407. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17408. server_->wait_until_ready();
  17409. }
  17410. void TearDown() override {
  17411. server_->stop();
  17412. if (server_thread_.joinable()) { server_thread_.join(); }
  17413. }
  17414. std::string url() const {
  17415. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17416. }
  17417. std::unique_ptr<SSLServer> server_;
  17418. std::thread server_thread_;
  17419. int port_ = 0;
  17420. };
  17421. // A custom CA loaded as PEM verifies the server with full certificate
  17422. // verification enabled
  17423. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17424. ws::WebSocketClient client(url());
  17425. std::string cert;
  17426. read_file(SERVER_CERT2_FILE, cert);
  17427. client.load_ca_cert_store(cert.c_str(), cert.size());
  17428. ASSERT_TRUE(client.connect());
  17429. ASSERT_TRUE(client.send("hello"));
  17430. std::string msg;
  17431. EXPECT_EQ(ws::Text, client.read(msg));
  17432. EXPECT_EQ("hello", msg);
  17433. client.close();
  17434. }
  17435. // A custom CA that does not cover the server must fail verification (the
  17436. // custom CA is exclusive; system certs are not loaded alongside it)
  17437. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17438. ws::WebSocketClient client(url());
  17439. std::string cert;
  17440. read_file(CLIENT_CA_CERT_FILE, cert);
  17441. client.load_ca_cert_store(cert.c_str(), cert.size());
  17442. ASSERT_FALSE(client.connect());
  17443. }
  17444. // Regression test: reconnecting with a native custom CA store used to reuse
  17445. // a store handle the previous TLS context had already freed (use-after-free
  17446. // under the OpenSSL backend). The context now lives as long as the client.
  17447. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17448. ws::WebSocketClient client(url());
  17449. std::string cert;
  17450. read_file(SERVER_CERT2_FILE, cert);
  17451. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17452. ASSERT_TRUE(client.connect());
  17453. client.close();
  17454. ASSERT_TRUE(client.connect());
  17455. ASSERT_TRUE(client.send("again"));
  17456. std::string msg;
  17457. EXPECT_EQ(ws::Text, client.read(msg));
  17458. EXPECT_EQ("again", msg);
  17459. client.close();
  17460. }
  17461. // Regression test: a certificate with a trusted chain but no identity match
  17462. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17463. // verification entirely for IP hosts, so this connection succeeded there.
  17464. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17465. // chain verification while the identity check must still fail.
  17466. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17468. ASSERT_TRUE(svr.is_valid());
  17469. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17470. std::string msg;
  17471. while (ws.read(msg)) {
  17472. ws.send(msg);
  17473. }
  17474. });
  17475. auto port = svr.bind_to_any_port("127.0.0.1");
  17476. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17477. auto se = detail::scope_exit([&] {
  17478. svr.stop();
  17479. t.join();
  17480. });
  17481. svr.wait_until_ready();
  17482. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17483. "/echo");
  17484. std::string cert;
  17485. read_file(SERVER_CERT_FILE, cert);
  17486. client.load_ca_cert_store(cert.c_str(), cert.size());
  17487. ASSERT_FALSE(client.connect());
  17488. }
  17489. #endif
  17490. #if !defined(_WIN32)
  17491. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17492. auto secret_dir = std::string("./symlink_test_secret");
  17493. auto served_dir = std::string("./symlink_test_served");
  17494. auto secret_file = secret_dir + "/secret.txt";
  17495. auto symlink_path = served_dir + "/escape";
  17496. // Setup: create directories and files
  17497. mkdir(secret_dir.c_str(), 0755);
  17498. mkdir(served_dir.c_str(), 0755);
  17499. {
  17500. std::ofstream ofs(secret_file);
  17501. ofs << "SECRET_DATA";
  17502. }
  17503. // Create symlink using absolute path so it resolves correctly
  17504. #ifdef PATH_MAX
  17505. char abs_secret[PATH_MAX];
  17506. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17507. #else
  17508. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17509. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17510. ASSERT_NE(nullptr, abs_secret);
  17511. #endif
  17512. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17513. auto se = detail::scope_exit([&] {
  17514. unlink(symlink_path.c_str());
  17515. unlink(secret_file.c_str());
  17516. rmdir(served_dir.c_str());
  17517. rmdir(secret_dir.c_str());
  17518. });
  17519. Server svr;
  17520. svr.set_mount_point("/", served_dir);
  17521. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17522. auto se2 = detail::scope_exit([&] {
  17523. svr.stop();
  17524. listen_thread.join();
  17525. });
  17526. svr.wait_until_ready();
  17527. Client cli("localhost", PORT);
  17528. // Symlink pointing outside base dir should be blocked
  17529. auto res = cli.Get("/escape/secret.txt");
  17530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17531. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17532. }
  17533. #endif
  17534. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17535. // A GET request with Content-Length to a static file handler must have its
  17536. // body drained before the keep-alive connection is reused. Otherwise the
  17537. // unread body bytes are interpreted as the next HTTP request.
  17538. //
  17539. // The body is sent AFTER receiving the first response (as in the original
  17540. // PoC) so that the stream_line_reader cannot buffer it together with the
  17541. // headers of the first request.
  17542. Server svr;
  17543. svr.set_mount_point("/", "./www");
  17544. std::atomic<int> smuggled_count(0);
  17545. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17546. smuggled_count++;
  17547. res.set_content("oops", "text/plain");
  17548. });
  17549. auto port = svr.bind_to_any_port("localhost");
  17550. thread t = thread([&] { svr.listen_after_bind(); });
  17551. auto se = detail::scope_exit([&] {
  17552. svr.stop();
  17553. t.join();
  17554. });
  17555. svr.wait_until_ready();
  17556. auto error = Error::Success;
  17557. auto sock = detail::create_client_socket(
  17558. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17559. /*connection_timeout_sec=*/2, 0,
  17560. /*read_timeout_sec=*/2, 0,
  17561. /*write_timeout_sec=*/2, 0, std::string(), error);
  17562. ASSERT_NE(INVALID_SOCKET, sock);
  17563. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17564. // The "smuggled" request will be sent as the body of the outer GET
  17565. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17566. "Host: localhost\r\n"
  17567. "Connection: close\r\n"
  17568. "\r\n";
  17569. // Step 1: Send only the outer request headers (no body yet)
  17570. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17571. "Host: localhost\r\n"
  17572. "Content-Length: " +
  17573. std::to_string(smuggled.size()) +
  17574. "\r\n"
  17575. "\r\n";
  17576. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17577. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17578. // Step 2: Read the first response (server serves file without reading body)
  17579. std::string first_response;
  17580. char buf[4096];
  17581. for (;;) {
  17582. auto n = recv(sock, buf, sizeof(buf), 0);
  17583. if (n <= 0) break;
  17584. first_response.append(buf, static_cast<size_t>(n));
  17585. // Stop once we have a complete response (headers + body)
  17586. auto hdr_end = first_response.find("\r\n\r\n");
  17587. if (hdr_end != std::string::npos) {
  17588. // Check for Content-Length to know when the body is complete
  17589. auto cl_pos = first_response.find("Content-Length:");
  17590. if (cl_pos != std::string::npos) {
  17591. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17592. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17593. auto cl = std::stoul(
  17594. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17595. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17596. } else {
  17597. break; // No Content-Length, assume headers-only response
  17598. }
  17599. }
  17600. }
  17601. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17602. // Step 3: Now send the body, which looks like a new HTTP request.
  17603. // On a vulnerable server the keep-alive loop reads this as a second request.
  17604. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17605. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17606. // Step 4: Try to read a second response (should NOT exist after fix)
  17607. std::string second_response;
  17608. for (;;) {
  17609. auto n = recv(sock, buf, sizeof(buf), 0);
  17610. if (n <= 0) break;
  17611. second_response.append(buf, static_cast<size_t>(n));
  17612. }
  17613. // The smuggled request must NOT have been processed
  17614. EXPECT_EQ(0, smuggled_count.load());
  17615. }
  17616. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17617. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17618. // must be rejected with 400 Bad Request.
  17619. Server svr;
  17620. svr.Post("/test", [&](const Request &, Response &res) {
  17621. res.set_content("ok", "text/plain");
  17622. });
  17623. thread t = thread([&] { svr.listen(HOST, PORT); });
  17624. auto se = detail::scope_exit([&] {
  17625. svr.stop();
  17626. t.join();
  17627. ASSERT_FALSE(svr.is_running());
  17628. });
  17629. svr.wait_until_ready();
  17630. // Exact "chunked"
  17631. {
  17632. auto req = "POST /test HTTP/1.1\r\n"
  17633. "Host: localhost\r\n"
  17634. "Content-Length: 5\r\n"
  17635. "Transfer-Encoding: chunked\r\n"
  17636. "Connection: close\r\n"
  17637. "\r\n"
  17638. "hello";
  17639. std::string response;
  17640. ASSERT_TRUE(send_request(1, req, &response));
  17641. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17642. response.substr(0, response.find("\r\n")));
  17643. }
  17644. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17645. {
  17646. auto req = "POST /test HTTP/1.1\r\n"
  17647. "Host: localhost\r\n"
  17648. "Content-Length: 5\r\n"
  17649. "Transfer-Encoding: gzip, chunked\r\n"
  17650. "Connection: close\r\n"
  17651. "\r\n"
  17652. "hello";
  17653. std::string response;
  17654. ASSERT_TRUE(send_request(1, req, &response));
  17655. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17656. response.substr(0, response.find("\r\n")));
  17657. }
  17658. }
  17659. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17660. Server svr;
  17661. svr.Post("/test", [&](const Request &, Response &res) {
  17662. res.set_content("ok", "text/plain");
  17663. });
  17664. thread t = thread([&] { svr.listen(HOST, PORT); });
  17665. auto se = detail::scope_exit([&] {
  17666. svr.stop();
  17667. t.join();
  17668. ASSERT_FALSE(svr.is_running());
  17669. });
  17670. svr.wait_until_ready();
  17671. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17672. // length cannot be determined, so the server must answer 400 and close
  17673. // rather than treat the request as bodyless and leave the body in the
  17674. // socket for the next request to pick up.
  17675. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17676. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17677. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17678. std::string response;
  17679. ASSERT_TRUE(send_request(1, req, &response));
  17680. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17681. response.substr(0, response.find("\r\n")))
  17682. << transfer_encoding;
  17683. }
  17684. // RFC 9110 5.3: the codings may also be split across several
  17685. // Transfer-Encoding lines, which combine in the order they were received.
  17686. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17687. // just like the single-line "chunked, gzip" above.
  17688. {
  17689. auto req = "POST /test HTTP/1.1\r\n"
  17690. "Host: localhost\r\n"
  17691. "Transfer-Encoding: chunked\r\n"
  17692. "Transfer-Encoding: gzip\r\n"
  17693. "\r\n"
  17694. "0\r\n\r\n";
  17695. std::string response;
  17696. ASSERT_TRUE(send_request(1, req, &response));
  17697. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17698. response.substr(0, response.find("\r\n")));
  17699. }
  17700. // A sequence ending in chunked stays valid.
  17701. auto req = "POST /test HTTP/1.1\r\n"
  17702. "Host: localhost\r\n"
  17703. "Transfer-Encoding: gzip, chunked\r\n"
  17704. "Connection: close\r\n"
  17705. "\r\n"
  17706. "0\r\n\r\n";
  17707. std::string response;
  17708. ASSERT_TRUE(send_request(1, req, &response));
  17709. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17710. // ...including when it is spread over several lines.
  17711. auto split_req = "POST /test HTTP/1.1\r\n"
  17712. "Host: localhost\r\n"
  17713. "Transfer-Encoding: gzip\r\n"
  17714. "Transfer-Encoding: chunked\r\n"
  17715. "Connection: close\r\n"
  17716. "\r\n"
  17717. "0\r\n\r\n";
  17718. std::string split_response;
  17719. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17720. EXPECT_EQ("HTTP/1.1 200 OK",
  17721. split_response.substr(0, split_response.find("\r\n")));
  17722. }
  17723. // Regression for issue #2450: a DELETE without Content-Length on a
  17724. // keep-alive connection must not let the post-response drain consume the
  17725. // next request's bytes.
  17726. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17727. Server svr;
  17728. std::atomic<int> delete_count(0);
  17729. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17730. delete_count++;
  17731. res.status = StatusCode::NoContent_204;
  17732. });
  17733. auto port = svr.bind_to_any_port(HOST);
  17734. thread t = thread([&] { svr.listen_after_bind(); });
  17735. auto se = detail::scope_exit([&] {
  17736. svr.stop();
  17737. t.join();
  17738. });
  17739. svr.wait_until_ready();
  17740. auto error = Error::Success;
  17741. auto sock = detail::create_client_socket(
  17742. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17743. /*connection_timeout_sec=*/2, 0,
  17744. /*read_timeout_sec=*/2, 0,
  17745. /*write_timeout_sec=*/2, 0, std::string(), error);
  17746. ASSERT_NE(INVALID_SOCKET, sock);
  17747. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17748. auto send_request_and_read_response = [&](const std::string &req,
  17749. std::string &out) -> bool {
  17750. auto sent = send(sock, req.data(), req.size(), 0);
  17751. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17752. char buf[4096];
  17753. for (;;) {
  17754. auto n = recv(sock, buf, sizeof(buf), 0);
  17755. if (n <= 0) { return !out.empty(); }
  17756. out.append(buf, static_cast<size_t>(n));
  17757. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17758. }
  17759. };
  17760. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17761. "Host: localhost\r\n"
  17762. "\r\n";
  17763. std::string resp1;
  17764. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17765. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17766. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17767. "Host: localhost\r\n"
  17768. "Connection: close\r\n"
  17769. "\r\n";
  17770. std::string resp2;
  17771. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17772. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17773. EXPECT_EQ(2, delete_count.load());
  17774. }
  17775. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17776. Server svr;
  17777. svr.Post("/ingest", [&](const Request &, Response &res,
  17778. const ContentReader &content_reader) {
  17779. auto consumed = content_reader([](const char *, size_t) { return false; });
  17780. EXPECT_FALSE(consumed);
  17781. res.status = StatusCode::Conflict_409;
  17782. res.set_header("Connection", "close");
  17783. });
  17784. auto port = svr.bind_to_any_port(HOST);
  17785. thread t = thread([&] { svr.listen_after_bind(); });
  17786. auto se = detail::scope_exit([&] {
  17787. svr.stop();
  17788. t.join();
  17789. });
  17790. svr.wait_until_ready();
  17791. auto error = Error::Success;
  17792. auto sock = detail::create_client_socket(
  17793. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17794. /*connection_timeout_sec=*/2, 0,
  17795. /*read_timeout_sec=*/1, 0,
  17796. /*write_timeout_sec=*/2, 0, std::string(), error);
  17797. ASSERT_NE(INVALID_SOCKET, sock);
  17798. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17799. std::string request = "POST /ingest HTTP/1.1\r\n"
  17800. "Host: localhost\r\n"
  17801. "Transfer-Encoding: chunked\r\n"
  17802. "\r\n"
  17803. "4\r\n"
  17804. "data\r\n";
  17805. auto sent = send(sock, request.data(), request.size(), 0);
  17806. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17807. std::string response;
  17808. ssize_t received = 0;
  17809. do {
  17810. char buf[4096];
  17811. received = recv(sock, buf, sizeof(buf), 0);
  17812. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17813. } while (received > 0);
  17814. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17815. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17816. EXPECT_EQ(0, received);
  17817. }
  17818. namespace no_proxy_test {
  17819. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17820. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17821. // calling listen().
  17822. class ScopedServer {
  17823. public:
  17824. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17825. ~ScopedServer() {
  17826. svr_.stop();
  17827. if (th_.joinable()) { th_.join(); }
  17828. }
  17829. Server &svr() { return svr_; }
  17830. int port() const { return port_; }
  17831. void listen() {
  17832. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17833. svr_.wait_until_ready();
  17834. }
  17835. private:
  17836. Server svr_;
  17837. std::thread th_;
  17838. int port_ = 0;
  17839. };
  17840. class ProxyAndTargetServers {
  17841. public:
  17842. ProxyAndTargetServers() {
  17843. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17844. proxy_hits_++;
  17845. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17846. res.set_content("via-proxy", "text/plain");
  17847. });
  17848. target_.Get(".*", [this](const Request &req, Response &res) {
  17849. target_hits_++;
  17850. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17851. res.set_content("direct", "text/plain");
  17852. });
  17853. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17854. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17855. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17856. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17857. proxy_mock_.wait_until_ready();
  17858. target_.wait_until_ready();
  17859. }
  17860. ~ProxyAndTargetServers() {
  17861. proxy_mock_.stop();
  17862. target_.stop();
  17863. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17864. if (target_thread_.joinable()) { target_thread_.join(); }
  17865. }
  17866. Server &proxy_mock() { return proxy_mock_; }
  17867. Server &target() { return target_; }
  17868. int proxy_port() const { return proxy_port_; }
  17869. int target_port() const { return target_port_; }
  17870. int proxy_hits() const { return proxy_hits_.load(); }
  17871. int target_hits() const { return target_hits_.load(); }
  17872. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17873. void reset_counters() {
  17874. proxy_hits_ = 0;
  17875. target_hits_ = 0;
  17876. last_had_proxy_authz_ = false;
  17877. }
  17878. private:
  17879. Server proxy_mock_;
  17880. Server target_;
  17881. std::thread proxy_thread_;
  17882. std::thread target_thread_;
  17883. int proxy_port_ = 0;
  17884. int target_port_ = 0;
  17885. std::atomic<int> proxy_hits_{0};
  17886. std::atomic<int> target_hits_{0};
  17887. std::atomic<bool> last_had_proxy_authz_{false};
  17888. };
  17889. inline std::unique_ptr<Client> make_client(const std::string &host,
  17890. ProxyAndTargetServers &s) {
  17891. auto cli = detail::make_unique<Client>(host, s.target_port());
  17892. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17893. cli->set_proxy("127.0.0.1", s.proxy_port());
  17894. return cli;
  17895. }
  17896. } // namespace no_proxy_test
  17897. using no_proxy_test::make_client;
  17898. using no_proxy_test::ProxyAndTargetServers;
  17899. TEST(NoProxyTest, ExactHostnameBypasses) {
  17900. ProxyAndTargetServers s;
  17901. auto cli = make_client("example.com", s);
  17902. cli->set_no_proxy({"example.com"});
  17903. auto res = cli->Get("/");
  17904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17905. EXPECT_EQ(0, s.proxy_hits());
  17906. EXPECT_EQ(1, s.target_hits());
  17907. }
  17908. TEST(NoProxyTest, SubdomainBypasses) {
  17909. ProxyAndTargetServers s;
  17910. auto cli = make_client("foo.example.com", s);
  17911. cli->set_no_proxy({"example.com"});
  17912. auto res = cli->Get("/");
  17913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17914. EXPECT_EQ(0, s.proxy_hits());
  17915. EXPECT_EQ(1, s.target_hits());
  17916. }
  17917. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17918. // Regression guard: "evilexample.com" must not be considered a subdomain
  17919. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17920. // check would let traffic bypass the proxy and leak credentials direct
  17921. // to the attacker host.
  17922. ProxyAndTargetServers s;
  17923. auto cli = make_client("evilexample.com", s);
  17924. cli->set_no_proxy({"example.com"});
  17925. auto res = cli->Get("/");
  17926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17927. EXPECT_GE(s.proxy_hits(), 1);
  17928. EXPECT_EQ(0, s.target_hits());
  17929. }
  17930. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17931. ProxyAndTargetServers s;
  17932. auto cli = make_client("example.com.evil.com", s);
  17933. cli->set_no_proxy({"example.com"});
  17934. auto res = cli->Get("/");
  17935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17936. EXPECT_GE(s.proxy_hits(), 1);
  17937. EXPECT_EQ(0, s.target_hits());
  17938. }
  17939. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17940. ProxyAndTargetServers s;
  17941. auto cli = make_client("example.com", s);
  17942. cli->set_no_proxy({".example.com"});
  17943. auto res = cli->Get("/");
  17944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17945. EXPECT_EQ(0, s.proxy_hits());
  17946. EXPECT_EQ(1, s.target_hits());
  17947. }
  17948. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17949. ProxyAndTargetServers s;
  17950. auto cli = make_client("Example.COM", s);
  17951. cli->set_no_proxy({"EXAMPLE.com"});
  17952. auto res = cli->Get("/");
  17953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17954. EXPECT_EQ(0, s.proxy_hits());
  17955. EXPECT_EQ(1, s.target_hits());
  17956. }
  17957. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17958. ProxyAndTargetServers s;
  17959. auto cli = make_client("example.com.", s);
  17960. cli->set_no_proxy({"example.com"});
  17961. auto res = cli->Get("/");
  17962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17963. EXPECT_EQ(0, s.proxy_hits());
  17964. EXPECT_EQ(1, s.target_hits());
  17965. }
  17966. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17967. // Trailing dots must be normalized on BOTH sides — host and entry.
  17968. // An implementation that only strips the host-side trailing dot would
  17969. // fail to match host "example.com" against entry "example.com." because
  17970. // a literal substring search would compare 11 chars against 12.
  17971. ProxyAndTargetServers s;
  17972. auto cli = make_client("example.com", s);
  17973. cli->set_no_proxy({"example.com."});
  17974. auto res = cli->Get("/");
  17975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17976. EXPECT_EQ(0, s.proxy_hits());
  17977. EXPECT_EQ(1, s.target_hits());
  17978. }
  17979. TEST(NoProxyTest, WildcardBypassesEverything) {
  17980. ProxyAndTargetServers s;
  17981. auto cli = make_client("anything.invalid.test", s);
  17982. cli->set_no_proxy({"*"});
  17983. auto res = cli->Get("/");
  17984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17985. EXPECT_EQ(0, s.proxy_hits());
  17986. EXPECT_EQ(1, s.target_hits());
  17987. }
  17988. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17989. ProxyAndTargetServers s;
  17990. Client cli("127.0.0.1", s.target_port());
  17991. cli.set_proxy("127.0.0.1", s.proxy_port());
  17992. cli.set_no_proxy({"127.0.0.1"});
  17993. auto res = cli.Get("/");
  17994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17995. EXPECT_EQ(0, s.proxy_hits());
  17996. EXPECT_EQ(1, s.target_hits());
  17997. }
  17998. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17999. ProxyAndTargetServers s;
  18000. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18001. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18002. cli.set_proxy("127.0.0.1", s.proxy_port());
  18003. cli.set_no_proxy({"::1"});
  18004. auto res = cli.Get("/");
  18005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18006. EXPECT_EQ(0, s.proxy_hits());
  18007. EXPECT_EQ(1, s.target_hits());
  18008. }
  18009. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18010. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18011. // must still be recognized as IPv6 for CIDR matching. Implementations
  18012. // that detect IPv6 only when the host begins with '[' would parse the
  18013. // host as a hostname and miss the match.
  18014. ProxyAndTargetServers s;
  18015. Client cli("fe80::1", s.target_port());
  18016. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18017. cli.set_proxy("127.0.0.1", s.proxy_port());
  18018. cli.set_no_proxy({"fe80::/10"});
  18019. auto res = cli.Get("/");
  18020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18021. EXPECT_EQ(0, s.proxy_hits());
  18022. EXPECT_EQ(1, s.target_hits());
  18023. }
  18024. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18025. ProxyAndTargetServers s;
  18026. Client cli("::1", s.target_port());
  18027. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18028. cli.set_proxy("127.0.0.1", s.proxy_port());
  18029. cli.set_no_proxy({"[::1]"});
  18030. auto res = cli.Get("/");
  18031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18032. EXPECT_EQ(0, s.proxy_hits());
  18033. EXPECT_EQ(1, s.target_hits());
  18034. }
  18035. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18036. ProxyAndTargetServers s;
  18037. Client cli("fe80::1", s.target_port());
  18038. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18039. cli.set_proxy("127.0.0.1", s.proxy_port());
  18040. cli.set_no_proxy({"[fe80::]/10"});
  18041. auto res = cli.Get("/");
  18042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18043. EXPECT_EQ(0, s.proxy_hits());
  18044. EXPECT_EQ(1, s.target_hits());
  18045. }
  18046. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18047. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18048. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18049. // tricks via address-family conversion.
  18050. ProxyAndTargetServers s;
  18051. Client cli("::ffff:127.0.0.1", s.target_port());
  18052. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18053. cli.set_proxy("127.0.0.1", s.proxy_port());
  18054. cli.set_no_proxy({"127.0.0.1"});
  18055. auto res = cli.Get("/");
  18056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18057. EXPECT_GE(s.proxy_hits(), 1);
  18058. EXPECT_EQ(0, s.target_hits());
  18059. }
  18060. TEST(NoProxyTest, IPv4CidrMatch) {
  18061. ProxyAndTargetServers s;
  18062. Client cli("127.0.0.1", s.target_port());
  18063. cli.set_proxy("127.0.0.1", s.proxy_port());
  18064. cli.set_no_proxy({"127.0.0.0/8"});
  18065. auto res = cli.Get("/");
  18066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18067. EXPECT_EQ(0, s.proxy_hits());
  18068. EXPECT_EQ(1, s.target_hits());
  18069. }
  18070. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18071. ProxyAndTargetServers s;
  18072. Client cli("127.0.0.1", s.target_port());
  18073. cli.set_proxy("127.0.0.1", s.proxy_port());
  18074. cli.set_no_proxy({"10.0.0.0/8"});
  18075. auto res = cli.Get("/");
  18076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18077. EXPECT_GE(s.proxy_hits(), 1);
  18078. EXPECT_EQ(0, s.target_hits());
  18079. }
  18080. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18081. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18082. // IPv4 target matches.
  18083. ProxyAndTargetServers s;
  18084. Client cli("127.0.0.1", s.target_port());
  18085. cli.set_proxy("127.0.0.1", s.proxy_port());
  18086. cli.set_no_proxy({"0.0.0.0/0"});
  18087. auto res = cli.Get("/");
  18088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18089. EXPECT_EQ(0, s.proxy_hits());
  18090. EXPECT_EQ(1, s.target_hits());
  18091. }
  18092. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18093. ProxyAndTargetServers s;
  18094. Client cli("127.0.0.1", s.target_port());
  18095. cli.set_proxy("127.0.0.1", s.proxy_port());
  18096. cli.set_no_proxy({"127.0.0.1"});
  18097. auto res = cli.Get("/");
  18098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18099. EXPECT_EQ(0, s.proxy_hits());
  18100. EXPECT_EQ(1, s.target_hits());
  18101. }
  18102. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18103. ProxyAndTargetServers s;
  18104. Client cli("127.0.0.1", s.target_port());
  18105. cli.set_proxy("127.0.0.1", s.proxy_port());
  18106. cli.set_no_proxy({"127.0.0.0/33"});
  18107. auto res = cli.Get("/");
  18108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18109. EXPECT_GE(s.proxy_hits(), 1);
  18110. EXPECT_EQ(0, s.target_hits());
  18111. }
  18112. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18113. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18114. ProxyAndTargetServers s;
  18115. Client cli("127.0.0.1", s.target_port());
  18116. cli.set_proxy("127.0.0.1", s.proxy_port());
  18117. cli.set_no_proxy({"127.0.0.1/"});
  18118. auto res = cli.Get("/");
  18119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18120. EXPECT_GE(s.proxy_hits(), 1);
  18121. EXPECT_EQ(0, s.target_hits());
  18122. }
  18123. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18124. ProxyAndTargetServers s;
  18125. auto cli = make_client("internal.corp", s);
  18126. cli->set_proxy_basic_auth("u", "p");
  18127. cli->set_no_proxy({"internal.corp"});
  18128. auto res = cli->Get("/");
  18129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18130. EXPECT_EQ(1, s.target_hits());
  18131. EXPECT_EQ(0, s.proxy_hits());
  18132. EXPECT_FALSE(s.last_had_proxy_authz())
  18133. << "Proxy-Authorization must not be sent direct to the target";
  18134. }
  18135. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18136. ProxyAndTargetServers s;
  18137. auto cli = make_client("public.example", s);
  18138. cli->set_proxy_basic_auth("u", "p");
  18139. cli->set_no_proxy({"internal.corp"}); // does not match
  18140. auto res = cli->Get("/");
  18141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18142. EXPECT_GE(s.proxy_hits(), 1);
  18143. EXPECT_TRUE(s.last_had_proxy_authz());
  18144. }
  18145. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18146. ProxyAndTargetServers s;
  18147. auto cli = make_client("anything.test", s);
  18148. auto res = cli->Get("/");
  18149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18150. EXPECT_GE(s.proxy_hits(), 1);
  18151. EXPECT_EQ(0, s.target_hits());
  18152. }
  18153. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18154. ProxyAndTargetServers s;
  18155. auto cli = make_client("example.com", s);
  18156. cli->set_no_proxy({"example.com:8080"});
  18157. auto res = cli->Get("/");
  18158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18159. EXPECT_GE(s.proxy_hits(), 1);
  18160. EXPECT_EQ(0, s.target_hits());
  18161. }
  18162. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18163. ProxyAndTargetServers s;
  18164. auto cli = make_client("anything.test", s);
  18165. cli->set_no_proxy({"", " ", "\t"});
  18166. auto res = cli->Get("/");
  18167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18168. EXPECT_GE(s.proxy_hits(), 1);
  18169. EXPECT_EQ(0, s.target_hits());
  18170. }
  18171. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18172. // An entry with leading/trailing whitespace must still match — env-style
  18173. // values are commonly pasted with stray spaces and an implementation
  18174. // that feeds the raw token directly to inet_pton would fail to match
  18175. // valid CIDRs because of the spaces.
  18176. ProxyAndTargetServers s;
  18177. Client cli("127.0.0.1", s.target_port());
  18178. cli.set_proxy("127.0.0.1", s.proxy_port());
  18179. cli.set_no_proxy({" 127.0.0.0/8 "});
  18180. auto res = cli.Get("/");
  18181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18182. EXPECT_EQ(0, s.proxy_hits());
  18183. EXPECT_EQ(1, s.target_hits());
  18184. }
  18185. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18186. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18187. // go direct and must NOT carry Proxy-Authorization.
  18188. std::atomic<int> proxy_hits{0};
  18189. std::atomic<int> target_hits{0};
  18190. std::atomic<bool> target_saw_authz{false};
  18191. no_proxy_test::ScopedServer proxy_mock, target;
  18192. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18193. proxy_hits++;
  18194. res.status = 302;
  18195. res.set_header("Location", "http://127.0.0.1:" +
  18196. std::to_string(target.port()) + "/landed");
  18197. });
  18198. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18199. target_hits++;
  18200. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18201. res.set_content("direct", "text/plain");
  18202. });
  18203. proxy_mock.listen();
  18204. target.listen();
  18205. Client cli("public.example", target.port());
  18206. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18207. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18208. cli.set_proxy_basic_auth("u", "p");
  18209. cli.set_no_proxy({"127.0.0.1"});
  18210. cli.set_follow_location(true);
  18211. auto res = cli.Get("/redir");
  18212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18213. EXPECT_GE(proxy_hits.load(), 1);
  18214. EXPECT_GE(target_hits.load(), 1);
  18215. EXPECT_FALSE(target_saw_authz.load());
  18216. }
  18217. #ifdef CPPHTTPLIB_SSL_ENABLED
  18218. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18219. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18220. // proxy creds would be sent to the (possibly hostile) origin.
  18221. std::atomic<int> target_hits{0};
  18222. std::atomic<bool> target_saw_proxy_authz{false};
  18223. no_proxy_test::ScopedServer target;
  18224. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18225. target_hits++;
  18226. if (req.has_header("Proxy-Authorization")) {
  18227. target_saw_proxy_authz = true;
  18228. }
  18229. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18230. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18231. "nonce=\"abc\", algorithm=MD5");
  18232. });
  18233. target.listen();
  18234. // The proxy address is set to the target's port: the bypass MUST kick in;
  18235. // if it doesn't, the test still routes "via proxy" to the same server and
  18236. // the Proxy-Authorization assertion below catches the leak.
  18237. Client cli("evil.example", target.port());
  18238. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18239. cli.set_proxy("127.0.0.1", target.port());
  18240. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18241. cli.set_no_proxy({"evil.example"});
  18242. auto res = cli.Get("/x");
  18243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18244. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18245. EXPECT_EQ(1, target_hits.load());
  18246. EXPECT_FALSE(target_saw_proxy_authz.load());
  18247. }
  18248. #endif
  18249. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18250. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18251. std::atomic<int> proxy_hits{0};
  18252. std::atomic<int> bypass_hits{0};
  18253. std::atomic<bool> proxy_saw_c_url{false};
  18254. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18255. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18256. proxy_hits++;
  18257. if (req.path.find("/start") != std::string::npos) {
  18258. res.status = 302;
  18259. res.set_header("Location", "http://127.0.0.1:" +
  18260. std::to_string(bypass_server.port()) +
  18261. "/middle");
  18262. return;
  18263. }
  18264. if (req.path.find("/end") != std::string::npos) {
  18265. proxy_saw_c_url = true;
  18266. res.set_content("c-via-proxy", "text/plain");
  18267. return;
  18268. }
  18269. res.set_content("unexpected", "text/plain");
  18270. });
  18271. // public.example's "advertised" port is arbitrary (the request never lands
  18272. // there — it goes through the proxy), but use a dynamic value to stay
  18273. // friendly with sharded parallel runs.
  18274. int public_port = bypass_server.port();
  18275. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18276. bypass_hits++;
  18277. res.status = 302;
  18278. res.set_header("Location", "http://public.example:" +
  18279. std::to_string(public_port) + "/end");
  18280. });
  18281. proxy_mock.listen();
  18282. bypass_server.listen();
  18283. Client cli("public.example", public_port);
  18284. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18285. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18286. cli.set_no_proxy({"127.0.0.1"});
  18287. cli.set_follow_location(true);
  18288. auto res = cli.Get("/start");
  18289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18290. EXPECT_EQ(StatusCode::OK_200, res->status);
  18291. EXPECT_EQ("c-via-proxy", res->body);
  18292. EXPECT_GE(proxy_hits.load(), 2);
  18293. EXPECT_GE(bypass_hits.load(), 1);
  18294. EXPECT_TRUE(proxy_saw_c_url.load());
  18295. }
  18296. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18297. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18298. // request reconnects to the correct endpoint.
  18299. std::atomic<int> proxy_hits{0};
  18300. std::atomic<int> target_hits{0};
  18301. no_proxy_test::ScopedServer proxy_mock, target;
  18302. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18303. proxy_hits++;
  18304. res.set_content("via-proxy", "text/plain");
  18305. });
  18306. target.svr().Get(".*", [&](const Request &, Response &res) {
  18307. target_hits++;
  18308. res.set_content("direct", "text/plain");
  18309. });
  18310. proxy_mock.listen();
  18311. target.listen();
  18312. Client cli("public.example", target.port());
  18313. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18314. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18315. cli.set_keep_alive(true);
  18316. auto res1 = cli.Get("/a");
  18317. ASSERT_TRUE(res1);
  18318. EXPECT_EQ("via-proxy", res1->body);
  18319. EXPECT_EQ(1, proxy_hits.load());
  18320. EXPECT_EQ(0, target_hits.load());
  18321. cli.set_no_proxy({"public.example"});
  18322. auto res2 = cli.Get("/b");
  18323. ASSERT_TRUE(res2);
  18324. EXPECT_EQ("direct", res2->body);
  18325. EXPECT_EQ(1, proxy_hits.load());
  18326. EXPECT_EQ(1, target_hits.load());
  18327. }
  18328. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18329. namespace proxy_tunnel_test {
  18330. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18331. class ScopedSSLServer {
  18332. public:
  18333. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18334. port_ = svr_.bind_to_any_port("127.0.0.1");
  18335. }
  18336. ~ScopedSSLServer() {
  18337. svr_.stop();
  18338. if (th_.joinable()) { th_.join(); }
  18339. }
  18340. SSLServer &svr() { return svr_; }
  18341. int port() const { return port_; }
  18342. void listen() {
  18343. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18344. svr_.wait_until_ready();
  18345. }
  18346. private:
  18347. SSLServer svr_;
  18348. std::thread th_;
  18349. int port_ = 0;
  18350. };
  18351. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18352. class ScopedConnectProxy {
  18353. public:
  18354. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18355. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18356. if (listen_fd_ < 0) { return; }
  18357. int yes = 1;
  18358. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18359. sockaddr_in a{};
  18360. a.sin_family = AF_INET;
  18361. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18362. a.sin_port = 0;
  18363. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18364. return;
  18365. }
  18366. socklen_t alen = sizeof(a);
  18367. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18368. 0) {
  18369. return;
  18370. }
  18371. port_ = ntohs(a.sin_port);
  18372. if (::listen(listen_fd_, 1) != 0) { return; }
  18373. th_ = std::thread([this] { run(); });
  18374. }
  18375. ~ScopedConnectProxy() {
  18376. stop_ = true;
  18377. if (listen_fd_ >= 0) {
  18378. ::shutdown(listen_fd_, SHUT_RDWR);
  18379. ::close(listen_fd_);
  18380. }
  18381. if (th_.joinable()) { th_.join(); }
  18382. }
  18383. int port() const { return port_; }
  18384. int connect_hits() const { return connect_hits_.load(); }
  18385. private:
  18386. void run() {
  18387. while (!stop_.load()) {
  18388. fd_set rfds;
  18389. FD_ZERO(&rfds);
  18390. FD_SET(listen_fd_, &rfds);
  18391. timeval tv{0, 100 * 1000};
  18392. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18393. if (sel <= 0) { continue; }
  18394. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18395. if (client_fd < 0) { continue; }
  18396. std::string req;
  18397. char buf[2048];
  18398. while (req.find("\r\n\r\n") == std::string::npos) {
  18399. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18400. if (n <= 0) { break; }
  18401. req.append(buf, static_cast<size_t>(n));
  18402. }
  18403. if (req.compare(0, 7, "CONNECT") != 0) {
  18404. ::close(client_fd);
  18405. continue;
  18406. }
  18407. connect_hits_++;
  18408. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18409. ::send(client_fd, ok, std::strlen(ok), 0);
  18410. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18411. sockaddr_in o{};
  18412. o.sin_family = AF_INET;
  18413. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18414. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18415. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18416. 0) {
  18417. ::close(client_fd);
  18418. ::close(origin_fd);
  18419. continue;
  18420. }
  18421. auto forward = [](int from, int to) {
  18422. char b[8192];
  18423. for (;;) {
  18424. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18425. if (n <= 0) { break; }
  18426. ssize_t off = 0;
  18427. while (off < n) {
  18428. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18429. if (s <= 0) {
  18430. off = n;
  18431. break;
  18432. }
  18433. off += s;
  18434. }
  18435. }
  18436. ::shutdown(to, SHUT_WR);
  18437. };
  18438. std::thread t1([&] { forward(client_fd, origin_fd); });
  18439. std::thread t2([&] { forward(origin_fd, client_fd); });
  18440. t1.join();
  18441. t2.join();
  18442. ::close(client_fd);
  18443. ::close(origin_fd);
  18444. }
  18445. }
  18446. int forward_port_ = -1;
  18447. int listen_fd_ = -1;
  18448. int port_ = 0;
  18449. std::thread th_;
  18450. std::atomic<bool> stop_{false};
  18451. std::atomic<int> connect_hits_{0};
  18452. };
  18453. } // namespace proxy_tunnel_test
  18454. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18455. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18456. // retry; otherwise proxy creds would be sent to the origin.
  18457. std::atomic<int> origin_hits{0};
  18458. std::atomic<bool> origin_saw_proxy_authz{false};
  18459. proxy_tunnel_test::ScopedSSLServer origin;
  18460. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18461. origin_hits++;
  18462. if (req.has_header("Proxy-Authorization")) {
  18463. origin_saw_proxy_authz = true;
  18464. }
  18465. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18466. res.set_header("Proxy-Authenticate",
  18467. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18468. "algorithm=MD5");
  18469. });
  18470. origin.listen();
  18471. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18472. ASSERT_NE(0, proxy.port());
  18473. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18474. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18475. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18476. // and answer with its own status, making this test flaky.
  18477. SSLClient cli("127.0.0.1", origin.port());
  18478. cli.enable_server_certificate_verification(false);
  18479. cli.set_proxy("127.0.0.1", proxy.port());
  18480. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18481. auto res = cli.Get("/x");
  18482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18483. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18484. EXPECT_EQ(1, origin_hits.load());
  18485. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18486. EXPECT_EQ(1, proxy.connect_hits());
  18487. }
  18488. #endif