1
0

test.cc 633 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration: in split builds split.py strips `inline` and moves the
  361. // definition into httplib.cc, so detail::base64_encode is not visible from the
  362. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  363. // in both header-only and split builds.
  364. namespace httplib {
  365. namespace detail {
  366. std::string base64_encode(const std::string &in);
  367. } // namespace detail
  368. } // namespace httplib
  369. TEST(Base64EncodeTest, KnownAnswers) {
  370. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  371. // where the accumulator's top bit is already set before the next shift.
  372. EXPECT_EQ("", detail::base64_encode(""));
  373. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  374. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  375. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  376. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  377. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  378. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  379. // High bytes keep the top bit set across several rounds.
  380. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  381. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  382. }
  383. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  384. string unescapedCharacters = "-_.!~*'()";
  385. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  386. }
  387. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  388. string reservedCharacters = ";,/?:@&=+$";
  389. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  390. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  391. }
  392. TEST(ClientQueryOrder, PreserveOrder) {
  393. // This test reproduces Issue #2259: client may reorder query parameters
  394. // when sending a GET request. The expected behavior is that the client
  395. // preserves the original query string order when the caller supplied it
  396. // as part of the path.
  397. Server svr;
  398. svr.Get("/", [&](const Request &req, Response &res) {
  399. // Echo back the raw target so the test can assert ordering
  400. res.set_content(req.target, "text/plain");
  401. });
  402. std::thread t{[&] { svr.listen(HOST, PORT); }};
  403. auto se = detail::scope_exit([&] {
  404. svr.stop();
  405. t.join();
  406. ASSERT_FALSE(svr.is_running());
  407. });
  408. svr.wait_until_ready();
  409. Client cli(HOST, PORT);
  410. ASSERT_TRUE(cli.is_valid());
  411. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  412. auto res = cli.Get(original);
  413. ASSERT_TRUE(res);
  414. // Expect the echoed target to exactly match the original path (order
  415. // preserved)
  416. EXPECT_EQ(res->body, original);
  417. }
  418. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  425. "%D0%B4%D0%BE%D0%BC");
  426. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  427. }
  428. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  429. string unescapedCharacters = "-_.!~*'()";
  430. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  431. }
  432. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  433. string reservedCharacters = ";,/?:@&=+$";
  434. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  435. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  436. }
  437. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  438. string chineseCharacters = U8("中国語");
  439. string russianCharacters = U8("дом");
  440. string brazilianCharacters = U8("óculos");
  441. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  442. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  443. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  444. "%D0%B4%D0%BE%D0%BC");
  445. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  446. }
  447. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  448. // Issue #2082 use case: encoding path component with ampersand
  449. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  450. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  451. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  452. }
  453. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  454. string unescapedCharacters = "-_.!~*'()";
  455. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  456. }
  457. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  458. string reservedCharacters = ";,/?:@&=+$#";
  459. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  460. }
  461. TEST(EncodeUriTest, TestUTF8Characters) {
  462. string chineseCharacters = U8("中国語");
  463. string russianCharacters = U8("дом");
  464. string brazilianCharacters = U8("óculos");
  465. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  466. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  467. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriTest, TestCompleteUri) {
  471. string uri =
  472. "https://example.com/path/to/resource?query=value&param=test#fragment";
  473. EXPECT_EQ(
  474. httplib::encode_uri(uri),
  475. "https://example.com/path/to/resource?query=value&param=test#fragment");
  476. }
  477. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  478. string uri =
  479. "https://example.com/path with spaces/file name.html?q=hello world";
  480. EXPECT_EQ(httplib::encode_uri(uri),
  481. "https://example.com/path%20with%20spaces/"
  482. "file%20name.html?q=hello%20world");
  483. }
  484. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  485. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  486. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  487. }
  488. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  489. string unescapedCharacters = "-_.!~*'()";
  490. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  491. }
  492. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  493. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  494. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  495. string encodedBrazilian = "%C3%B3culos";
  496. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  497. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  498. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  499. }
  500. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  501. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  502. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  503. "Piri Tommy Villiers - on & on");
  504. }
  505. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  506. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  507. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  508. }
  509. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  510. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  511. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  512. }
  513. TEST(DecodeUriTest, TestUTF8Characters) {
  514. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  515. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  516. string encodedBrazilian = "%C3%B3culos";
  517. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  518. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  519. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  520. }
  521. TEST(DecodeUriTest, TestCompleteUri) {
  522. string encodedUri = "https://example.com/path%20with%20spaces/"
  523. "file%20name.html?q=hello%20world";
  524. EXPECT_EQ(
  525. httplib::decode_uri(encodedUri),
  526. "https://example.com/path with spaces/file name.html?q=hello world");
  527. }
  528. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  529. string original =
  530. "https://example.com/path with spaces/file name.html?q=hello world";
  531. string encoded = httplib::encode_uri(original);
  532. string decoded = httplib::decode_uri(encoded);
  533. EXPECT_EQ(decoded, original);
  534. }
  535. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  536. string original = "Piri Tommy Villiers - on & on";
  537. string encoded = httplib::encode_uri_component(original);
  538. string decoded = httplib::decode_uri_component(encoded);
  539. EXPECT_EQ(decoded, original);
  540. }
  541. TEST(TrimTests, TrimStringTests) {
  542. EXPECT_EQ("abc", detail::trim_copy("abc"));
  543. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  544. EXPECT_TRUE(detail::trim_copy("").empty());
  545. }
  546. TEST(AsciiTest, LocaleIndependentClassification) {
  547. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  548. // which consult the global C locale: std::isalnum(0xC5) can return true
  549. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  550. // helpers must classify every byte by the ASCII grammar alone.
  551. for (int i = 0; i < 256; i++) {
  552. auto c = static_cast<char>(i);
  553. auto is_digit = i >= '0' && i <= '9';
  554. auto is_upper = i >= 'A' && i <= 'Z';
  555. auto is_lower = i >= 'a' && i <= 'z';
  556. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  557. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  558. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  559. << "byte " << i;
  560. }
  561. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  562. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  563. // Non-ASCII bytes must be percent-encoded, never passed through as
  564. // alphanumeric.
  565. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  566. }
  567. TEST(FromCharsTest, Double) {
  568. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  569. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  570. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  571. auto parse = [](const std::string &s, double &v) {
  572. return detail::from_chars(s.data(), s.data() + s.size(), v);
  573. };
  574. double v = -1.0;
  575. // Representative quality values.
  576. EXPECT_EQ(parse("0", v).ec, std::errc{});
  577. EXPECT_DOUBLE_EQ(v, 0.0);
  578. EXPECT_EQ(parse("1", v).ec, std::errc{});
  579. EXPECT_DOUBLE_EQ(v, 1.0);
  580. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  581. EXPECT_DOUBLE_EQ(v, 0.8);
  582. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  583. EXPECT_DOUBLE_EQ(v, 0.001);
  584. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  585. EXPECT_DOUBLE_EQ(v, 1.0);
  586. // A missing integer or fractional part is tolerated.
  587. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  588. EXPECT_DOUBLE_EQ(v, 0.5);
  589. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  590. EXPECT_DOUBLE_EQ(v, 5.0);
  591. // Values outside [0, 1] still parse; the caller range-checks them.
  592. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  593. EXPECT_DOUBLE_EQ(v, 123.456);
  594. // Stops at the first byte that is not part of the number and reports where.
  595. std::string trailing = "0.9, text/html";
  596. auto r = parse(trailing, v);
  597. EXPECT_EQ(r.ec, std::errc{});
  598. EXPECT_DOUBLE_EQ(v, 0.9);
  599. EXPECT_EQ(*r.ptr, ',');
  600. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  601. // outright, and an 'e'/'E' simply ends the number.
  602. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  603. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  604. std::string exp_input = "1.5e3";
  605. r = parse(exp_input, v);
  606. EXPECT_EQ(r.ec, std::errc{});
  607. EXPECT_DOUBLE_EQ(v, 1.5);
  608. EXPECT_EQ(*r.ptr, 'e');
  609. // Invalid inputs.
  610. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  611. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  612. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  613. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  614. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  615. // Pathological but well-formed inputs must stay bounded (no overflow, no
  616. // out-of-bounds table access) and stay within [0, 1] for the caller.
  617. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  618. std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  621. std::errc{});
  622. EXPECT_GE(v, 0.0);
  623. EXPECT_LE(v, 1.0);
  624. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  625. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  626. }
  627. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  628. // Simple case without quality values
  629. std::vector<std::string> result1;
  630. EXPECT_TRUE(detail::parse_accept_header(
  631. "text/html,application/json,text/plain", result1));
  632. EXPECT_EQ(result1.size(), 3U);
  633. EXPECT_EQ(result1[0], "text/html");
  634. EXPECT_EQ(result1[1], "application/json");
  635. EXPECT_EQ(result1[2], "text/plain");
  636. // With quality values
  637. std::vector<std::string> result2;
  638. EXPECT_TRUE(detail::parse_accept_header(
  639. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  640. EXPECT_EQ(result2.size(), 3U);
  641. EXPECT_EQ(result2[0], "application/json"); // highest q value
  642. EXPECT_EQ(result2[1], "text/html");
  643. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  644. }
  645. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  646. // Mixed with and without quality values
  647. std::vector<std::string> result;
  648. EXPECT_TRUE(detail::parse_accept_header(
  649. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  650. EXPECT_EQ(result.size(), 3U);
  651. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  652. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  653. EXPECT_EQ(result[2], "application/json"); // q=0.5
  654. }
  655. TEST(ParseAcceptHeaderTest, EdgeCases) {
  656. // Empty header
  657. std::vector<std::string> empty_result;
  658. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  659. EXPECT_TRUE(empty_result.empty());
  660. // Single type
  661. std::vector<std::string> single_result;
  662. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  663. EXPECT_EQ(single_result.size(), 1U);
  664. EXPECT_EQ(single_result[0], "application/json");
  665. // Wildcard types
  666. std::vector<std::string> wildcard_result;
  667. EXPECT_TRUE(detail::parse_accept_header(
  668. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  669. EXPECT_EQ(wildcard_result.size(), 3U);
  670. EXPECT_EQ(wildcard_result[0], "application/json");
  671. EXPECT_EQ(wildcard_result[1], "text/*");
  672. EXPECT_EQ(wildcard_result[2], "*/*");
  673. }
  674. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  675. // Common browser Accept header
  676. std::vector<std::string> browser_result;
  677. EXPECT_TRUE(
  678. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  679. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  680. browser_result));
  681. EXPECT_EQ(browser_result.size(), 6U);
  682. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  683. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  684. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  685. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  686. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  687. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  688. // API client header
  689. std::vector<std::string> api_result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  692. api_result));
  693. EXPECT_EQ(api_result.size(), 3U);
  694. EXPECT_EQ(api_result[0], "application/json");
  695. EXPECT_EQ(api_result[1], "application/xml");
  696. EXPECT_EQ(api_result[2], "text/plain");
  697. }
  698. TEST(ParseAcceptHeaderTest, SpecialCases) {
  699. // Quality value with 3 decimal places
  700. std::vector<std::string> decimal_result;
  701. EXPECT_TRUE(detail::parse_accept_header(
  702. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  703. EXPECT_EQ(decimal_result.size(), 2U);
  704. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  705. EXPECT_EQ(decimal_result[1], "text/html");
  706. // Zero quality (should still be included but with lowest priority)
  707. std::vector<std::string> zero_q_result;
  708. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  709. zero_q_result));
  710. EXPECT_EQ(zero_q_result.size(), 2U);
  711. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  712. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  713. // No spaces around commas
  714. std::vector<std::string> no_space_result;
  715. EXPECT_TRUE(detail::parse_accept_header(
  716. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  717. no_space_result));
  718. EXPECT_EQ(no_space_result.size(), 3U);
  719. EXPECT_EQ(no_space_result[0], "text/html");
  720. EXPECT_EQ(no_space_result[1], "application/json");
  721. EXPECT_EQ(no_space_result[2], "text/plain");
  722. }
  723. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  724. // Quality values always use '.' as the decimal separator, so parsing must
  725. // not depend on the process locale. An embedding application may have
  726. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  727. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  728. std::string saved = cur ? cur : "C";
  729. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  730. "fr_FR.UTF-8"};
  731. bool switched = false;
  732. for (const auto loc : comma_locales) {
  733. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  734. std::localeconv()->decimal_point[0] == ',') {
  735. switched = true;
  736. break;
  737. }
  738. }
  739. if (!switched) {
  740. std::setlocale(LC_NUMERIC, saved.c_str());
  741. GTEST_SKIP() << "no comma-decimal locale available on this host";
  742. }
  743. // The higher-weighted type appears later in the list, so a correct parse
  744. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  745. // sensitive parse reads both weights as 0 and leaves the original order.
  746. std::vector<std::string> result;
  747. EXPECT_TRUE(detail::parse_accept_header(
  748. "application/json;q=0.1,text/html;q=0.9", result));
  749. ASSERT_EQ(result.size(), 2U);
  750. EXPECT_EQ(result[0], "text/html");
  751. EXPECT_EQ(result[1], "application/json");
  752. std::setlocale(LC_NUMERIC, saved.c_str());
  753. }
  754. TEST(ParseAcceptHeaderTest, InvalidCases) {
  755. std::vector<std::string> result;
  756. // Invalid quality value (> 1.0)
  757. EXPECT_FALSE(
  758. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  759. // Invalid quality value (< 0.0)
  760. EXPECT_FALSE(
  761. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  762. // Invalid quality value (not a number)
  763. EXPECT_FALSE(detail::parse_accept_header(
  764. "text/html;q=invalid,application/json", result));
  765. // Empty quality value
  766. EXPECT_FALSE(
  767. detail::parse_accept_header("text/html;q=,application/json", result));
  768. // Invalid media type format (no slash and not wildcard)
  769. EXPECT_FALSE(
  770. detail::parse_accept_header("invalidtype,application/json", result));
  771. // Empty media type
  772. result.clear();
  773. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  774. // Only commas
  775. result.clear();
  776. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  777. // Valid cases should still work
  778. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  779. EXPECT_EQ(result.size(), 1U);
  780. EXPECT_EQ(result[0], "*/*");
  781. EXPECT_TRUE(detail::parse_accept_header("*", result));
  782. EXPECT_EQ(result.size(), 1U);
  783. EXPECT_EQ(result[0], "*");
  784. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  785. EXPECT_EQ(result.size(), 1U);
  786. EXPECT_EQ(result[0], "text/*");
  787. }
  788. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  789. Server svr;
  790. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  791. EXPECT_EQ(req.accept_content_types.size(), 3U);
  792. EXPECT_EQ(req.accept_content_types[0], "application/json");
  793. EXPECT_EQ(req.accept_content_types[1], "text/html");
  794. EXPECT_EQ(req.accept_content_types[2], "*/*");
  795. res.set_content("ok", "text/plain");
  796. });
  797. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  798. EXPECT_TRUE(false);
  799. res.set_content("bad request", "text/plain");
  800. });
  801. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  802. auto se = detail::scope_exit([&] {
  803. svr.stop();
  804. listen_thread.join();
  805. ASSERT_FALSE(svr.is_running());
  806. });
  807. svr.wait_until_ready();
  808. Client cli("localhost", PORT);
  809. {
  810. auto res = cli.Get(
  811. "/accept_ok",
  812. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  813. ASSERT_TRUE(res);
  814. EXPECT_EQ(StatusCode::OK_200, res->status);
  815. }
  816. {
  817. auto res = cli.Get("/accept_bad_request",
  818. Headers{{"Accept", "text/html;q=abc,application/json"}});
  819. ASSERT_TRUE(res);
  820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  821. }
  822. }
  823. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  824. Server svr;
  825. svr.Get("/", [](const Request & /*req*/, Response &res) {
  826. res.set_content("ok", "text/plain");
  827. });
  828. std::atomic<int> start_count{0};
  829. std::atomic<bool> running_when_called{false};
  830. svr.set_start_handler([&]() {
  831. running_when_called = svr.is_running();
  832. start_count++;
  833. });
  834. auto port = svr.bind_to_any_port(HOST);
  835. std::thread t([&]() { svr.listen_after_bind(); });
  836. auto se = detail::scope_exit([&] {
  837. svr.stop();
  838. t.join();
  839. ASSERT_FALSE(svr.is_running());
  840. });
  841. svr.wait_until_ready();
  842. // A successful request proves the accept loop is running, which the start
  843. // handler precedes; so by now the handler must have run exactly once.
  844. Client cli(HOST, port);
  845. cli.set_connection_timeout(std::chrono::seconds(5));
  846. auto res = cli.Get("/");
  847. ASSERT_TRUE(res);
  848. EXPECT_EQ(StatusCode::OK_200, res->status);
  849. EXPECT_EQ(1, start_count.load());
  850. EXPECT_TRUE(running_when_called.load());
  851. }
  852. TEST(DivideTest, DivideStringTests) {
  853. auto divide = [](const std::string &str, char d) {
  854. std::string lhs;
  855. std::string rhs;
  856. detail::divide(str, d,
  857. [&](const char *lhs_data, std::size_t lhs_size,
  858. const char *rhs_data, std::size_t rhs_size) {
  859. lhs.assign(lhs_data, lhs_size);
  860. rhs.assign(rhs_data, rhs_size);
  861. });
  862. return std::make_pair(std::move(lhs), std::move(rhs));
  863. };
  864. {
  865. const auto res = divide("", '=');
  866. EXPECT_EQ(res.first, "");
  867. EXPECT_EQ(res.second, "");
  868. }
  869. {
  870. const auto res = divide("=", '=');
  871. EXPECT_EQ(res.first, "");
  872. EXPECT_EQ(res.second, "");
  873. }
  874. {
  875. const auto res = divide(" ", '=');
  876. EXPECT_EQ(res.first, " ");
  877. EXPECT_EQ(res.second, "");
  878. }
  879. {
  880. const auto res = divide("a", '=');
  881. EXPECT_EQ(res.first, "a");
  882. EXPECT_EQ(res.second, "");
  883. }
  884. {
  885. const auto res = divide("a=", '=');
  886. EXPECT_EQ(res.first, "a");
  887. EXPECT_EQ(res.second, "");
  888. }
  889. {
  890. const auto res = divide("=b", '=');
  891. EXPECT_EQ(res.first, "");
  892. EXPECT_EQ(res.second, "b");
  893. }
  894. {
  895. const auto res = divide("a=b", '=');
  896. EXPECT_EQ(res.first, "a");
  897. EXPECT_EQ(res.second, "b");
  898. }
  899. {
  900. const auto res = divide("a=b=", '=');
  901. EXPECT_EQ(res.first, "a");
  902. EXPECT_EQ(res.second, "b=");
  903. }
  904. {
  905. const auto res = divide("a=b=c", '=');
  906. EXPECT_EQ(res.first, "a");
  907. EXPECT_EQ(res.second, "b=c");
  908. }
  909. }
  910. TEST(SplitTest, ParseQueryString) {
  911. string s = "key1=val1&key2=val2&key3=val3";
  912. Params dic;
  913. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  914. [&](const char *b, const char *e) {
  915. string key, val;
  916. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  917. if (key.empty()) {
  918. key.assign(b2, e2);
  919. } else {
  920. val.assign(b2, e2);
  921. }
  922. });
  923. dic.emplace(key, val);
  924. });
  925. EXPECT_EQ("val1", dic.find("key1")->second);
  926. EXPECT_EQ("val2", dic.find("key2")->second);
  927. EXPECT_EQ("val3", dic.find("key3")->second);
  928. }
  929. TEST(SplitTest, ParseInvalidQueryTests) {
  930. {
  931. string s = " ";
  932. Params dict;
  933. detail::parse_query_text(s, dict);
  934. EXPECT_TRUE(dict.empty());
  935. }
  936. {
  937. string s = " = =";
  938. Params dict;
  939. detail::parse_query_text(s, dict);
  940. EXPECT_TRUE(dict.empty());
  941. }
  942. }
  943. TEST(ParseQueryTest, ParseQueryString) {
  944. {
  945. std::string s = "key1=val1&key2=val2&key3=val3";
  946. Params dic;
  947. detail::parse_query_text(s, dic);
  948. EXPECT_EQ("val1", dic.find("key1")->second);
  949. EXPECT_EQ("val2", dic.find("key2")->second);
  950. EXPECT_EQ("val3", dic.find("key3")->second);
  951. }
  952. {
  953. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  954. Params dic;
  955. detail::parse_query_text(s, dic);
  956. EXPECT_EQ("", dic.find("key1")->second);
  957. EXPECT_EQ("val1", dic.find("key2")->second);
  958. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  959. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  960. }
  961. }
  962. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  963. Params dic;
  964. EXPECT_EQ(detail::params_to_query_str(dic), "");
  965. dic.emplace("key1", "val1");
  966. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  967. dic.emplace("key2", "val2");
  968. dic.emplace("key3", "val3");
  969. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  970. }
  971. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  972. string content_type = "multipart/form-data; boundary=something";
  973. string boundary;
  974. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  975. EXPECT_TRUE(ret);
  976. EXPECT_EQ(boundary, "something");
  977. }
  978. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  979. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  980. string boundary;
  981. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  982. EXPECT_TRUE(ret);
  983. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  984. }
  985. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  986. string content_type =
  987. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  988. string boundary;
  989. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  990. EXPECT_TRUE(ret);
  991. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  992. }
  993. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  994. string content_type =
  995. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  996. string boundary;
  997. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  998. EXPECT_TRUE(ret);
  999. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1000. }
  1001. TEST(GetHeaderValueTest, DefaultValue) {
  1002. Headers headers = {{"Dummy", "Dummy"}};
  1003. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1004. EXPECT_STREQ("text/plain", val);
  1005. }
  1006. TEST(GetHeaderValueTest, DefaultValueInt) {
  1007. Headers headers = {{"Dummy", "Dummy"}};
  1008. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1009. EXPECT_EQ(100ull, val);
  1010. }
  1011. TEST(GetHeaderValueTest, RegularValue) {
  1012. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1013. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1014. EXPECT_STREQ("text/html", val);
  1015. }
  1016. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1017. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1018. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1019. EXPECT_STREQ("text/html", val);
  1020. }
  1021. TEST(GetHeaderValueTest, SetContent) {
  1022. Response res;
  1023. res.set_content("html", "text/html");
  1024. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1025. res.set_content("text", "text/plain");
  1026. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1027. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1028. }
  1029. TEST(GetHeaderValueTest, RegularValueInt) {
  1030. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1031. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1032. EXPECT_EQ(100ull, val);
  1033. }
  1034. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1035. Headers headers = {{"Content-Length", "x"}};
  1036. auto is_invalid_value = false;
  1037. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1038. is_invalid_value);
  1039. EXPECT_EQ(0ull, val);
  1040. EXPECT_TRUE(is_invalid_value);
  1041. }
  1042. TEST(GetHeaderValueTest, Range) {
  1043. {
  1044. Headers headers = {make_range_header({{1, -1}})};
  1045. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1046. EXPECT_STREQ("bytes=1-", val);
  1047. }
  1048. {
  1049. Headers headers = {make_range_header({{-1, 1}})};
  1050. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1051. EXPECT_STREQ("bytes=-1", val);
  1052. }
  1053. {
  1054. Headers headers = {make_range_header({{1, 10}})};
  1055. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1056. EXPECT_STREQ("bytes=1-10", val);
  1057. }
  1058. {
  1059. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1060. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1061. EXPECT_STREQ("bytes=1-10, 100-", val);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1065. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1066. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1067. }
  1068. {
  1069. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1070. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1071. EXPECT_STREQ("bytes=0-0, -1", val);
  1072. }
  1073. }
  1074. TEST(ParseHeaderValueTest, Range) {
  1075. {
  1076. Ranges ranges;
  1077. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1078. EXPECT_TRUE(ret);
  1079. EXPECT_EQ(1u, ranges.size());
  1080. EXPECT_EQ(1u, ranges[0].first);
  1081. EXPECT_EQ(-1, ranges[0].second);
  1082. }
  1083. {
  1084. Ranges ranges;
  1085. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1086. EXPECT_TRUE(ret);
  1087. EXPECT_EQ(1u, ranges.size());
  1088. EXPECT_EQ(-1, ranges[0].first);
  1089. EXPECT_EQ(1u, ranges[0].second);
  1090. }
  1091. {
  1092. Ranges ranges;
  1093. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1094. EXPECT_TRUE(ret);
  1095. EXPECT_EQ(1u, ranges.size());
  1096. EXPECT_EQ(1u, ranges[0].first);
  1097. EXPECT_EQ(10u, ranges[0].second);
  1098. }
  1099. {
  1100. Ranges ranges;
  1101. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1102. EXPECT_FALSE(ret);
  1103. }
  1104. {
  1105. Ranges ranges;
  1106. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1107. EXPECT_TRUE(ret);
  1108. EXPECT_EQ(2u, ranges.size());
  1109. EXPECT_EQ(1u, ranges[0].first);
  1110. EXPECT_EQ(10u, ranges[0].second);
  1111. EXPECT_EQ(100u, ranges[1].first);
  1112. EXPECT_EQ(-1, ranges[1].second);
  1113. }
  1114. {
  1115. Ranges ranges;
  1116. auto ret =
  1117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1118. EXPECT_TRUE(ret);
  1119. EXPECT_EQ(3u, ranges.size());
  1120. EXPECT_EQ(1u, ranges[0].first);
  1121. EXPECT_EQ(10u, ranges[0].second);
  1122. EXPECT_EQ(100u, ranges[1].first);
  1123. EXPECT_EQ(200u, ranges[1].second);
  1124. EXPECT_EQ(300u, ranges[2].first);
  1125. EXPECT_EQ(400u, ranges[2].second);
  1126. }
  1127. {
  1128. Ranges ranges;
  1129. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1130. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1131. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1132. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1133. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1134. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1135. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1136. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1137. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1138. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1139. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1140. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1141. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1142. EXPECT_TRUE(ranges.empty());
  1143. }
  1144. }
  1145. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1146. Request req;
  1147. req.set_header("Accept-Encoding", "gzip");
  1148. Response res;
  1149. res.set_header("Content-Type", "text/plain");
  1150. auto ret = detail::encoding_type(req, res);
  1151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1152. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1153. #else
  1154. EXPECT_TRUE(ret == detail::EncodingType::None);
  1155. #endif
  1156. }
  1157. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1158. Request req;
  1159. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1160. Response res;
  1161. res.set_header("Content-Type", "text/plain");
  1162. auto ret = detail::encoding_type(req, res);
  1163. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1164. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1165. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1167. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1168. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1169. #else
  1170. EXPECT_TRUE(ret == detail::EncodingType::None);
  1171. #endif
  1172. }
  1173. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1174. Request req;
  1175. req.set_header("Accept-Encoding",
  1176. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1177. Response res;
  1178. res.set_header("Content-Type", "text/plain");
  1179. auto ret = detail::encoding_type(req, res);
  1180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1181. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1182. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1183. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1184. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1185. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1186. #else
  1187. EXPECT_TRUE(ret == detail::EncodingType::None);
  1188. #endif
  1189. }
  1190. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1191. // All supported encodings rejected with q=0 should return None
  1192. Request req;
  1193. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1194. Response res;
  1195. res.set_header("Content-Type", "text/plain");
  1196. auto ret = detail::encoding_type(req, res);
  1197. EXPECT_TRUE(ret == detail::EncodingType::None);
  1198. }
  1199. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1200. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1201. Request req;
  1202. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1203. Response res;
  1204. res.set_header("Content-Type", "text/plain");
  1205. auto ret = detail::encoding_type(req, res);
  1206. EXPECT_TRUE(ret == detail::EncodingType::None);
  1207. }
  1208. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1209. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1210. Request req;
  1211. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1212. Response res;
  1213. res.set_header("Content-Type", "text/plain");
  1214. auto ret = detail::encoding_type(req, res);
  1215. EXPECT_TRUE(ret == detail::EncodingType::None);
  1216. }
  1217. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1218. // RFC 7231: Accept-Encoding values are case-insensitive
  1219. Request req;
  1220. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1221. Response res;
  1222. res.set_header("Content-Type", "text/plain");
  1223. auto ret = detail::encoding_type(req, res);
  1224. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1225. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1226. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1227. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1228. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1229. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1230. #else
  1231. EXPECT_TRUE(ret == detail::EncodingType::None);
  1232. #endif
  1233. }
  1234. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1235. // q value should determine priority, not hardcoded order
  1236. Request req;
  1237. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1238. Response res;
  1239. res.set_header("Content-Type", "text/plain");
  1240. auto ret = detail::encoding_type(req, res);
  1241. // gzip has highest q=1.0, so it should be selected even though
  1242. // br and zstd are also supported
  1243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1244. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1245. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1246. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1247. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1248. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1249. #else
  1250. EXPECT_TRUE(ret == detail::EncodingType::None);
  1251. #endif
  1252. }
  1253. TEST(BufferStreamTest, read) {
  1254. detail::BufferStream strm1;
  1255. Stream &strm = strm1;
  1256. EXPECT_EQ(5, strm.write("hello"));
  1257. char buf[512];
  1258. EXPECT_EQ(2, strm.read(buf, 2));
  1259. EXPECT_EQ('h', buf[0]);
  1260. EXPECT_EQ('e', buf[1]);
  1261. EXPECT_EQ(2, strm.read(buf, 2));
  1262. EXPECT_EQ('l', buf[0]);
  1263. EXPECT_EQ('l', buf[1]);
  1264. EXPECT_EQ(1, strm.read(buf, 1));
  1265. EXPECT_EQ('o', buf[0]);
  1266. EXPECT_EQ(0, strm.read(buf, 1));
  1267. }
  1268. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1269. auto host = "www.httpwatch.com";
  1270. auto ip = hosted_at(host);
  1271. EXPECT_EQ("23.96.13.243", ip);
  1272. std::vector<std::string> addrs;
  1273. hosted_at(host, addrs);
  1274. EXPECT_EQ(1u, addrs.size());
  1275. }
  1276. #if 0 // It depends on each test environment...
  1277. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1278. auto host = "www.youtube.com";
  1279. std::vector<std::string> addrs;
  1280. hosted_at(host, addrs);
  1281. EXPECT_EQ(20u, addrs.size());
  1282. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1283. EXPECT_TRUE(it != addrs.end());
  1284. }
  1285. #endif
  1286. class ChunkedEncodingTest : public ::testing::Test {
  1287. protected:
  1288. ChunkedEncodingTest()
  1289. : cli_(HOST, PORT)
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. ,
  1292. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1293. #endif
  1294. {
  1295. cli_.set_connection_timeout(2);
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. cli_.enable_server_certificate_verification(false);
  1298. #endif
  1299. }
  1300. virtual void SetUp() {
  1301. read_file("./image.jpg", image_data_);
  1302. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1303. res.set_content("Hello World!", "text/plain");
  1304. });
  1305. svr_.Get(
  1306. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1307. res.set_chunked_content_provider(
  1308. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1309. size_t remaining = image_data_.size() - offset;
  1310. if (remaining == 0) {
  1311. sink.done();
  1312. } else {
  1313. constexpr size_t CHUNK_SIZE = 1024;
  1314. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1315. sink.write(&image_data_[offset], send_size);
  1316. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1317. }
  1318. return true;
  1319. });
  1320. });
  1321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1322. svr_.wait_until_ready();
  1323. }
  1324. virtual void TearDown() {
  1325. svr_.stop();
  1326. if (!request_threads_.empty()) {
  1327. std::this_thread::sleep_for(std::chrono::seconds(1));
  1328. for (auto &t : request_threads_) {
  1329. t.join();
  1330. }
  1331. }
  1332. t_.join();
  1333. }
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. SSLClient cli_;
  1336. SSLServer svr_;
  1337. #else
  1338. Client cli_;
  1339. Server svr_;
  1340. #endif
  1341. thread t_;
  1342. std::vector<thread> request_threads_;
  1343. std::string image_data_;
  1344. };
  1345. TEST_F(ChunkedEncodingTest, NormalGet) {
  1346. auto res = cli_.Get("/chunked");
  1347. ASSERT_TRUE(res);
  1348. std::string out;
  1349. read_file("./image.jpg", out);
  1350. EXPECT_EQ(StatusCode::OK_200, res->status);
  1351. EXPECT_EQ(out, res->body);
  1352. }
  1353. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1354. std::string body;
  1355. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1356. body.append(data, data_length);
  1357. return true;
  1358. });
  1359. ASSERT_TRUE(res);
  1360. std::string out;
  1361. read_file("./image.jpg", out);
  1362. EXPECT_EQ(StatusCode::OK_200, res->status);
  1363. EXPECT_EQ(out, body);
  1364. }
  1365. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1366. std::string body;
  1367. auto res = cli_.Get(
  1368. "/chunked",
  1369. [&](const Response &response) {
  1370. EXPECT_EQ(StatusCode::OK_200, response.status);
  1371. return true;
  1372. },
  1373. [&](const char *data, size_t data_length) {
  1374. body.append(data, data_length);
  1375. return true;
  1376. });
  1377. ASSERT_TRUE(res);
  1378. std::string out;
  1379. read_file("./image.jpg", out);
  1380. EXPECT_EQ(StatusCode::OK_200, res->status);
  1381. EXPECT_EQ(out, body);
  1382. }
  1383. TEST(RangeTest, FromHTTPBin_Online) {
  1384. auto host = "httpbingo.org";
  1385. auto path = std::string{"/range/32"};
  1386. #ifdef CPPHTTPLIB_SSL_ENABLED
  1387. auto port = 443;
  1388. SSLClient cli(host, port);
  1389. #else
  1390. auto port = 80;
  1391. Client cli(host, port);
  1392. #endif
  1393. cli.set_connection_timeout(5);
  1394. {
  1395. auto res = cli.Get(path);
  1396. ASSERT_TRUE(res);
  1397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1398. EXPECT_EQ(StatusCode::OK_200, res->status);
  1399. }
  1400. {
  1401. Headers headers = {make_range_header({{1, -1}})};
  1402. auto res = cli.Get(path, headers);
  1403. ASSERT_TRUE(res);
  1404. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1406. }
  1407. {
  1408. Headers headers = {make_range_header({{1, 10}})};
  1409. auto res = cli.Get(path, headers);
  1410. ASSERT_TRUE(res);
  1411. EXPECT_EQ("bcdefghijk", res->body);
  1412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1413. }
  1414. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1415. // entire resource, while the original httpbin returned 200. Both are
  1416. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1417. {
  1418. Headers headers = {make_range_header({{0, 31}})};
  1419. auto res = cli.Get(path, headers);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1422. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1423. res->status == StatusCode::PartialContent_206);
  1424. }
  1425. {
  1426. Headers headers = {make_range_header({{0, -1}})};
  1427. auto res = cli.Get(path, headers);
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1430. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1431. res->status == StatusCode::PartialContent_206);
  1432. }
  1433. // go-httpbin returns 206 with clamped range for over-range requests,
  1434. // while the original httpbin returned 416. Both behaviors are observed
  1435. // in real servers, so we only verify the request succeeds.
  1436. {
  1437. Headers headers = {make_range_header({{0, 32}})};
  1438. auto res = cli.Get(path, headers);
  1439. ASSERT_TRUE(res);
  1440. }
  1441. }
  1442. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1443. auto host = "unresolvableaddress.local";
  1444. auto path = std::string{"/"};
  1445. #ifdef CPPHTTPLIB_SSL_ENABLED
  1446. auto port = 443;
  1447. SSLClient cli(host, port);
  1448. #else
  1449. auto port = 80;
  1450. Client cli(host, port);
  1451. #endif
  1452. cli.set_connection_timeout(1);
  1453. {
  1454. auto res = cli.Get(path);
  1455. ASSERT_FALSE(res);
  1456. }
  1457. std::this_thread::sleep_for(std::chrono::seconds(8));
  1458. }
  1459. #if defined(__linux__) && defined(__GLIBC__) && \
  1460. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1461. // Forward declaration: in split builds split.py strips `inline` and moves the
  1462. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1463. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1464. // against the symbol in both header-only and split builds.
  1465. namespace httplib {
  1466. namespace detail {
  1467. int getaddrinfo_with_timeout(const char *node, const char *service,
  1468. const struct addrinfo *hints,
  1469. struct addrinfo **res, time_t timeout_sec);
  1470. } // namespace detail
  1471. } // namespace httplib
  1472. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1473. //
  1474. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1475. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1476. // gai_suspend() call hits the connection timeout the function calls
  1477. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1478. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1479. // still alive and still references the now-destroyed stack frame.
  1480. //
  1481. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1482. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1483. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1484. // and runs them in a container.
  1485. namespace {
  1486. bool should_run_issue_2431_tests() {
  1487. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1488. return v && *v && std::string(v) != "0";
  1489. }
  1490. std::string unique_unresolvable_host(int n) {
  1491. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1492. // glibc still asks the configured nameserver — which is exactly the path
  1493. // we want to exercise. A unique label per call avoids the resolver cache.
  1494. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1495. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1496. std::to_string(n) + ".invalid";
  1497. }
  1498. } // namespace
  1499. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1500. if (!should_run_issue_2431_tests()) {
  1501. GTEST_SKIP()
  1502. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1503. }
  1504. for (int i = 0; i < 8; ++i) {
  1505. struct addrinfo hints;
  1506. memset(&hints, 0, sizeof(hints));
  1507. hints.ai_family = AF_UNSPEC;
  1508. hints.ai_socktype = SOCK_STREAM;
  1509. auto host = unique_unresolvable_host(i);
  1510. struct addrinfo *result = nullptr;
  1511. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1512. &result, /*timeout_sec=*/1);
  1513. if (rc == 0 && result) { freeaddrinfo(result); }
  1514. }
  1515. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1516. // stack region they still believe holds their gaicb.
  1517. std::this_thread::sleep_for(std::chrono::seconds(3));
  1518. }
  1519. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1520. if (!should_run_issue_2431_tests()) {
  1521. GTEST_SKIP()
  1522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1523. }
  1524. std::atomic<bool> stop{false};
  1525. std::vector<std::thread> threads;
  1526. for (int t = 0; t < 8; ++t) {
  1527. threads.emplace_back([t, &stop] {
  1528. int i = 0;
  1529. while (!stop.load(std::memory_order_relaxed)) {
  1530. struct addrinfo hints;
  1531. memset(&hints, 0, sizeof(hints));
  1532. hints.ai_family = AF_UNSPEC;
  1533. hints.ai_socktype = SOCK_STREAM;
  1534. auto host = unique_unresolvable_host(t * 100000 + i++);
  1535. struct addrinfo *result = nullptr;
  1536. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1537. &result, /*timeout_sec=*/1);
  1538. if (rc == 0 && result) { freeaddrinfo(result); }
  1539. }
  1540. });
  1541. }
  1542. std::this_thread::sleep_for(std::chrono::seconds(8));
  1543. stop.store(true, std::memory_order_relaxed);
  1544. for (auto &th : threads) {
  1545. th.join();
  1546. }
  1547. std::this_thread::sleep_for(std::chrono::seconds(3));
  1548. }
  1549. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1550. if (!should_run_issue_2431_tests()) {
  1551. GTEST_SKIP()
  1552. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1553. }
  1554. std::atomic<bool> stop{false};
  1555. std::vector<std::thread> threads;
  1556. for (int t = 0; t < 8; ++t) {
  1557. threads.emplace_back([t, &stop] {
  1558. int i = 0;
  1559. while (!stop.load(std::memory_order_relaxed)) {
  1560. auto host = unique_unresolvable_host(t * 100000 + i++);
  1561. Client cli(host, 80);
  1562. cli.set_connection_timeout(1, 0);
  1563. cli.set_read_timeout(1, 0);
  1564. cli.set_write_timeout(1, 0);
  1565. (void)cli.Get("/");
  1566. }
  1567. });
  1568. }
  1569. std::this_thread::sleep_for(std::chrono::seconds(8));
  1570. stop.store(true, std::memory_order_relaxed);
  1571. for (auto &th : threads) {
  1572. th.join();
  1573. }
  1574. std::this_thread::sleep_for(std::chrono::seconds(3));
  1575. }
  1576. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1577. TEST(ConnectionErrorTest, InvalidHost) {
  1578. auto host = "-abcde.com";
  1579. #ifdef CPPHTTPLIB_SSL_ENABLED
  1580. auto port = 443;
  1581. SSLClient cli(host, port);
  1582. #else
  1583. auto port = 80;
  1584. Client cli(host, port);
  1585. #endif
  1586. cli.set_connection_timeout(std::chrono::seconds(2));
  1587. auto res = cli.Get("/");
  1588. ASSERT_TRUE(!res);
  1589. EXPECT_EQ(Error::Connection, res.error());
  1590. }
  1591. TEST(ConnectionErrorTest, InvalidHost2) {
  1592. auto host = "httpcan.org/";
  1593. #ifdef CPPHTTPLIB_SSL_ENABLED
  1594. SSLClient cli(host);
  1595. #else
  1596. Client cli(host);
  1597. #endif
  1598. cli.set_connection_timeout(std::chrono::seconds(2));
  1599. auto res = cli.Get("/");
  1600. ASSERT_TRUE(!res);
  1601. EXPECT_EQ(Error::Connection, res.error());
  1602. }
  1603. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1604. auto host = "httpcan.org/";
  1605. #ifdef CPPHTTPLIB_SSL_ENABLED
  1606. SSLClient cli(host);
  1607. #else
  1608. Client cli(host);
  1609. #endif
  1610. cli.set_connection_timeout(std::chrono::seconds(2));
  1611. auto res = cli.Get("/");
  1612. ASSERT_TRUE(!res);
  1613. stringstream s;
  1614. s << "error code: " << res.error();
  1615. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1616. }
  1617. TEST(ConnectionErrorTest, InvalidPort) {
  1618. auto host = "localhost";
  1619. auto port = 44380;
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. SSLClient cli(host, port);
  1622. #else
  1623. Client cli(host, port);
  1624. #endif
  1625. cli.set_connection_timeout(std::chrono::seconds(2));
  1626. auto res = cli.Get("/");
  1627. ASSERT_TRUE(!res);
  1628. EXPECT_TRUE(Error::Connection == res.error() ||
  1629. Error::ConnectionTimeout == res.error());
  1630. }
  1631. TEST(ConnectionErrorTest, Timeout_Online) {
  1632. auto host = "google.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 44380;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 8080;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. // only probe one address type so that the error reason
  1642. // correlates to the timed-out IPv4, not the unsupported
  1643. // IPv6 connection attempt
  1644. cli.set_address_family(AF_INET);
  1645. auto res = cli.Get("/");
  1646. ASSERT_TRUE(!res);
  1647. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1648. }
  1649. TEST(CancelTest, NoCancel_Online) {
  1650. auto host = "httpbingo.org";
  1651. auto path = std::string{"/range/32"};
  1652. #ifdef CPPHTTPLIB_SSL_ENABLED
  1653. auto port = 443;
  1654. SSLClient cli(host, port);
  1655. #else
  1656. auto port = 80;
  1657. Client cli(host, port);
  1658. #endif
  1659. cli.set_connection_timeout(std::chrono::seconds(5));
  1660. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1661. ASSERT_TRUE(res);
  1662. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1663. EXPECT_EQ(StatusCode::OK_200, res->status);
  1664. }
  1665. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1666. // Use /bytes with a large payload so that the DownloadProgress callback
  1667. // (which only fires for Content-Length responses) is invoked before the
  1668. // entire body is received, giving cancellation a chance to fire.
  1669. auto host = "httpbingo.org";
  1670. auto path = std::string{"/bytes/524288"};
  1671. #ifdef CPPHTTPLIB_SSL_ENABLED
  1672. auto port = 443;
  1673. SSLClient cli(host, port);
  1674. #else
  1675. auto port = 80;
  1676. Client cli(host, port);
  1677. #endif
  1678. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1679. cli.set_connection_timeout(std::chrono::seconds(5));
  1680. ASSERT_TRUE(!res);
  1681. EXPECT_EQ(Error::Canceled, res.error());
  1682. }
  1683. TEST(CancelTest, WithCancelLargePayload_Online) {
  1684. auto host = "httpbingo.org";
  1685. auto path = std::string{"/bytes/524288"};
  1686. #ifdef CPPHTTPLIB_SSL_ENABLED
  1687. auto port = 443;
  1688. SSLClient cli(host, port);
  1689. #else
  1690. auto port = 80;
  1691. Client cli(host, port);
  1692. #endif
  1693. cli.set_connection_timeout(std::chrono::seconds(5));
  1694. uint32_t count = 0;
  1695. auto res =
  1696. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1697. ASSERT_TRUE(!res);
  1698. EXPECT_EQ(Error::Canceled, res.error());
  1699. }
  1700. TEST(CancelTest, NoCancelPost) {
  1701. Server svr;
  1702. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1703. res.set_content("Hello World!", "text/plain");
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. Client cli(HOST, PORT);
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res =
  1715. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1716. "application/json", [](uint64_t, uint64_t) { return true; });
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ("Hello World!", res->body);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. }
  1721. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1722. Server svr;
  1723. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1724. res.set_content("Hello World!", "text/plain");
  1725. });
  1726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. Client cli(HOST, PORT);
  1734. cli.set_connection_timeout(std::chrono::seconds(5));
  1735. auto res =
  1736. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1737. "application/json", [](uint64_t, uint64_t) { return false; });
  1738. ASSERT_TRUE(!res);
  1739. EXPECT_EQ(Error::Canceled, res.error());
  1740. }
  1741. TEST(CancelTest, WithCancelLargePayloadPost) {
  1742. Server svr;
  1743. svr.set_payload_max_length(200 * 1024 * 1024);
  1744. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1745. res.set_content(LARGE_DATA, "text/plain");
  1746. });
  1747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1748. auto se = detail::scope_exit([&] {
  1749. svr.stop();
  1750. thread.join();
  1751. ASSERT_FALSE(svr.is_running());
  1752. });
  1753. svr.wait_until_ready();
  1754. Client cli(HOST, PORT);
  1755. cli.set_payload_max_length(200 * 1024 * 1024);
  1756. cli.set_connection_timeout(std::chrono::seconds(5));
  1757. auto res =
  1758. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1759. "application/json", [](uint64_t, uint64_t) { return false; });
  1760. ASSERT_TRUE(!res);
  1761. EXPECT_EQ(Error::Canceled, res.error());
  1762. }
  1763. TEST(CancelTest, NoCancelPut) {
  1764. Server svr;
  1765. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1766. res.set_content("Hello World!", "text/plain");
  1767. });
  1768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1769. auto se = detail::scope_exit([&] {
  1770. svr.stop();
  1771. thread.join();
  1772. ASSERT_FALSE(svr.is_running());
  1773. });
  1774. svr.wait_until_ready();
  1775. Client cli(HOST, PORT);
  1776. cli.set_connection_timeout(std::chrono::seconds(5));
  1777. auto res =
  1778. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1779. "application/json", [](uint64_t, uint64_t) { return true; });
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ("Hello World!", res->body);
  1782. EXPECT_EQ(StatusCode::OK_200, res->status);
  1783. }
  1784. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1785. Server svr;
  1786. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1787. res.set_content("Hello World!", "text/plain");
  1788. });
  1789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1790. auto se = detail::scope_exit([&] {
  1791. svr.stop();
  1792. thread.join();
  1793. ASSERT_FALSE(svr.is_running());
  1794. });
  1795. svr.wait_until_ready();
  1796. Client cli(HOST, PORT);
  1797. cli.set_connection_timeout(std::chrono::seconds(5));
  1798. auto res =
  1799. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1800. "application/json", [](uint64_t, uint64_t) { return false; });
  1801. ASSERT_TRUE(!res);
  1802. EXPECT_EQ(Error::Canceled, res.error());
  1803. }
  1804. TEST(CancelTest, WithCancelLargePayloadPut) {
  1805. Server svr;
  1806. svr.set_payload_max_length(200 * 1024 * 1024);
  1807. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1808. res.set_content(LARGE_DATA, "text/plain");
  1809. });
  1810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1811. auto se = detail::scope_exit([&] {
  1812. svr.stop();
  1813. thread.join();
  1814. ASSERT_FALSE(svr.is_running());
  1815. });
  1816. svr.wait_until_ready();
  1817. Client cli(HOST, PORT);
  1818. cli.set_payload_max_length(200 * 1024 * 1024);
  1819. cli.set_connection_timeout(std::chrono::seconds(5));
  1820. auto res =
  1821. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1822. "application/json", [](uint64_t, uint64_t) { return false; });
  1823. ASSERT_TRUE(!res);
  1824. EXPECT_EQ(Error::Canceled, res.error());
  1825. }
  1826. TEST(CancelTest, NoCancelPatch) {
  1827. Server svr;
  1828. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1829. res.set_content("Hello World!", "text/plain");
  1830. });
  1831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. Client cli(HOST, PORT);
  1839. cli.set_connection_timeout(std::chrono::seconds(5));
  1840. auto res =
  1841. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1842. "application/json", [](uint64_t, uint64_t) { return true; });
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ("Hello World!", res->body);
  1845. EXPECT_EQ(StatusCode::OK_200, res->status);
  1846. }
  1847. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1848. Server svr;
  1849. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!", "text/plain");
  1851. });
  1852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1853. auto se = detail::scope_exit([&] {
  1854. svr.stop();
  1855. thread.join();
  1856. ASSERT_FALSE(svr.is_running());
  1857. });
  1858. svr.wait_until_ready();
  1859. Client cli(HOST, PORT);
  1860. cli.set_connection_timeout(std::chrono::seconds(5));
  1861. auto res =
  1862. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1863. "application/json", [](uint64_t, uint64_t) { return false; });
  1864. ASSERT_TRUE(!res);
  1865. EXPECT_EQ(Error::Canceled, res.error());
  1866. }
  1867. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1868. Server svr;
  1869. svr.set_payload_max_length(200 * 1024 * 1024);
  1870. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1871. res.set_content(LARGE_DATA, "text/plain");
  1872. });
  1873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1874. auto se = detail::scope_exit([&] {
  1875. svr.stop();
  1876. thread.join();
  1877. ASSERT_FALSE(svr.is_running());
  1878. });
  1879. svr.wait_until_ready();
  1880. Client cli(HOST, PORT);
  1881. cli.set_payload_max_length(200 * 1024 * 1024);
  1882. cli.set_connection_timeout(std::chrono::seconds(5));
  1883. auto res =
  1884. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1885. "application/json", [](uint64_t, uint64_t) { return false; });
  1886. ASSERT_TRUE(!res);
  1887. EXPECT_EQ(Error::Canceled, res.error());
  1888. }
  1889. TEST(CancelTest, NoCancelDelete) {
  1890. Server svr;
  1891. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1892. res.set_content("Hello World!", "text/plain");
  1893. });
  1894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1895. auto se = detail::scope_exit([&] {
  1896. svr.stop();
  1897. thread.join();
  1898. ASSERT_FALSE(svr.is_running());
  1899. });
  1900. svr.wait_until_ready();
  1901. Client cli(HOST, PORT);
  1902. cli.set_connection_timeout(std::chrono::seconds(5));
  1903. auto res =
  1904. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1905. "application/json", [](uint64_t, uint64_t) { return true; });
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("Hello World!", res->body);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. }
  1910. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1911. Server svr;
  1912. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. thread.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. Client cli(HOST, PORT);
  1923. cli.set_connection_timeout(std::chrono::seconds(5));
  1924. auto res =
  1925. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1926. "application/json", [](uint64_t, uint64_t) { return false; });
  1927. ASSERT_TRUE(!res);
  1928. EXPECT_EQ(Error::Canceled, res.error());
  1929. }
  1930. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1931. Server svr;
  1932. svr.set_payload_max_length(200 * 1024 * 1024);
  1933. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1934. res.set_content(LARGE_DATA, "text/plain");
  1935. });
  1936. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1937. auto se = detail::scope_exit([&] {
  1938. svr.stop();
  1939. thread.join();
  1940. ASSERT_FALSE(svr.is_running());
  1941. });
  1942. svr.wait_until_ready();
  1943. Client cli(HOST, PORT);
  1944. cli.set_payload_max_length(200 * 1024 * 1024);
  1945. cli.set_connection_timeout(std::chrono::seconds(5));
  1946. auto res =
  1947. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1948. "application/json", [](uint64_t, uint64_t) { return false; });
  1949. ASSERT_TRUE(!res);
  1950. EXPECT_EQ(Error::Canceled, res.error());
  1951. }
  1952. static std::string remove_whitespace(const std::string &input) {
  1953. std::string output;
  1954. output.reserve(input.size());
  1955. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1956. [](unsigned char c) { return !std::isspace(c); });
  1957. return output;
  1958. }
  1959. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1960. auto host = "httpbingo.org";
  1961. auto path = std::string{"/basic-auth/hello/world"};
  1962. #ifdef CPPHTTPLIB_SSL_ENABLED
  1963. auto port = 443;
  1964. SSLClient cli(host, port);
  1965. #else
  1966. auto port = 80;
  1967. Client cli(host, port);
  1968. #endif
  1969. {
  1970. auto res = cli.Get(path);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1973. }
  1974. {
  1975. auto res = cli.Get(
  1976. path, Headers{make_basic_authentication_header("hello", "world")});
  1977. ASSERT_TRUE(res);
  1978. auto body = remove_whitespace(res->body);
  1979. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1980. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. {
  1984. cli.set_basic_auth("hello", "world");
  1985. auto res = cli.Get(path);
  1986. ASSERT_TRUE(res);
  1987. auto body = remove_whitespace(res->body);
  1988. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1989. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1990. EXPECT_EQ(StatusCode::OK_200, res->status);
  1991. }
  1992. {
  1993. cli.set_basic_auth("hello", "bad");
  1994. auto res = cli.Get(path);
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1997. }
  1998. {
  1999. cli.set_basic_auth("bad", "world");
  2000. auto res = cli.Get(path);
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2003. }
  2004. }
  2005. #ifdef CPPHTTPLIB_SSL_ENABLED
  2006. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2007. auto host = "httpbingo.org";
  2008. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2009. auto paths = std::vector<std::string>{
  2010. "/digest-auth/auth/hello/world/MD5",
  2011. "/digest-auth/auth/hello/world/SHA-256",
  2012. };
  2013. auto port = 443;
  2014. SSLClient cli(host, port);
  2015. {
  2016. auto res = cli.Get(unauth_path);
  2017. ASSERT_TRUE(res);
  2018. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2019. }
  2020. {
  2021. cli.set_digest_auth("hello", "world");
  2022. for (const auto &path : paths) {
  2023. auto res = cli.Get(path.c_str());
  2024. ASSERT_TRUE(res);
  2025. auto body = remove_whitespace(res->body);
  2026. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2027. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. }
  2030. cli.set_digest_auth("hello", "bad");
  2031. for (const auto &path : paths) {
  2032. auto res = cli.Get(path.c_str());
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. }
  2037. }
  2038. #endif
  2039. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2040. auto host = "google.com";
  2041. auto another_host = "example.com";
  2042. auto wrong_ip = "0.0.0.0";
  2043. #ifdef CPPHTTPLIB_SSL_ENABLED
  2044. SSLClient cli(host);
  2045. #else
  2046. Client cli(host);
  2047. #endif
  2048. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2049. auto res = cli.Get("/");
  2050. ASSERT_TRUE(res);
  2051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2052. }
  2053. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2054. auto host = "google.com";
  2055. auto wrong_ip = "0.0.0.0";
  2056. #ifdef CPPHTTPLIB_SSL_ENABLED
  2057. SSLClient cli(host);
  2058. #else
  2059. Client cli(host);
  2060. #endif
  2061. cli.set_hostname_addr_map({{host, wrong_ip}});
  2062. auto res = cli.Get("/");
  2063. ASSERT_TRUE(!res);
  2064. EXPECT_EQ(Error::Connection, res.error());
  2065. }
  2066. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto path = std::string{"/absolute-redirect/3"};
  2069. #ifdef CPPHTTPLIB_SSL_ENABLED
  2070. SSLClient cli(host);
  2071. #else
  2072. Client cli(host);
  2073. #endif
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get(path);
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. }
  2079. TEST(RedirectTest, Redirect_Online) {
  2080. auto host = "httpbingo.org";
  2081. auto path = std::string{"/redirect/3"};
  2082. #ifdef CPPHTTPLIB_SSL_ENABLED
  2083. SSLClient cli(host);
  2084. #else
  2085. Client cli(host);
  2086. #endif
  2087. cli.set_follow_location(true);
  2088. auto res = cli.Get(path);
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. TEST(RelativeRedirectTest, Redirect_Online) {
  2093. auto host = "httpbingo.org";
  2094. auto path = std::string{"/relative-redirect/3"};
  2095. #ifdef CPPHTTPLIB_SSL_ENABLED
  2096. SSLClient cli(host);
  2097. #else
  2098. Client cli(host);
  2099. #endif
  2100. cli.set_follow_location(true);
  2101. auto res = cli.Get(path);
  2102. ASSERT_TRUE(res);
  2103. EXPECT_EQ(StatusCode::OK_200, res->status);
  2104. }
  2105. TEST(TooManyRedirectTest, Redirect_Online) {
  2106. auto host = "httpbingo.org";
  2107. auto path = std::string{"/redirect/21"};
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. SSLClient cli(host);
  2110. #else
  2111. Client cli(host);
  2112. #endif
  2113. cli.set_follow_location(true);
  2114. auto res = cli.Get(path);
  2115. ASSERT_TRUE(!res);
  2116. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2117. }
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. TEST(YahooRedirectTest, Redirect_Online) {
  2120. Client cli("yahoo.com");
  2121. auto res = cli.Get("/");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2124. cli.set_follow_location(true);
  2125. res = cli.Get("/");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2129. }
  2130. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2131. #define REDIR_HOST "httpbingo.org"
  2132. #define REDIR_PATH "/redirect-to"
  2133. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2134. SSLClient cli(REDIR_HOST);
  2135. cli.set_follow_location(true);
  2136. auto res =
  2137. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::OK_200, res->status);
  2140. }
  2141. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2142. SSLClient cli(REDIR_HOST);
  2143. cli.set_follow_location(true);
  2144. Params params;
  2145. params.emplace("url", "http://example.com");
  2146. params.emplace("status_code", "302");
  2147. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(StatusCode::OK_200, res->status);
  2150. }
  2151. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2152. SSLClient cli(REDIR_HOST);
  2153. cli.set_follow_location(true);
  2154. Params params;
  2155. params.emplace("url", "http://example.com");
  2156. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2157. ASSERT_TRUE(res);
  2158. EXPECT_EQ(StatusCode::OK_200, res->status);
  2159. }
  2160. TEST(UrlWithSpace, Redirect_Online) {
  2161. SSLClient cli("edge.forgecdn.net");
  2162. cli.set_follow_location(true);
  2163. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2167. }
  2168. #endif
  2169. #if !defined(_WIN32) && !defined(_WIN64)
  2170. TEST(ReceiveSignals, Signal) {
  2171. auto setupSignalHandlers = []() {
  2172. struct sigaction act;
  2173. sigemptyset(&act.sa_mask);
  2174. act.sa_flags = SA_SIGINFO;
  2175. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2176. switch (sig) {
  2177. case SIGINT:
  2178. default: break;
  2179. }
  2180. };
  2181. ::sigaction(SIGINT, &act, nullptr);
  2182. };
  2183. Server svr;
  2184. int port = 0;
  2185. auto thread = std::thread([&]() {
  2186. setupSignalHandlers();
  2187. port = svr.bind_to_any_port(HOST);
  2188. svr.listen_after_bind();
  2189. });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. ASSERT_TRUE(svr.is_running());
  2197. pthread_kill(thread.native_handle(), SIGINT);
  2198. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2199. ASSERT_TRUE(svr.is_running());
  2200. }
  2201. #endif
  2202. TEST(RedirectToDifferentPort, Redirect) {
  2203. Server svr1;
  2204. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2205. res.set_content("Hello World!", "text/plain");
  2206. });
  2207. int svr1_port = 0;
  2208. auto thread1 = std::thread([&]() {
  2209. svr1_port = svr1.bind_to_any_port(HOST);
  2210. svr1.listen_after_bind();
  2211. });
  2212. Server svr2;
  2213. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2214. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2215. });
  2216. int svr2_port = 0;
  2217. auto thread2 = std::thread([&]() {
  2218. svr2_port = svr2.bind_to_any_port(HOST);
  2219. svr2.listen_after_bind();
  2220. });
  2221. auto se = detail::scope_exit([&] {
  2222. svr2.stop();
  2223. thread2.join();
  2224. svr1.stop();
  2225. thread1.join();
  2226. ASSERT_FALSE(svr2.is_running());
  2227. ASSERT_FALSE(svr1.is_running());
  2228. });
  2229. svr1.wait_until_ready();
  2230. svr2.wait_until_ready();
  2231. Client cli("localhost", svr2_port);
  2232. cli.set_follow_location(true);
  2233. auto res = cli.Get("/2");
  2234. ASSERT_TRUE(res);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. EXPECT_EQ("Hello World!", res->body);
  2237. }
  2238. static void
  2239. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2240. Server svr1;
  2241. std::string captured_authorization;
  2242. svr1.Get("/target", [&](const Request &req, Response &res) {
  2243. captured_authorization = req.get_header_value("Authorization");
  2244. res.set_content("OK", "text/plain");
  2245. });
  2246. int svr1_port = 0;
  2247. auto thread1 = std::thread([&]() {
  2248. svr1_port = svr1.bind_to_any_port(HOST);
  2249. svr1.listen_after_bind();
  2250. });
  2251. Server svr2;
  2252. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2253. res.set_redirect(
  2254. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2255. });
  2256. int svr2_port = 0;
  2257. auto thread2 = std::thread([&]() {
  2258. svr2_port = svr2.bind_to_any_port(HOST);
  2259. svr2.listen_after_bind();
  2260. });
  2261. auto se = detail::scope_exit([&] {
  2262. svr2.stop();
  2263. thread2.join();
  2264. svr1.stop();
  2265. thread1.join();
  2266. ASSERT_FALSE(svr2.is_running());
  2267. ASSERT_FALSE(svr1.is_running());
  2268. });
  2269. svr1.wait_until_ready();
  2270. svr2.wait_until_ready();
  2271. Client cli("localhost", svr2_port);
  2272. cli.set_follow_location(true);
  2273. set_auth(cli);
  2274. auto res = cli.Get("/redir");
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2278. EXPECT_TRUE(captured_authorization.empty());
  2279. }
  2280. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2281. TestDoNotForwardCredentialsOnRedirect(
  2282. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2283. }
  2284. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2285. TestDoNotForwardCredentialsOnRedirect(
  2286. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2287. }
  2288. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2289. Server svr;
  2290. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2291. // Port number that overflows int — should not crash
  2292. res.set_redirect("http://localhost:99999999999999999999/target");
  2293. });
  2294. auto port = svr.bind_to_any_port(HOST);
  2295. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. Client cli(HOST, port);
  2303. cli.set_follow_location(true);
  2304. auto res = cli.Get("/redir");
  2305. // Should fail gracefully, not crash (no valid response due to bad port)
  2306. EXPECT_FALSE(res);
  2307. }
  2308. TEST(RedirectFromPageWithContent, Redirect) {
  2309. Server svr;
  2310. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2311. res.set_content("___", "text/plain");
  2312. res.set_redirect("/2");
  2313. });
  2314. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2315. res.set_content("Hello World!", "text/plain");
  2316. });
  2317. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2318. auto se = detail::scope_exit([&] {
  2319. svr.stop();
  2320. th.join();
  2321. ASSERT_FALSE(svr.is_running());
  2322. });
  2323. svr.wait_until_ready();
  2324. {
  2325. Client cli("localhost", PORT);
  2326. cli.set_follow_location(true);
  2327. std::string body;
  2328. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2329. body.append(data, data_length);
  2330. return true;
  2331. });
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::OK_200, res->status);
  2334. EXPECT_EQ("Hello World!", body);
  2335. }
  2336. {
  2337. Client cli("localhost", PORT);
  2338. std::string body;
  2339. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2340. body.append(data, data_length);
  2341. return true;
  2342. });
  2343. ASSERT_TRUE(res);
  2344. EXPECT_EQ(StatusCode::Found_302, res->status);
  2345. EXPECT_EQ("___", body);
  2346. }
  2347. }
  2348. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2349. Server svr;
  2350. auto port_str = std::to_string(PORT);
  2351. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2352. auto expected_host = "[::1]:" + port_str;
  2353. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2354. res.set_content("___", "text/plain");
  2355. // res.set_redirect("/2");
  2356. res.set_redirect(redirect_url);
  2357. });
  2358. svr.Get("/2", [&](const Request &req, Response &res) {
  2359. auto host_header = req.headers.find("Host");
  2360. ASSERT_TRUE(host_header != req.headers.end());
  2361. EXPECT_EQ(expected_host, host_header->second);
  2362. res.set_content("Hello World!", "text/plain");
  2363. });
  2364. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2365. auto se = detail::scope_exit([&] {
  2366. svr.stop();
  2367. th.join();
  2368. ASSERT_FALSE(svr.is_running());
  2369. });
  2370. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2371. // actually starts anything, so the condition !svr.is_running() will
  2372. // always remain true, and the loop never stops.
  2373. // This basically counts how many milliseconds have passed since the
  2374. // call to svr.listen(), and if after 5 seconds nothing started yet
  2375. // aborts the test.
  2376. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2377. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2378. ASSERT_LT(milliseconds, 5000U);
  2379. }
  2380. {
  2381. Client cli("::1", PORT);
  2382. cli.set_follow_location(true);
  2383. std::string body;
  2384. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2385. body.append(data, data_length);
  2386. return true;
  2387. });
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!", body);
  2391. }
  2392. {
  2393. Client cli("::1", PORT);
  2394. std::string body;
  2395. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2396. body.append(data, data_length);
  2397. return true;
  2398. });
  2399. ASSERT_TRUE(res);
  2400. EXPECT_EQ(StatusCode::Found_302, res->status);
  2401. EXPECT_EQ("___", body);
  2402. }
  2403. }
  2404. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2405. Server svr;
  2406. svr.Get("/foo", [](const Request &req, Response &res) {
  2407. auto a = req.params.find("a");
  2408. if (a != req.params.end()) {
  2409. res.set_content((*a).second, "text/plain");
  2410. res.status = StatusCode::OK_200;
  2411. } else {
  2412. res.status = StatusCode::BadRequest_400;
  2413. }
  2414. });
  2415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. {
  2423. Client cli(HOST, PORT);
  2424. cli.set_path_encode(false);
  2425. auto res = cli.Get("/foo?a=explicitly+encoded");
  2426. ASSERT_TRUE(res);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. // This expects it back with a space, as the `+` won't have been
  2429. // url-encoded, and server-side the params get decoded turning `+`
  2430. // into spaces.
  2431. EXPECT_EQ("explicitly encoded", res->body);
  2432. }
  2433. }
  2434. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2435. // When path encoding is disabled the client must transmit the supplied
  2436. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2437. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2438. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2439. // than a space (0x20). Assert on the raw wire target to catch this.
  2440. Server svr;
  2441. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2442. svr.Get("/foo", [&](const Request &req, Response &res) {
  2443. EXPECT_EQ(expected_target, req.target);
  2444. res.status = StatusCode::OK_200;
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. cli.set_path_encode(false);
  2456. auto res = cli.Get(expected_target.c_str());
  2457. ASSERT_TRUE(res);
  2458. EXPECT_EQ(StatusCode::OK_200, res->status);
  2459. }
  2460. }
  2461. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2462. Server svr;
  2463. svr.Get("/", [](const Request &req, Response &) {
  2464. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. {
  2474. Client cli(HOST, PORT);
  2475. cli.set_path_encode(false);
  2476. auto res = cli.Get("/?something=%0A");
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(StatusCode::OK_200, res->status);
  2479. }
  2480. }
  2481. TEST(BindServerTest, BindDualStack) {
  2482. Server svr;
  2483. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2484. res.set_content("Hello World!", "text/plain");
  2485. });
  2486. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2487. auto se = detail::scope_exit([&] {
  2488. svr.stop();
  2489. thread.join();
  2490. ASSERT_FALSE(svr.is_running());
  2491. });
  2492. svr.wait_until_ready();
  2493. {
  2494. Client cli("127.0.0.1", PORT);
  2495. auto res = cli.Get("/1");
  2496. ASSERT_TRUE(res);
  2497. EXPECT_EQ(StatusCode::OK_200, res->status);
  2498. EXPECT_EQ("Hello World!", res->body);
  2499. }
  2500. {
  2501. Client cli("::1", PORT);
  2502. auto res = cli.Get("/1");
  2503. ASSERT_TRUE(res);
  2504. EXPECT_EQ(StatusCode::OK_200, res->status);
  2505. EXPECT_EQ("Hello World!", res->body);
  2506. }
  2507. }
  2508. TEST(BindServerTest, BindAndListenSeparately) {
  2509. Server svr;
  2510. int port = svr.bind_to_any_port("0.0.0.0");
  2511. ASSERT_TRUE(svr.is_valid());
  2512. ASSERT_TRUE(port > 0);
  2513. svr.stop();
  2514. }
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2518. CLIENT_CA_CERT_DIR);
  2519. int port = svr.bind_to_any_port("0.0.0.0");
  2520. ASSERT_TRUE(svr.is_valid());
  2521. ASSERT_TRUE(port > 0);
  2522. svr.stop();
  2523. }
  2524. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2525. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2526. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2527. int port = svr.bind_to_any_port("0.0.0.0");
  2528. ASSERT_TRUE(svr.is_valid());
  2529. ASSERT_TRUE(port > 0);
  2530. svr.stop();
  2531. }
  2532. TEST(BindServerTest, UpdateCertsPem) {
  2533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2534. int port = svr.bind_to_any_port("0.0.0.0");
  2535. ASSERT_TRUE(svr.is_valid());
  2536. ASSERT_TRUE(port > 0);
  2537. // Read PEM files
  2538. std::string cert_pem, key_pem, ca_pem;
  2539. read_file(SERVER_CERT_FILE, cert_pem);
  2540. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2541. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2542. // Update server certificates using PEM API
  2543. ASSERT_TRUE(
  2544. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2545. ASSERT_TRUE(svr.is_valid());
  2546. svr.stop();
  2547. }
  2548. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2549. // Start server with client CA (enables client auth)
  2550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2551. ASSERT_TRUE(svr.is_valid());
  2552. bool handler_called = false;
  2553. svr.Get("/test", [&](const Request &req, Response &res) {
  2554. handler_called = true;
  2555. // Verify client certificate is present
  2556. auto cert = req.peer_cert();
  2557. EXPECT_TRUE(static_cast<bool>(cert));
  2558. res.set_content("ok", "text/plain");
  2559. });
  2560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2561. auto se = detail::scope_exit([&] {
  2562. svr.stop();
  2563. t.join();
  2564. ASSERT_FALSE(svr.is_running());
  2565. });
  2566. svr.wait_until_ready();
  2567. // Read PEM files
  2568. std::string cert_pem, key_pem, ca_pem;
  2569. read_file(SERVER_CERT_FILE, cert_pem);
  2570. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2571. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2572. // Update server certificates and client CA using PEM API while server running
  2573. ASSERT_TRUE(
  2574. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2575. // Connect with client certificate
  2576. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2577. cli.enable_server_certificate_verification(false);
  2578. cli.set_connection_timeout(30);
  2579. auto res = cli.Get("/test");
  2580. ASSERT_TRUE(res);
  2581. ASSERT_EQ(StatusCode::OK_200, res->status);
  2582. ASSERT_TRUE(handler_called);
  2583. EXPECT_EQ("ok", res->body);
  2584. }
  2585. #endif
  2586. TEST(ErrorHandlerTest, ContentLength) {
  2587. Server svr;
  2588. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2589. res.status = StatusCode::OK_200;
  2590. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2591. "text/html"); // <= Content-Length still 13
  2592. });
  2593. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2594. res.set_content("Hello World!\n", "text/plain");
  2595. res.status = 524;
  2596. });
  2597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2598. auto se = detail::scope_exit([&] {
  2599. svr.stop();
  2600. thread.join();
  2601. ASSERT_FALSE(svr.is_running());
  2602. });
  2603. svr.wait_until_ready();
  2604. {
  2605. Client cli(HOST, PORT);
  2606. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2607. ASSERT_TRUE(res);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2610. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2611. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2612. }
  2613. }
  2614. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2615. TEST(ExceptionTest, WithoutExceptionHandler) {
  2616. Server svr;
  2617. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2618. throw std::runtime_error("exception...");
  2619. });
  2620. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2621. throw std::runtime_error("exception\r\n...");
  2622. });
  2623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. listen_thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli("localhost", PORT);
  2631. {
  2632. auto res = cli.Get("/exception");
  2633. ASSERT_TRUE(res);
  2634. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2635. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2636. }
  2637. {
  2638. auto res = cli.Get("/unknown");
  2639. ASSERT_TRUE(res);
  2640. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2641. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2642. }
  2643. }
  2644. TEST(ExceptionTest, WithExceptionHandler) {
  2645. Server svr;
  2646. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2647. std::exception_ptr ep) {
  2648. EXPECT_FALSE(ep == nullptr);
  2649. try {
  2650. std::rethrow_exception(ep);
  2651. } catch (std::exception &e) {
  2652. EXPECT_EQ("abc", std::string(e.what()));
  2653. } catch (...) {}
  2654. res.status = StatusCode::InternalServerError_500;
  2655. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2656. "text/html"); // <= Content-Length still 13 at this point
  2657. });
  2658. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2659. res.set_content("Hello World!\n", "text/plain");
  2660. throw std::runtime_error("abc");
  2661. });
  2662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2663. auto se = detail::scope_exit([&] {
  2664. svr.stop();
  2665. thread.join();
  2666. ASSERT_FALSE(svr.is_running());
  2667. });
  2668. svr.wait_until_ready();
  2669. for (size_t i = 0; i < 10; i++) {
  2670. Client cli(HOST, PORT);
  2671. for (size_t j = 0; j < 100; j++) {
  2672. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2673. ASSERT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2675. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2676. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2677. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2678. }
  2679. cli.set_keep_alive(true);
  2680. for (size_t j = 0; j < 100; j++) {
  2681. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2684. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2685. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2686. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2687. }
  2688. }
  2689. }
  2690. TEST(ExceptionTest, AndErrorHandler) {
  2691. Server svr;
  2692. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2693. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2694. });
  2695. svr.set_exception_handler(
  2696. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2697. EXPECT_FALSE(ep == nullptr);
  2698. try {
  2699. std::rethrow_exception(ep);
  2700. } catch (std::exception &e) {
  2701. res.set_content(e.what(), "text/html");
  2702. } catch (...) {}
  2703. res.status = StatusCode::InternalServerError_500;
  2704. });
  2705. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2706. throw std::runtime_error("EXCEPTION");
  2707. });
  2708. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2709. res.set_content("ERROR", "text/html");
  2710. res.status = StatusCode::InternalServerError_500;
  2711. });
  2712. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. thread.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. svr.wait_until_ready();
  2719. Client cli(HOST, PORT);
  2720. {
  2721. auto res = cli.Get("/exception");
  2722. ASSERT_TRUE(res);
  2723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2724. EXPECT_EQ("EXCEPTION", res->body);
  2725. }
  2726. {
  2727. auto res = cli.Get("/error");
  2728. ASSERT_TRUE(res);
  2729. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2730. EXPECT_EQ("ERROR", res->body);
  2731. }
  2732. {
  2733. auto res = cli.Get("/invalid");
  2734. ASSERT_TRUE(res);
  2735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2736. EXPECT_EQ("NOT_FOUND", res->body);
  2737. }
  2738. }
  2739. #endif
  2740. TEST(NoContentTest, ContentLength) {
  2741. Server svr;
  2742. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2743. res.status = StatusCode::NoContent_204;
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. {
  2753. Client cli(HOST, PORT);
  2754. auto res = cli.Get("/hi");
  2755. ASSERT_TRUE(res);
  2756. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2757. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2758. }
  2759. }
  2760. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2763. ASSERT_TRUE(svr.is_valid());
  2764. #else
  2765. Server svr;
  2766. #endif
  2767. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2768. if (req.path == "/routing_handler") {
  2769. res.set_header("PRE_ROUTING", "on");
  2770. res.set_content("Routing Handler", "text/plain");
  2771. return httplib::Server::HandlerResponse::Handled;
  2772. }
  2773. return httplib::Server::HandlerResponse::Unhandled;
  2774. });
  2775. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2776. res.set_content("Error", "text/html");
  2777. });
  2778. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2779. if (req.path == "/routing_handler") {
  2780. res.set_header("POST_ROUTING", "on");
  2781. }
  2782. });
  2783. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!\n", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. {
  2794. #ifdef CPPHTTPLIB_SSL_ENABLED
  2795. SSLClient cli(HOST, PORT);
  2796. cli.enable_server_certificate_verification(false);
  2797. #else
  2798. Client cli(HOST, PORT);
  2799. #endif
  2800. auto res = cli.Get("/routing_handler");
  2801. ASSERT_TRUE(res);
  2802. EXPECT_EQ(StatusCode::OK_200, res->status);
  2803. EXPECT_EQ("Routing Handler", res->body);
  2804. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2805. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2806. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2807. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2808. }
  2809. {
  2810. #ifdef CPPHTTPLIB_SSL_ENABLED
  2811. SSLClient cli(HOST, PORT);
  2812. cli.enable_server_certificate_verification(false);
  2813. #else
  2814. Client cli(HOST, PORT);
  2815. #endif
  2816. auto res = cli.Get("/hi");
  2817. ASSERT_TRUE(res);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. EXPECT_EQ("Hello World!\n", res->body);
  2820. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2821. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2822. }
  2823. {
  2824. #ifdef CPPHTTPLIB_SSL_ENABLED
  2825. SSLClient cli(HOST, PORT);
  2826. cli.enable_server_certificate_verification(false);
  2827. #else
  2828. Client cli(HOST, PORT);
  2829. #endif
  2830. auto res = cli.Get("/aaa");
  2831. ASSERT_TRUE(res);
  2832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2833. EXPECT_EQ("Error", res->body);
  2834. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2835. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2836. }
  2837. }
  2838. TEST(RequestHandlerTest, PreRequestHandler) {
  2839. auto route_path = "/user/:user";
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request &, Response &res) {
  2842. res.set_content("hi", "text/plain");
  2843. });
  2844. svr.Get(route_path, [](const Request &req, Response &res) {
  2845. res.set_content(req.path_params.at("user"), "text/plain");
  2846. });
  2847. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2848. if (req.matched_route == route_path) {
  2849. auto user = req.path_params.at("user");
  2850. if (user != "john") {
  2851. res.status = StatusCode::Forbidden_403;
  2852. res.set_content("error", "text/html");
  2853. return Server::HandlerResponse::Handled;
  2854. }
  2855. }
  2856. return Server::HandlerResponse::Unhandled;
  2857. });
  2858. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. Client cli(HOST, PORT);
  2866. {
  2867. auto res = cli.Get("/hi");
  2868. ASSERT_TRUE(res);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. EXPECT_EQ("hi", res->body);
  2871. }
  2872. {
  2873. auto res = cli.Get("/user/john");
  2874. ASSERT_TRUE(res);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. EXPECT_EQ("john", res->body);
  2877. }
  2878. {
  2879. auto res = cli.Get("/user/invalid-user");
  2880. ASSERT_TRUE(res);
  2881. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2882. EXPECT_EQ("error", res->body);
  2883. }
  2884. }
  2885. // The pre-request handler must run before the request body is read, so a
  2886. // rejected request never forces the server to buffer a (potentially large)
  2887. // body. Here the posted body is larger than the payload limit: if the body
  2888. // were read first the server would answer 413, but because the pre-request
  2889. // handler runs first it answers 403 and the body is never read.
  2890. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2891. Server svr;
  2892. svr.set_payload_max_length(8);
  2893. auto handler_ran = false;
  2894. svr.Post("/reject", [&](const Request &req, Response &res) {
  2895. handler_ran = true;
  2896. res.set_content(req.body, "text/plain");
  2897. });
  2898. svr.Post("/accept", [](const Request &req, Response &res) {
  2899. res.set_content(req.body, "text/plain");
  2900. });
  2901. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2902. if (req.matched_route == "/reject") {
  2903. res.status = StatusCode::Forbidden_403;
  2904. res.set_content("denied", "text/plain");
  2905. return Server::HandlerResponse::Handled;
  2906. }
  2907. return Server::HandlerResponse::Unhandled;
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2918. // rejects with 403 before the body is read, so 413 is never reached.
  2919. {
  2920. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2923. EXPECT_EQ("denied", res->body);
  2924. EXPECT_FALSE(handler_ran);
  2925. }
  2926. // An approved route still reads the body and enforces the payload limit.
  2927. {
  2928. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2929. ASSERT_TRUE(res);
  2930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2931. }
  2932. }
  2933. TEST(UserDataTest, BasicOperations) {
  2934. httplib::UserData ud;
  2935. // Initially empty
  2936. EXPECT_FALSE(ud.has("key"));
  2937. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2938. // set and get
  2939. ud.set("key", 42);
  2940. EXPECT_TRUE(ud.has("key"));
  2941. auto *p = ud.get<int>("key");
  2942. ASSERT_NE(nullptr, p);
  2943. EXPECT_EQ(42, *p);
  2944. // Type mismatch → nullptr
  2945. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2946. // Overwrite with different type
  2947. ud.set("key", std::string("hello"));
  2948. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2949. auto *s = ud.get<std::string>("key");
  2950. ASSERT_NE(nullptr, s);
  2951. EXPECT_EQ("hello", *s);
  2952. // erase
  2953. ud.erase("key");
  2954. EXPECT_FALSE(ud.has("key"));
  2955. // clear
  2956. ud.set("a", 1);
  2957. ud.set("b", 2);
  2958. ud.clear();
  2959. EXPECT_FALSE(ud.has("a"));
  2960. EXPECT_FALSE(ud.has("b"));
  2961. }
  2962. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2963. struct AuthCtx {
  2964. std::string user_id;
  2965. };
  2966. Server svr;
  2967. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2968. res.user_data.set("auth", AuthCtx{"alice"});
  2969. return Server::HandlerResponse::Unhandled;
  2970. });
  2971. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2972. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2973. ASSERT_NE(nullptr, ctx);
  2974. res.set_content("Hello " + ctx->user_id, "text/plain");
  2975. });
  2976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. thread.join();
  2980. ASSERT_FALSE(svr.is_running());
  2981. });
  2982. svr.wait_until_ready();
  2983. Client cli(HOST, PORT);
  2984. auto res = cli.Get("/me");
  2985. ASSERT_TRUE(res);
  2986. EXPECT_EQ(StatusCode::OK_200, res->status);
  2987. EXPECT_EQ("Hello alice", res->body);
  2988. }
  2989. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2990. struct RoleCtx {
  2991. std::string role;
  2992. };
  2993. Server svr;
  2994. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2995. res.user_data.set("role", RoleCtx{"admin"});
  2996. return Server::HandlerResponse::Unhandled;
  2997. });
  2998. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2999. auto *ctx = res.user_data.get<RoleCtx>("role");
  3000. ASSERT_NE(nullptr, ctx);
  3001. res.set_content(ctx->role, "text/plain");
  3002. });
  3003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3004. auto se = detail::scope_exit([&] {
  3005. svr.stop();
  3006. thread.join();
  3007. ASSERT_FALSE(svr.is_running());
  3008. });
  3009. svr.wait_until_ready();
  3010. Client cli(HOST, PORT);
  3011. auto res = cli.Get("/role");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. EXPECT_EQ("admin", res->body);
  3015. }
  3016. TEST(InvalidFormatTest, StatusCode) {
  3017. Server svr;
  3018. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3019. res.set_content("Hello World!\n", "text/plain");
  3020. res.status = 9999; // Status should be a three-digit code...
  3021. });
  3022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3023. auto se = detail::scope_exit([&] {
  3024. svr.stop();
  3025. thread.join();
  3026. ASSERT_FALSE(svr.is_running());
  3027. });
  3028. svr.wait_until_ready();
  3029. {
  3030. Client cli(HOST, PORT);
  3031. auto res = cli.Get("/hi");
  3032. ASSERT_FALSE(res);
  3033. }
  3034. }
  3035. TEST(URLFragmentTest, WithFragment) {
  3036. Server svr;
  3037. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3038. EXPECT_TRUE(req.target == "/hi");
  3039. });
  3040. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3041. auto se = detail::scope_exit([&] {
  3042. svr.stop();
  3043. thread.join();
  3044. ASSERT_FALSE(svr.is_running());
  3045. });
  3046. svr.wait_until_ready();
  3047. {
  3048. Client cli(HOST, PORT);
  3049. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3050. EXPECT_TRUE(res);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. res = cli.Get("/hi%23key1=val1=key2=val2");
  3053. EXPECT_TRUE(res);
  3054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3055. }
  3056. }
  3057. TEST(HeaderWriter, SetHeaderWriter) {
  3058. Server svr;
  3059. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3060. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3061. return detail::write_headers(strm, hdrs);
  3062. });
  3063. svr.Get("/hi", [](const Request &req, Response &res) {
  3064. auto it = req.headers.find("CustomClientHeader");
  3065. EXPECT_TRUE(it != req.headers.end());
  3066. EXPECT_EQ(it->second, "CustomClientValue");
  3067. res.set_content("Hello World!\n", "text/plain");
  3068. });
  3069. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  3078. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3079. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3080. return detail::write_headers(strm, hdrs);
  3081. });
  3082. auto res = cli.Get("/hi");
  3083. EXPECT_TRUE(res);
  3084. EXPECT_EQ(StatusCode::OK_200, res->status);
  3085. auto it = res->headers.find("CustomServerHeader");
  3086. EXPECT_TRUE(it != res->headers.end());
  3087. EXPECT_EQ(it->second, "CustomServerValue");
  3088. }
  3089. }
  3090. class ServerTest : public ::testing::Test {
  3091. protected:
  3092. ServerTest()
  3093. : cli_(HOST, PORT)
  3094. #ifdef CPPHTTPLIB_SSL_ENABLED
  3095. ,
  3096. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3097. #endif
  3098. {
  3099. #ifdef CPPHTTPLIB_SSL_ENABLED
  3100. cli_.enable_server_certificate_verification(false);
  3101. #endif
  3102. // Allow LARGE_DATA (100MB) responses
  3103. cli_.set_payload_max_length(200 * 1024 * 1024);
  3104. }
  3105. virtual void SetUp() {
  3106. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3107. svr_.set_payload_max_length(200 * 1024 * 1024);
  3108. svr_.set_mount_point("/", "./www");
  3109. svr_.set_mount_point("/mount", "./www2");
  3110. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3111. svr_.Get("/hi",
  3112. [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. })
  3115. .Get("/file_content",
  3116. [&](const Request & /*req*/, Response &res) {
  3117. res.set_file_content("./www/dir/test.html");
  3118. })
  3119. .Get("/file_content_with_content_type",
  3120. [&](const Request & /*req*/, Response &res) {
  3121. res.set_file_content("./www/file", "text/plain");
  3122. })
  3123. .Get("/invalid_file_content",
  3124. [&](const Request & /*req*/, Response &res) {
  3125. res.set_file_content("./www/dir/invalid_file_path");
  3126. })
  3127. .Get("/http_response_splitting",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3130. EXPECT_EQ(0U, res.headers.size());
  3131. EXPECT_FALSE(res.has_header("a"));
  3132. res.set_header("a", "1\nSet-Cookie: a=1");
  3133. EXPECT_EQ(0U, res.headers.size());
  3134. EXPECT_FALSE(res.has_header("a"));
  3135. res.set_header("a", "1\rSet-Cookie: a=1");
  3136. EXPECT_EQ(0U, res.headers.size());
  3137. EXPECT_FALSE(res.has_header("a"));
  3138. res.set_header("a\r\nb", "0");
  3139. EXPECT_EQ(0U, res.headers.size());
  3140. EXPECT_FALSE(res.has_header("a"));
  3141. res.set_header("a\rb", "0");
  3142. EXPECT_EQ(0U, res.headers.size());
  3143. EXPECT_FALSE(res.has_header("a"));
  3144. res.set_header("a\nb", "0");
  3145. EXPECT_EQ(0U, res.headers.size());
  3146. EXPECT_FALSE(res.has_header("a"));
  3147. res.set_redirect("1\r\nSet-Cookie: a=1");
  3148. EXPECT_EQ(0U, res.headers.size());
  3149. EXPECT_FALSE(res.has_header("Location"));
  3150. })
  3151. .Get("/slow",
  3152. [&](const Request & /*req*/, Response &res) {
  3153. std::this_thread::sleep_for(std::chrono::seconds(4));
  3154. res.set_content("slow", "text/plain");
  3155. })
  3156. #if 0
  3157. .Post("/slowpost",
  3158. [&](const Request & /*req*/, Response &res) {
  3159. std::this_thread::sleep_for(std::chrono::seconds(2));
  3160. res.set_content("slow", "text/plain");
  3161. })
  3162. #endif
  3163. .Get("/remote_addr",
  3164. [&](const Request &req, Response &res) {
  3165. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3166. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3167. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3168. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3169. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3170. #endif
  3171. res.set_content(req.remote_addr, "text/plain");
  3172. })
  3173. .Get("/local_addr",
  3174. [&](const Request &req, Response &res) {
  3175. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3176. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3178. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3179. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3180. #endif
  3181. auto local_addr = req.local_addr;
  3182. auto local_port = std::to_string(req.local_port);
  3183. res.set_content(local_addr.append(":").append(local_port),
  3184. "text/plain");
  3185. })
  3186. .Get("/endwith%",
  3187. [&](const Request & /*req*/, Response &res) {
  3188. res.set_content("Hello World!", "text/plain");
  3189. })
  3190. .Get("/a\\+\\+b",
  3191. [&](const Request &req, Response &res) {
  3192. ASSERT_TRUE(req.has_param("a +b"));
  3193. auto val = req.get_param_value("a +b");
  3194. res.set_content(val, "text/plain");
  3195. })
  3196. .Get("/", [&](const Request & /*req*/,
  3197. Response &res) { res.set_redirect("/hi"); })
  3198. .Post("/1",
  3199. [](const Request & /*req*/, Response &res) {
  3200. res.set_redirect("/2", StatusCode::SeeOther_303);
  3201. })
  3202. .Get("/2",
  3203. [](const Request & /*req*/, Response &res) {
  3204. res.set_content("redirected.", "text/plain");
  3205. res.status = StatusCode::OK_200;
  3206. })
  3207. .Post("/person",
  3208. [&](const Request &req, Response &res) {
  3209. if (req.has_param("name") && req.has_param("note")) {
  3210. persons_[req.get_param_value("name")] =
  3211. req.get_param_value("note");
  3212. } else {
  3213. res.status = StatusCode::BadRequest_400;
  3214. }
  3215. })
  3216. .Put("/person",
  3217. [&](const Request &req, Response &res) {
  3218. if (req.has_param("name") && req.has_param("note")) {
  3219. persons_[req.get_param_value("name")] =
  3220. req.get_param_value("note");
  3221. } else {
  3222. res.status = StatusCode::BadRequest_400;
  3223. }
  3224. })
  3225. .Get("/person/(.*)",
  3226. [&](const Request &req, Response &res) {
  3227. string name = req.matches[1];
  3228. if (persons_.find(name) != persons_.end()) {
  3229. auto note = persons_[name];
  3230. res.set_content(note, "text/plain");
  3231. } else {
  3232. res.status = StatusCode::NotFound_404;
  3233. }
  3234. })
  3235. .Delete("/person",
  3236. [&](const Request &req, Response &res) {
  3237. if (req.has_param("name")) {
  3238. string name = req.get_param_value("name");
  3239. if (persons_.find(name) != persons_.end()) {
  3240. persons_.erase(name);
  3241. res.set_content("DELETED", "text/plain");
  3242. } else {
  3243. res.status = StatusCode::NotFound_404;
  3244. }
  3245. } else {
  3246. res.status = StatusCode::BadRequest_400;
  3247. }
  3248. })
  3249. .Post("/x-www-form-urlencoded-json",
  3250. [&](const Request &req, Response &res) {
  3251. auto json = req.get_param_value("json");
  3252. ASSERT_EQ(JSON_DATA, json);
  3253. res.set_content(json, "appliation/json");
  3254. res.status = StatusCode::OK_200;
  3255. })
  3256. .Get("/streamed-chunked",
  3257. [&](const Request & /*req*/, Response &res) {
  3258. res.set_chunked_content_provider(
  3259. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3260. sink.os << "123";
  3261. sink.os << "456";
  3262. sink.os << "789";
  3263. sink.done();
  3264. return true;
  3265. });
  3266. })
  3267. .Get("/streamed-chunked-with-prohibited-trailer",
  3268. [&](const Request & /*req*/, Response &res) {
  3269. auto i = new int(0);
  3270. // Declare both a prohibited trailer (Content-Length) and an
  3271. // allowed one
  3272. res.set_header("Trailer", "Content-Length, X-Allowed");
  3273. res.set_chunked_content_provider(
  3274. "text/plain",
  3275. [i](size_t /*offset*/, DataSink &sink) {
  3276. switch (*i) {
  3277. case 0: sink.os << "123"; break;
  3278. case 1: sink.os << "456"; break;
  3279. case 2: sink.os << "789"; break;
  3280. case 3: {
  3281. sink.done_with_trailer(
  3282. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3283. } break;
  3284. }
  3285. (*i)++;
  3286. return true;
  3287. },
  3288. [i](bool success) {
  3289. EXPECT_TRUE(success);
  3290. delete i;
  3291. });
  3292. })
  3293. .Get("/streamed-chunked2",
  3294. [&](const Request & /*req*/, Response &res) {
  3295. auto i = new int(0);
  3296. res.set_chunked_content_provider(
  3297. "text/plain",
  3298. [i](size_t /*offset*/, DataSink &sink) {
  3299. switch (*i) {
  3300. case 0: sink.os << "123"; break;
  3301. case 1: sink.os << "456"; break;
  3302. case 2: sink.os << "789"; break;
  3303. case 3: sink.done(); break;
  3304. }
  3305. (*i)++;
  3306. return true;
  3307. },
  3308. [i](bool success) {
  3309. EXPECT_TRUE(success);
  3310. delete i;
  3311. });
  3312. })
  3313. .Get("/streamed-chunked-with-trailer",
  3314. [&](const Request & /*req*/, Response &res) {
  3315. auto i = new int(0);
  3316. res.set_header("Trailer", "Dummy1, Dummy2");
  3317. res.set_chunked_content_provider(
  3318. "text/plain",
  3319. [i](size_t /*offset*/, DataSink &sink) {
  3320. switch (*i) {
  3321. case 0: sink.os << "123"; break;
  3322. case 1: sink.os << "456"; break;
  3323. case 2: sink.os << "789"; break;
  3324. case 3: {
  3325. sink.done_with_trailer(
  3326. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3327. } break;
  3328. }
  3329. (*i)++;
  3330. return true;
  3331. },
  3332. [i](bool success) {
  3333. EXPECT_TRUE(success);
  3334. delete i;
  3335. });
  3336. })
  3337. .Get("/streamed",
  3338. [&](const Request & /*req*/, Response &res) {
  3339. res.set_content_provider(
  3340. 6, "text/plain",
  3341. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3342. sink.os << (offset < 3 ? "a" : "b");
  3343. return true;
  3344. });
  3345. })
  3346. .Get("/streamed-without-length",
  3347. [&](const Request & /*req*/, Response &res) {
  3348. auto data = new std::string("abcdefg");
  3349. res.set_content_provider(
  3350. "text/plain",
  3351. [data](size_t offset, DataSink &sink) {
  3352. if (offset < data->size()) {
  3353. sink.os << data->substr(offset);
  3354. }
  3355. sink.done();
  3356. return true;
  3357. },
  3358. [data](bool success) {
  3359. EXPECT_TRUE(success);
  3360. delete data;
  3361. });
  3362. })
  3363. .Get("/streamed-with-range",
  3364. [&](const Request &req, Response &res) {
  3365. auto data = new std::string("abcdefg");
  3366. res.set_content_provider(
  3367. data->size(), "text/plain",
  3368. [data](size_t offset, size_t length, DataSink &sink) {
  3369. size_t DATA_CHUNK_SIZE = 4;
  3370. const auto &d = *data;
  3371. auto out_len =
  3372. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3373. auto ret =
  3374. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3375. EXPECT_TRUE(ret);
  3376. return true;
  3377. },
  3378. [data, &req](bool success) {
  3379. EXPECT_EQ(success, !req.has_param("error"));
  3380. delete data;
  3381. });
  3382. })
  3383. .Get("/streamed-cancel",
  3384. [&](const Request & /*req*/, Response &res) {
  3385. res.set_content_provider(
  3386. size_t(-1), "text/plain",
  3387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3388. sink.os << "data_chunk";
  3389. return true;
  3390. });
  3391. })
  3392. .Get("/regex-with-delimiter",
  3393. [&](const Request &req, Response & /*res*/) {
  3394. ASSERT_TRUE(req.has_param("key"));
  3395. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3396. })
  3397. .Get("/with-range",
  3398. [&](const Request & /*req*/, Response &res) {
  3399. res.set_content("abcdefg", "text/plain");
  3400. })
  3401. .Get("/test-start-time",
  3402. [&](const Request &req, Response & /*res*/) {
  3403. EXPECT_NE(req.start_time_,
  3404. std::chrono::steady_clock::time_point::min());
  3405. })
  3406. .Get("/with-range-customized-response",
  3407. [&](const Request & /*req*/, Response &res) {
  3408. res.status = StatusCode::BadRequest_400;
  3409. res.set_content(JSON_DATA, "application/json");
  3410. })
  3411. .Post("/chunked",
  3412. [&](const Request &req, Response & /*res*/) {
  3413. EXPECT_EQ(req.body, "dechunked post body");
  3414. })
  3415. .Post("/large-chunked",
  3416. [&](const Request &req, Response & /*res*/) {
  3417. std::string expected(6 * 30 * 1024u, 'a');
  3418. EXPECT_EQ(req.body, expected);
  3419. })
  3420. .Post("/multipart",
  3421. [&](const Request &req, Response & /*res*/) {
  3422. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3423. req.form.get_field_count("text2") +
  3424. req.form.get_field_count("file3") +
  3425. req.form.get_field_count("file4"));
  3426. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3427. req.form.get_file_count("file2"));
  3428. ASSERT_TRUE(!req.form.has_file("???"));
  3429. ASSERT_TRUE(!req.form.has_field("???"));
  3430. ASSERT_TRUE(req.body.empty());
  3431. {
  3432. const auto &text = req.form.get_field("text1");
  3433. EXPECT_EQ("text default", text);
  3434. }
  3435. {
  3436. const auto &text = req.form.get_field("text2");
  3437. EXPECT_EQ("aωb", text);
  3438. }
  3439. {
  3440. const auto &file = req.form.get_file("file1");
  3441. EXPECT_EQ("hello.txt", file.filename);
  3442. EXPECT_EQ("text/plain", file.content_type);
  3443. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3444. }
  3445. {
  3446. const auto &file = req.form.get_file("file2");
  3447. EXPECT_EQ("world.json", file.filename);
  3448. EXPECT_EQ("application/json", file.content_type);
  3449. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3450. }
  3451. {
  3452. const auto &text = req.form.get_field("file3");
  3453. EXPECT_EQ(0u, text.size());
  3454. }
  3455. {
  3456. const auto &text = req.form.get_field("file4");
  3457. EXPECT_EQ(0u, text.size());
  3458. }
  3459. })
  3460. .Post("/multipart/multi_file_values",
  3461. [&](const Request &req, Response & /*res*/) {
  3462. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3463. req.form.get_field_count("multi_text1"));
  3464. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3465. ASSERT_TRUE(!req.form.has_file("???"));
  3466. ASSERT_TRUE(!req.form.has_field("???"));
  3467. ASSERT_TRUE(req.body.empty());
  3468. {
  3469. const auto &text = req.form.get_field("text");
  3470. EXPECT_EQ("default text", text);
  3471. }
  3472. {
  3473. const auto &text1_values = req.form.get_fields("multi_text1");
  3474. EXPECT_EQ(2u, text1_values.size());
  3475. EXPECT_EQ("aaaaa", text1_values[0]);
  3476. EXPECT_EQ("bbbbb", text1_values[1]);
  3477. }
  3478. {
  3479. const auto &file1_values = req.form.get_files("multi_file1");
  3480. EXPECT_EQ(2u, file1_values.size());
  3481. auto file1 = file1_values[0];
  3482. EXPECT_EQ(file1.filename, "hello.txt");
  3483. EXPECT_EQ(file1.content_type, "text/plain");
  3484. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3485. auto file2 = file1_values[1];
  3486. EXPECT_EQ(file2.filename, "world.json");
  3487. EXPECT_EQ(file2.content_type, "application/json");
  3488. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3489. }
  3490. })
  3491. .Post("/empty",
  3492. [&](const Request &req, Response &res) {
  3493. EXPECT_EQ(req.body, "");
  3494. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3495. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3496. res.set_content("empty", "text/plain");
  3497. })
  3498. .Post("/empty-no-content-type",
  3499. [&](const Request &req, Response &res) {
  3500. EXPECT_EQ(req.body, "");
  3501. EXPECT_FALSE(req.has_header("Content-Type"));
  3502. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3503. res.set_content("empty-no-content-type", "text/plain");
  3504. })
  3505. .Post("/path-only",
  3506. [&](const Request &req, Response &res) {
  3507. EXPECT_EQ(req.body, "");
  3508. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3509. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3510. res.set_content("path-only", "text/plain");
  3511. })
  3512. .Post("/path-headers-only",
  3513. [&](const Request &req, Response &res) {
  3514. EXPECT_EQ(req.body, "");
  3515. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3516. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3517. EXPECT_EQ("world", req.get_header_value("hello"));
  3518. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3519. res.set_content("path-headers-only", "text/plain");
  3520. })
  3521. .Post("/post-large",
  3522. [&](const Request &req, Response &res) {
  3523. EXPECT_EQ(req.body, LARGE_DATA);
  3524. res.set_content(req.body, "text/plain");
  3525. })
  3526. .Post("/post-loopback",
  3527. [&](const Request &, Response &res,
  3528. ContentReader const &content_reader) {
  3529. std::string body;
  3530. content_reader([&](const char *data, size_t data_length) {
  3531. body.append(data, data_length);
  3532. return true;
  3533. });
  3534. res.set_content(body, "text/plain");
  3535. })
  3536. .Put("/put-loopback",
  3537. [&](const Request &, Response &res,
  3538. ContentReader const &content_reader) {
  3539. std::string body;
  3540. content_reader([&](const char *data, size_t data_length) {
  3541. body.append(data, data_length);
  3542. return true;
  3543. });
  3544. res.set_content(body, "text/plain");
  3545. })
  3546. .Patch("/patch-loopback",
  3547. [&](const Request &, Response &res,
  3548. ContentReader const &content_reader) {
  3549. std::string body;
  3550. content_reader([&](const char *data, size_t data_length) {
  3551. body.append(data, data_length);
  3552. return true;
  3553. });
  3554. res.set_content(body, "text/plain");
  3555. })
  3556. .Put("/empty-no-content-type",
  3557. [&](const Request &req, Response &res) {
  3558. EXPECT_EQ(req.body, "");
  3559. EXPECT_FALSE(req.has_header("Content-Type"));
  3560. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3561. res.set_content("empty-no-content-type", "text/plain");
  3562. })
  3563. .Put("/put",
  3564. [&](const Request &req, Response &res) {
  3565. EXPECT_EQ(req.body, "PUT");
  3566. res.set_content(req.body, "text/plain");
  3567. })
  3568. .Put("/put-large",
  3569. [&](const Request &req, Response &res) {
  3570. EXPECT_EQ(req.body, LARGE_DATA);
  3571. res.set_content(req.body, "text/plain");
  3572. })
  3573. .Patch("/patch",
  3574. [&](const Request &req, Response &res) {
  3575. EXPECT_EQ(req.body, "PATCH");
  3576. res.set_content(req.body, "text/plain");
  3577. })
  3578. .Delete("/delete",
  3579. [&](const Request & /*req*/, Response &res) {
  3580. res.set_content("DELETE", "text/plain");
  3581. })
  3582. .Delete("/delete-body",
  3583. [&](const Request &req, Response &res) {
  3584. EXPECT_EQ(req.body, "content");
  3585. res.set_content(req.body, "text/plain");
  3586. })
  3587. .Options(R"(\*)",
  3588. [&](const Request & /*req*/, Response &res) {
  3589. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3590. })
  3591. .Get("/request-target",
  3592. [&](const Request &req, Response & /*res*/) {
  3593. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3594. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3595. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3596. })
  3597. .Get("/long-query-value",
  3598. [&](const Request &req, Response & /*res*/) {
  3599. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3600. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3601. })
  3602. .Get("/too-long-query-value",
  3603. [&](const Request &req, Response & /*res*/) {
  3604. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3605. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3606. })
  3607. .Get("/array-param",
  3608. [&](const Request &req, Response & /*res*/) {
  3609. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3610. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3611. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3612. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3613. })
  3614. .Get("/array-param-values",
  3615. [&](const Request &req, Response & /*res*/) {
  3616. auto values = req.get_param_values("array");
  3617. EXPECT_EQ(3u, values.size());
  3618. EXPECT_EQ("value1", values[0]);
  3619. EXPECT_EQ("value2", values[1]);
  3620. EXPECT_EQ("value3", values[2]);
  3621. auto empty = req.get_param_values("nonexistent");
  3622. EXPECT_TRUE(empty.empty());
  3623. })
  3624. .Post("/validate-no-multiple-headers",
  3625. [&](const Request &req, Response & /*res*/) {
  3626. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3627. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3628. })
  3629. .Post("/content_receiver",
  3630. [&](const Request &req, Response &res,
  3631. const ContentReader &content_reader) {
  3632. if (req.is_multipart_form_data()) {
  3633. std::vector<FormData> items;
  3634. content_reader(
  3635. [&](const FormData &file) {
  3636. items.push_back(file);
  3637. return true;
  3638. },
  3639. [&](const char *data, size_t data_length) {
  3640. items.back().content.append(data, data_length);
  3641. return true;
  3642. });
  3643. EXPECT_EQ(5u, items.size());
  3644. {
  3645. const auto &file = get_file_value(items, "text1");
  3646. EXPECT_TRUE(file.filename.empty());
  3647. EXPECT_EQ("text default", file.content);
  3648. }
  3649. {
  3650. const auto &file = get_file_value(items, "text2");
  3651. EXPECT_TRUE(file.filename.empty());
  3652. EXPECT_EQ("aωb", file.content);
  3653. }
  3654. {
  3655. const auto &file = get_file_value(items, "file1");
  3656. EXPECT_EQ("hello.txt", file.filename);
  3657. EXPECT_EQ("text/plain", file.content_type);
  3658. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3659. }
  3660. {
  3661. const auto &file = get_file_value(items, "file2");
  3662. EXPECT_EQ("world.json", file.filename);
  3663. EXPECT_EQ("application/json", file.content_type);
  3664. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3665. }
  3666. {
  3667. const auto &file = get_file_value(items, "file3");
  3668. EXPECT_TRUE(file.filename.empty());
  3669. EXPECT_EQ("application/octet-stream", file.content_type);
  3670. EXPECT_EQ(0u, file.content.size());
  3671. }
  3672. } else {
  3673. std::string body;
  3674. content_reader([&](const char *data, size_t data_length) {
  3675. EXPECT_EQ(7U, data_length);
  3676. body.append(data, data_length);
  3677. return true;
  3678. });
  3679. EXPECT_EQ(body, "content");
  3680. res.set_content(body, "text/plain");
  3681. }
  3682. })
  3683. .Put("/content_receiver",
  3684. [&](const Request & /*req*/, Response &res,
  3685. const ContentReader &content_reader) {
  3686. std::string body;
  3687. content_reader([&](const char *data, size_t data_length) {
  3688. body.append(data, data_length);
  3689. return true;
  3690. });
  3691. EXPECT_EQ(body, "content");
  3692. res.set_content(body, "text/plain");
  3693. })
  3694. .Patch("/content_receiver",
  3695. [&](const Request & /*req*/, Response &res,
  3696. const ContentReader &content_reader) {
  3697. std::string body;
  3698. content_reader([&](const char *data, size_t data_length) {
  3699. body.append(data, data_length);
  3700. return true;
  3701. });
  3702. EXPECT_EQ(body, "content");
  3703. res.set_content(body, "text/plain");
  3704. })
  3705. .Post("/query-string-and-body",
  3706. [&](const Request &req, Response & /*res*/) {
  3707. ASSERT_TRUE(req.has_param("key"));
  3708. EXPECT_EQ(req.get_param_value("key"), "value");
  3709. EXPECT_EQ(req.body, "content");
  3710. })
  3711. .Get("/last-request",
  3712. [&](const Request &req, Response & /*res*/) {
  3713. EXPECT_EQ("close", req.get_header_value("Connection"));
  3714. })
  3715. .Get(R"(/redirect/(\d+))",
  3716. [&](const Request &req, Response &res) {
  3717. auto num = std::stoi(req.matches[1]) + 1;
  3718. std::string url = "/redirect/" + std::to_string(num);
  3719. res.set_redirect(url);
  3720. })
  3721. .Post("/binary",
  3722. [&](const Request &req, Response &res) {
  3723. EXPECT_EQ(4U, req.body.size());
  3724. EXPECT_EQ("application/octet-stream",
  3725. req.get_header_value("Content-Type"));
  3726. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3727. res.set_content(req.body, "application/octet-stream");
  3728. })
  3729. .Put("/binary",
  3730. [&](const Request &req, Response &res) {
  3731. EXPECT_EQ(4U, req.body.size());
  3732. EXPECT_EQ("application/octet-stream",
  3733. req.get_header_value("Content-Type"));
  3734. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3735. res.set_content(req.body, "application/octet-stream");
  3736. })
  3737. .Patch("/binary",
  3738. [&](const Request &req, Response &res) {
  3739. EXPECT_EQ(4U, req.body.size());
  3740. EXPECT_EQ("application/octet-stream",
  3741. req.get_header_value("Content-Type"));
  3742. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3743. res.set_content(req.body, "application/octet-stream");
  3744. })
  3745. .Delete("/binary",
  3746. [&](const Request &req, Response &res) {
  3747. EXPECT_EQ(4U, req.body.size());
  3748. EXPECT_EQ("application/octet-stream",
  3749. req.get_header_value("Content-Type"));
  3750. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3751. res.set_content(req.body, "application/octet-stream");
  3752. })
  3753. .Get("/issue1772",
  3754. [&](const Request & /*req*/, Response &res) {
  3755. res.status = 401;
  3756. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3757. })
  3758. .Delete("/issue609",
  3759. [](const httplib::Request &, httplib::Response &res,
  3760. const httplib::ContentReader &) {
  3761. res.set_content("ok", "text/plain");
  3762. })
  3763. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3764. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3765. .Get("/compress",
  3766. [&](const Request & /*req*/, Response &res) {
  3767. res.set_content(
  3768. "12345678901234567890123456789012345678901234567890123456789"
  3769. "01234567890123456789012345678901234567890",
  3770. "text/plain");
  3771. })
  3772. .Get("/compress-with-charset",
  3773. [&](const Request & /*req*/, Response &res) {
  3774. res.set_content(
  3775. "12345678901234567890123456789012345678901234567890123456789"
  3776. "01234567890123456789012345678901234567890",
  3777. "application/json; charset=utf-8");
  3778. })
  3779. .Get("/nocompress",
  3780. [&](const Request & /*req*/, Response &res) {
  3781. res.set_content(
  3782. "12345678901234567890123456789012345678901234567890123456789"
  3783. "01234567890123456789012345678901234567890",
  3784. "application/octet-stream");
  3785. })
  3786. .Post("/compress-multipart",
  3787. [&](const Request &req, Response & /*res*/) {
  3788. EXPECT_EQ(2u, req.form.fields.size());
  3789. ASSERT_TRUE(!req.form.has_field("???"));
  3790. {
  3791. const auto &text = req.form.get_field("key1");
  3792. EXPECT_EQ("test", text);
  3793. }
  3794. {
  3795. const auto &text = req.form.get_field("key2");
  3796. EXPECT_EQ("--abcdefg123", text);
  3797. }
  3798. })
  3799. #endif
  3800. ;
  3801. persons_["john"] = "programmer";
  3802. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3803. svr_.wait_until_ready();
  3804. }
  3805. virtual void TearDown() {
  3806. svr_.stop();
  3807. if (!request_threads_.empty()) {
  3808. std::this_thread::sleep_for(std::chrono::seconds(1));
  3809. for (auto &t : request_threads_) {
  3810. t.join();
  3811. }
  3812. }
  3813. t_.join();
  3814. }
  3815. map<string, string> persons_;
  3816. #ifdef CPPHTTPLIB_SSL_ENABLED
  3817. SSLClient cli_;
  3818. SSLServer svr_;
  3819. #else
  3820. Client cli_;
  3821. Server svr_;
  3822. #endif
  3823. thread t_;
  3824. std::vector<thread> request_threads_;
  3825. };
  3826. TEST_F(ServerTest, GetMethod200) {
  3827. auto res = cli_.Get("/hi");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ("HTTP/1.1", res->version);
  3830. EXPECT_EQ(StatusCode::OK_200, res->status);
  3831. EXPECT_EQ("OK", res->reason);
  3832. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3833. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3834. EXPECT_EQ("Hello World!", res->body);
  3835. }
  3836. TEST_F(ServerTest, GetEmptyFile) {
  3837. auto res = cli_.Get("/empty_file");
  3838. ASSERT_TRUE(res);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3841. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3842. EXPECT_EQ("", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetFileContent) {
  3845. auto res = cli_.Get("/file_content");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3850. EXPECT_EQ("test.html", res->body);
  3851. }
  3852. TEST_F(ServerTest, GetFileContentWithRange) {
  3853. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3856. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3858. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3859. EXPECT_EQ("est", res->body);
  3860. }
  3861. TEST_F(ServerTest, GetFileContentWithContentType) {
  3862. auto res = cli_.Get("/file_content_with_content_type");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3866. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3867. EXPECT_EQ("file\n", res->body);
  3868. }
  3869. TEST_F(ServerTest, GetInvalidFileContent) {
  3870. auto res = cli_.Get("/invalid_file_content");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3873. }
  3874. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3875. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ("HTTP/1.1", res->version);
  3878. EXPECT_EQ(StatusCode::OK_200, res->status);
  3879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3880. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. TEST_F(ServerTest, GetMethod302) {
  3884. auto res = cli_.Get("/");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::Found_302, res->status);
  3887. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3888. }
  3889. TEST_F(ServerTest, GetMethod302Redirect) {
  3890. cli_.set_follow_location(true);
  3891. auto res = cli_.Get("/");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("Hello World!", res->body);
  3895. EXPECT_EQ("/hi", res->location);
  3896. }
  3897. TEST_F(ServerTest, GetMethod404) {
  3898. auto res = cli_.Get("/invalid");
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3901. }
  3902. TEST_F(ServerTest, HeadMethod200) {
  3903. auto res = cli_.Head("/hi");
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3907. EXPECT_TRUE(res->body.empty());
  3908. }
  3909. TEST_F(ServerTest, HeadMethod200Static) {
  3910. auto res = cli_.Head("/mount/dir/index.html");
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3914. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3915. EXPECT_TRUE(res->body.empty());
  3916. }
  3917. TEST_F(ServerTest, HeadMethod404) {
  3918. auto res = cli_.Head("/invalid");
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3921. EXPECT_TRUE(res->body.empty());
  3922. }
  3923. TEST_F(ServerTest, GetMethodPersonJohn) {
  3924. auto res = cli_.Get("/person/john");
  3925. ASSERT_TRUE(res);
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3928. EXPECT_EQ("programmer", res->body);
  3929. }
  3930. TEST_F(ServerTest, PostMethod1) {
  3931. auto res = cli_.Get("/person/john1");
  3932. ASSERT_TRUE(res);
  3933. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3934. res = cli_.Post("/person", "name=john1&note=coder",
  3935. "application/x-www-form-urlencoded");
  3936. ASSERT_TRUE(res);
  3937. ASSERT_EQ(StatusCode::OK_200, res->status);
  3938. res = cli_.Get("/person/john1");
  3939. ASSERT_TRUE(res);
  3940. ASSERT_EQ(StatusCode::OK_200, res->status);
  3941. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3942. ASSERT_EQ("coder", res->body);
  3943. }
  3944. TEST_F(ServerTest, PostMethod2) {
  3945. auto res = cli_.Get("/person/john2");
  3946. ASSERT_TRUE(res);
  3947. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3948. Params params;
  3949. params.emplace("name", "john2");
  3950. params.emplace("note", "coder");
  3951. res = cli_.Post("/person", params);
  3952. ASSERT_TRUE(res);
  3953. ASSERT_EQ(StatusCode::OK_200, res->status);
  3954. res = cli_.Get("/person/john2");
  3955. ASSERT_TRUE(res);
  3956. ASSERT_EQ(StatusCode::OK_200, res->status);
  3957. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3958. ASSERT_EQ("coder", res->body);
  3959. }
  3960. TEST_F(ServerTest, PutMethod3) {
  3961. auto res = cli_.Get("/person/john3");
  3962. ASSERT_TRUE(res);
  3963. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3964. Params params;
  3965. params.emplace("name", "john3");
  3966. params.emplace("note", "coder");
  3967. res = cli_.Put("/person", params);
  3968. ASSERT_TRUE(res);
  3969. ASSERT_EQ(StatusCode::OK_200, res->status);
  3970. res = cli_.Get("/person/john3");
  3971. ASSERT_TRUE(res);
  3972. ASSERT_EQ(StatusCode::OK_200, res->status);
  3973. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3974. ASSERT_EQ("coder", res->body);
  3975. }
  3976. TEST_F(ServerTest, DeleteMethod1) {
  3977. auto res = cli_.Get("/person/john4");
  3978. ASSERT_TRUE(res);
  3979. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3980. Params params;
  3981. params.emplace("name", "john4");
  3982. params.emplace("note", "coder");
  3983. res = cli_.Post("/person", params);
  3984. ASSERT_TRUE(res);
  3985. ASSERT_EQ(StatusCode::OK_200, res->status);
  3986. res = cli_.Get("/person/john4");
  3987. ASSERT_TRUE(res);
  3988. ASSERT_EQ(StatusCode::OK_200, res->status);
  3989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3990. ASSERT_EQ("coder", res->body);
  3991. Params delete_params;
  3992. delete_params.emplace("name", "john4");
  3993. res = cli_.Delete("/person", delete_params);
  3994. ASSERT_TRUE(res);
  3995. ASSERT_EQ(StatusCode::OK_200, res->status);
  3996. ASSERT_EQ("DELETED", res->body);
  3997. res = cli_.Get("/person/john4");
  3998. ASSERT_TRUE(res);
  3999. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4000. }
  4001. TEST_F(ServerTest, DeleteMethod2) {
  4002. auto res = cli_.Get("/person/john5");
  4003. ASSERT_TRUE(res);
  4004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4005. Params params;
  4006. params.emplace("name", "john5");
  4007. params.emplace("note", "developer");
  4008. res = cli_.Post("/person", params);
  4009. ASSERT_TRUE(res);
  4010. ASSERT_EQ(StatusCode::OK_200, res->status);
  4011. res = cli_.Get("/person/john5");
  4012. ASSERT_TRUE(res);
  4013. ASSERT_EQ(StatusCode::OK_200, res->status);
  4014. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4015. ASSERT_EQ("developer", res->body);
  4016. Params delete_params;
  4017. delete_params.emplace("name", "john5");
  4018. Headers headers;
  4019. headers.emplace("Custom-Header", "test-value");
  4020. res = cli_.Delete("/person", headers, delete_params);
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ("DELETED", res->body);
  4024. res = cli_.Get("/person/john5");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4027. }
  4028. TEST_F(ServerTest, DeleteMethod3) {
  4029. auto res = cli_.Get("/person/john6");
  4030. ASSERT_TRUE(res);
  4031. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4032. Params params;
  4033. params.emplace("name", "john6");
  4034. params.emplace("note", "tester");
  4035. res = cli_.Post("/person", params);
  4036. ASSERT_TRUE(res);
  4037. ASSERT_EQ(StatusCode::OK_200, res->status);
  4038. res = cli_.Get("/person/john6");
  4039. ASSERT_TRUE(res);
  4040. ASSERT_EQ(StatusCode::OK_200, res->status);
  4041. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4042. ASSERT_EQ("tester", res->body);
  4043. Params delete_params;
  4044. delete_params.emplace("name", "john6");
  4045. Headers headers;
  4046. headers.emplace("Custom-Header", "test-value");
  4047. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4048. ASSERT_TRUE(res);
  4049. ASSERT_EQ(StatusCode::OK_200, res->status);
  4050. ASSERT_EQ("DELETED", res->body);
  4051. res = cli_.Get("/person/john6");
  4052. ASSERT_TRUE(res);
  4053. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4054. }
  4055. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4056. Params params;
  4057. params.emplace("json", JSON_DATA);
  4058. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4059. ASSERT_TRUE(res);
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_EQ(JSON_DATA, res->body);
  4062. }
  4063. TEST_F(ServerTest, PostEmptyContent) {
  4064. auto res = cli_.Post("/empty", "", "text/plain");
  4065. ASSERT_TRUE(res);
  4066. ASSERT_EQ(StatusCode::OK_200, res->status);
  4067. ASSERT_EQ("empty", res->body);
  4068. }
  4069. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4070. auto res = cli_.Post("/empty-no-content-type");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("empty-no-content-type", res->body);
  4074. }
  4075. TEST_F(ServerTest, PostPathOnly) {
  4076. auto res = cli_.Post("/path-only");
  4077. ASSERT_TRUE(res);
  4078. ASSERT_EQ(StatusCode::OK_200, res->status);
  4079. ASSERT_EQ("path-only", res->body);
  4080. }
  4081. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4082. auto res = cli_.Post("/path-headers-only",
  4083. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. ASSERT_EQ("path-headers-only", res->body);
  4087. }
  4088. TEST_F(ServerTest, PostLarge) {
  4089. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4090. ASSERT_TRUE(res);
  4091. ASSERT_EQ(StatusCode::OK_200, res->status);
  4092. EXPECT_EQ(LARGE_DATA, res->body);
  4093. }
  4094. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4095. auto res = cli_.Put("/empty-no-content-type");
  4096. ASSERT_TRUE(res);
  4097. ASSERT_EQ(StatusCode::OK_200, res->status);
  4098. ASSERT_EQ("empty-no-content-type", res->body);
  4099. }
  4100. TEST_F(ServerTest, GetMethodDir) {
  4101. auto res = cli_.Get("/dir/");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(StatusCode::OK_200, res->status);
  4104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4105. auto body = R"(<html>
  4106. <head>
  4107. </head>
  4108. <body>
  4109. <a href="/dir/test.html">Test</a>
  4110. <a href="/hi">hi</a>
  4111. </body>
  4112. </html>
  4113. )";
  4114. EXPECT_EQ(body, res->body);
  4115. }
  4116. TEST_F(ServerTest, GetMethodDirTest) {
  4117. auto res = cli_.Get("/dir/test.html");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4121. EXPECT_EQ("test.html", res->body);
  4122. }
  4123. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4124. auto res = cli_.Get("/dir/../dir/test.html");
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::OK_200, res->status);
  4127. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4128. EXPECT_EQ("test.html", res->body);
  4129. }
  4130. TEST_F(ServerTest, GetMethodInvalidPath) {
  4131. auto res = cli_.Get("/dir/../test.html");
  4132. ASSERT_TRUE(res);
  4133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4134. }
  4135. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4136. auto res = cli_.Get("/../www/dir/test.html");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4139. }
  4140. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4141. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4142. ASSERT_TRUE(res);
  4143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4144. }
  4145. TEST_F(ServerTest, GetMethodDirMountTest) {
  4146. auto res = cli_.Get("/mount/dir/test.html");
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::OK_200, res->status);
  4149. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4150. EXPECT_EQ("test.html", res->body);
  4151. }
  4152. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4153. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4154. ASSERT_TRUE(res);
  4155. EXPECT_EQ(StatusCode::OK_200, res->status);
  4156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4157. EXPECT_EQ("test.html", res->body);
  4158. }
  4159. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4160. auto res = cli_.Get("/mount/dir/../test.html");
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4163. }
  4164. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4165. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4166. ASSERT_TRUE(res);
  4167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4168. }
  4169. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4170. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4175. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4178. }
  4179. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4180. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. }
  4184. TEST_F(ServerTest, PostMethod303) {
  4185. auto res = cli_.Post("/1", "body", "text/plain");
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4188. EXPECT_EQ("/2", res->get_header_value("Location"));
  4189. }
  4190. TEST_F(ServerTest, PostMethod303Redirect) {
  4191. cli_.set_follow_location(true);
  4192. auto res = cli_.Post("/1", "body", "text/plain");
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::OK_200, res->status);
  4195. EXPECT_EQ("redirected.", res->body);
  4196. EXPECT_EQ("/2", res->location);
  4197. }
  4198. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4199. auto res = cli_.Get("/dir/test.abcde");
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::OK_200, res->status);
  4202. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4203. EXPECT_EQ("abcde", res->body);
  4204. }
  4205. TEST_F(ServerTest, StaticFileRange) {
  4206. auto res =
  4207. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(true, res->has_header("Content-Range"));
  4213. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4214. EXPECT_EQ(std::string("cd"), res->body);
  4215. }
  4216. TEST_F(ServerTest, StaticFileRanges) {
  4217. auto res = cli_.Get("/dir/test.abcde",
  4218. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_TRUE(
  4222. res->get_header_value("Content-Type")
  4223. .find(
  4224. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4225. 0);
  4226. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4227. }
  4228. TEST_F(ServerTest, StaticFileRangeHead) {
  4229. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4233. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4236. }
  4237. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4238. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4243. EXPECT_EQ(true, res->has_header("Content-Range"));
  4244. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4245. res->get_header_value("Content-Range"));
  4246. EXPECT_EQ("LAST\n", res->body);
  4247. }
  4248. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4249. auto res =
  4250. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4254. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4255. EXPECT_EQ(true, res->has_header("Content-Range"));
  4256. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4257. }
  4258. TEST_F(ServerTest, StaticFileBigFile) {
  4259. auto res = cli_.Get("/dir/1MB.txt");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4263. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4264. }
  4265. TEST_F(ServerTest, InvalidBaseDirMount) {
  4266. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4267. }
  4268. TEST_F(ServerTest, Binary) {
  4269. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4270. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4271. "application/octet-stream");
  4272. ASSERT_TRUE(res);
  4273. ASSERT_EQ(StatusCode::OK_200, res->status);
  4274. ASSERT_EQ(4U, res->body.size());
  4275. res = cli_.Put("/binary", binary.data(), binary.size(),
  4276. "application/octet-stream");
  4277. ASSERT_TRUE(res);
  4278. ASSERT_EQ(StatusCode::OK_200, res->status);
  4279. ASSERT_EQ(4U, res->body.size());
  4280. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4281. "application/octet-stream");
  4282. ASSERT_TRUE(res);
  4283. ASSERT_EQ(StatusCode::OK_200, res->status);
  4284. ASSERT_EQ(4U, res->body.size());
  4285. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4286. "application/octet-stream");
  4287. ASSERT_TRUE(res);
  4288. ASSERT_EQ(StatusCode::OK_200, res->status);
  4289. ASSERT_EQ(4U, res->body.size());
  4290. }
  4291. TEST_F(ServerTest, BinaryString) {
  4292. auto binary = std::string("\x00\x01\x02\x03", 4);
  4293. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4294. ASSERT_TRUE(res);
  4295. ASSERT_EQ(StatusCode::OK_200, res->status);
  4296. ASSERT_EQ(4U, res->body.size());
  4297. res = cli_.Put("/binary", binary, "application/octet-stream");
  4298. ASSERT_TRUE(res);
  4299. ASSERT_EQ(StatusCode::OK_200, res->status);
  4300. ASSERT_EQ(4U, res->body.size());
  4301. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4302. ASSERT_TRUE(res);
  4303. ASSERT_EQ(StatusCode::OK_200, res->status);
  4304. ASSERT_EQ(4U, res->body.size());
  4305. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4306. ASSERT_TRUE(res);
  4307. ASSERT_EQ(StatusCode::OK_200, res->status);
  4308. ASSERT_EQ(4U, res->body.size());
  4309. }
  4310. TEST_F(ServerTest, EmptyRequest) {
  4311. auto res = cli_.Get("");
  4312. ASSERT_TRUE(!res);
  4313. EXPECT_EQ(Error::Connection, res.error());
  4314. }
  4315. TEST_F(ServerTest, LongRequest) {
  4316. std::string request;
  4317. for (size_t i = 0; i < 545; i++) {
  4318. request += "/TooLongRequest";
  4319. }
  4320. request += "OK";
  4321. auto res = cli_.Get(request.c_str());
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4324. }
  4325. TEST_F(ServerTest, TooLongRequest) {
  4326. std::string request;
  4327. for (size_t i = 0; i < 546; i++) {
  4328. request += "/TooLongRequest";
  4329. }
  4330. request += "_NG";
  4331. auto start = std::chrono::high_resolution_clock::now();
  4332. cli_.set_keep_alive(true);
  4333. auto res = cli_.Get(request.c_str());
  4334. auto end = std::chrono::high_resolution_clock::now();
  4335. auto elapsed =
  4336. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4337. .count();
  4338. ASSERT_TRUE(res);
  4339. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4340. EXPECT_LE(elapsed, 1000);
  4341. EXPECT_EQ("close", res->get_header_value("Connection"));
  4342. EXPECT_FALSE(cli_.is_socket_open());
  4343. }
  4344. TEST_F(ServerTest, AlmostTooLongRequest) {
  4345. // test for #2046 - URI length check shouldn't include other content on req
  4346. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4347. // leading /, space, HTTP/1.1)
  4348. std::string request =
  4349. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4350. auto res = cli_.Get(request.c_str());
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4353. }
  4354. TEST_F(ServerTest, LongHeader) {
  4355. Request req;
  4356. req.method = "GET";
  4357. req.path = "/hi";
  4358. std::string host_and_port;
  4359. host_and_port += HOST;
  4360. host_and_port += ":";
  4361. host_and_port += std::to_string(PORT);
  4362. req.headers.emplace("Host", host_and_port.c_str());
  4363. req.headers.emplace("Accept", "*/*");
  4364. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4365. req.headers.emplace(
  4366. "Header-Name",
  4367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4395. "@@@@@@@@@@@@@@@@");
  4396. auto res = std::make_shared<Response>();
  4397. auto error = Error::Success;
  4398. auto ret = cli_.send(req, *res, error);
  4399. ASSERT_TRUE(ret);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. }
  4402. TEST_F(ServerTest, LongQueryValue) {
  4403. auto start = std::chrono::high_resolution_clock::now();
  4404. cli_.set_keep_alive(true);
  4405. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4406. auto end = std::chrono::high_resolution_clock::now();
  4407. auto elapsed =
  4408. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4409. .count();
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4412. EXPECT_LE(elapsed, 1000);
  4413. EXPECT_EQ("close", res->get_header_value("Connection"));
  4414. EXPECT_FALSE(cli_.is_socket_open());
  4415. }
  4416. TEST_F(ServerTest, TooLongQueryValue) {
  4417. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4418. ASSERT_FALSE(res);
  4419. EXPECT_EQ(Error::Read, res.error());
  4420. }
  4421. TEST_F(ServerTest, TooLongHeader) {
  4422. Request req;
  4423. req.method = "GET";
  4424. req.path = "/hi";
  4425. std::string host_and_port;
  4426. host_and_port += HOST;
  4427. host_and_port += ":";
  4428. host_and_port += std::to_string(PORT);
  4429. req.headers.emplace("Host", host_and_port.c_str());
  4430. req.headers.emplace("Accept", "*/*");
  4431. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4432. req.headers.emplace(
  4433. "Header-Name",
  4434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4462. "@@@@@@@@@@@@@@@@@");
  4463. auto res = std::make_shared<Response>();
  4464. auto error = Error::Success;
  4465. auto ret = cli_.send(req, *res, error);
  4466. ASSERT_TRUE(ret);
  4467. EXPECT_EQ(StatusCode::OK_200, res->status);
  4468. }
  4469. TEST_F(ServerTest, HeaderCountAtLimit) {
  4470. // Test with headers just under the 100 limit
  4471. httplib::Headers headers;
  4472. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4473. // This should keep us just under the 100 header limit
  4474. for (int i = 0; i < 95; i++) {
  4475. std::string name = "X-Test-Header-" + std::to_string(i);
  4476. std::string value = "value" + std::to_string(i);
  4477. headers.emplace(name, value);
  4478. }
  4479. // This should work fine as we're under the limit
  4480. auto res = cli_.Get("/hi", headers);
  4481. EXPECT_TRUE(res);
  4482. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4483. }
  4484. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4485. // Test with many headers to exceed the 100 limit
  4486. httplib::Headers headers;
  4487. // Add 150 headers to definitely exceed the 100 limit
  4488. for (int i = 0; i < 150; i++) {
  4489. std::string name = "X-Test-Header-" + std::to_string(i);
  4490. std::string value = "value" + std::to_string(i);
  4491. headers.emplace(name, value);
  4492. }
  4493. // This should fail due to exceeding header count limit
  4494. cli_.set_keep_alive(true);
  4495. auto res = cli_.Get("/hi", headers);
  4496. // The server should respond with 400 Bad Request
  4497. ASSERT_TRUE(res);
  4498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4499. EXPECT_EQ("close", res->get_header_value("Connection"));
  4500. EXPECT_FALSE(cli_.is_socket_open());
  4501. }
  4502. TEST_F(ServerTest, PercentEncoding) {
  4503. auto res = cli_.Get("/e%6edwith%");
  4504. ASSERT_TRUE(res);
  4505. EXPECT_EQ(StatusCode::OK_200, res->status);
  4506. }
  4507. TEST_F(ServerTest, PercentEncodingUnicode) {
  4508. auto res = cli_.Get("/e%u006edwith%");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. }
  4512. TEST_F(ServerTest, InvalidPercentEncoding) {
  4513. auto res = cli_.Get("/%endwith%");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4516. }
  4517. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4518. auto res = cli_.Get("/%uendwith%");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4521. }
  4522. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4523. auto res = cli_.Get("/hello?aaa=bbb%");
  4524. ASSERT_TRUE(res);
  4525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4526. }
  4527. TEST_F(ServerTest, PlusSignEncoding) {
  4528. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("a +b", res->body);
  4532. }
  4533. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4534. // This test simulates a potential DoS attack using many headers
  4535. // to verify our security fix prevents memory exhaustion
  4536. httplib::Headers attack_headers;
  4537. // Attempt to add many headers like an attacker would (200 headers to far
  4538. // exceed limit)
  4539. for (int i = 0; i < 200; i++) {
  4540. std::string name = "X-Attack-Header-" + std::to_string(i);
  4541. std::string value = "attack_payload_" + std::to_string(i);
  4542. attack_headers.emplace(name, value);
  4543. }
  4544. // Try to POST with excessive headers
  4545. cli_.set_keep_alive(true);
  4546. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4547. // Should either fail or return 400 Bad Request due to security limit
  4548. if (res) {
  4549. // If we get a response, it should be 400 Bad Request
  4550. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4551. EXPECT_EQ("close", res->get_header_value("Connection"));
  4552. }
  4553. EXPECT_FALSE(cli_.is_socket_open());
  4554. }
  4555. TEST_F(ServerTest, MultipartFormData) {
  4556. UploadFormDataItems items = {
  4557. {"text1", "text default", "", ""},
  4558. {"text2", "aωb", "", ""},
  4559. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4560. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4561. {"file3", "", "", "application/octet-stream"},
  4562. {"file4", "", "", " application/json tmp-string "}};
  4563. auto res = cli_.Post("/multipart", items);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4568. UploadFormDataItems items = {
  4569. {"text", "default text", "", ""},
  4570. {"multi_text1", "aaaaa", "", ""},
  4571. {"multi_text1", "bbbbb", "", ""},
  4572. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4573. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4574. "application/json"},
  4575. };
  4576. auto res = cli_.Post("/multipart/multi_file_values", items);
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. }
  4580. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4581. auto res = cli_.Get("/hi");
  4582. ASSERT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4585. EXPECT_EQ("Hello World!", res->body);
  4586. }
  4587. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4588. Request req;
  4589. req.method = "POST";
  4590. req.path = "/chunked";
  4591. std::string host_and_port;
  4592. host_and_port += HOST;
  4593. host_and_port += ":";
  4594. host_and_port += std::to_string(PORT);
  4595. req.headers.emplace("Host", host_and_port.c_str());
  4596. req.headers.emplace("Accept", "*/*");
  4597. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4598. req.headers.emplace("Content-Type", "text/plain");
  4599. req.headers.emplace("Content-Length", "0");
  4600. req.headers.emplace(
  4601. "Transfer-Encoding",
  4602. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4603. // Client does not chunk, so make a chunked body manually.
  4604. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4605. auto res = std::make_shared<Response>();
  4606. auto error = Error::Success;
  4607. auto ret = cli_.send(req, *res, error);
  4608. ASSERT_TRUE(ret);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4612. // rather than treat them as valid lengths.
  4613. template <typename ClientT>
  4614. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4615. Request req;
  4616. req.method = "POST";
  4617. req.path = "/chunked";
  4618. std::string host_and_port;
  4619. host_and_port += HOST;
  4620. host_and_port += ":";
  4621. host_and_port += std::to_string(PORT);
  4622. req.headers.emplace("Host", host_and_port.c_str());
  4623. req.headers.emplace("Content-Length", "0");
  4624. req.headers.emplace("Transfer-Encoding", "chunked");
  4625. req.body = body;
  4626. auto res = std::make_shared<Response>();
  4627. auto error = Error::Success;
  4628. ASSERT_TRUE(cli.send(req, *res, error));
  4629. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4630. }
  4631. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4632. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4633. }
  4634. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4635. expect_chunked_body_rejected(
  4636. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4637. }
  4638. TEST_F(ServerTest, GetStreamed2) {
  4639. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4642. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4643. EXPECT_EQ(true, res->has_header("Content-Range"));
  4644. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4645. EXPECT_EQ(std::string("ab"), res->body);
  4646. }
  4647. TEST_F(ServerTest, GetStreamed) {
  4648. auto res = cli_.Get("/streamed");
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4652. EXPECT_EQ(std::string("aaabbb"), res->body);
  4653. }
  4654. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4655. auto res = cli_.Get("/streamed-without-length",
  4656. Headers{make_range_header({{0, -1}})});
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(false, res->has_header("Content-Length"));
  4660. EXPECT_EQ(false, res->has_header("Content-Range"));
  4661. EXPECT_EQ(std::string("abcdefg"), res->body);
  4662. }
  4663. TEST_F(ServerTest, GetStreamedWithRange1) {
  4664. auto res =
  4665. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4668. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4669. EXPECT_EQ(true, res->has_header("Content-Range"));
  4670. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4671. EXPECT_EQ(std::string("def"), res->body);
  4672. }
  4673. TEST_F(ServerTest, GetStreamedWithRange2) {
  4674. auto res =
  4675. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4676. ASSERT_TRUE(res);
  4677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4678. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4679. EXPECT_EQ(true, res->has_header("Content-Range"));
  4680. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4681. EXPECT_EQ(std::string("bcdefg"), res->body);
  4682. }
  4683. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4684. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4685. ASSERT_TRUE(res);
  4686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4687. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4688. EXPECT_EQ(true, res->has_header("Content-Range"));
  4689. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4690. EXPECT_EQ(std::string("efg"), res->body);
  4691. }
  4692. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4693. auto res =
  4694. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4697. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4698. EXPECT_EQ(false, res->has_header("Content-Range"));
  4699. EXPECT_EQ(0U, res->body.size());
  4700. }
  4701. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4702. auto res =
  4703. cli_.Get("/streamed-with-range",
  4704. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4705. "92233720368547758079223372036854775807"}});
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4708. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4709. EXPECT_EQ(false, res->has_header("Content-Range"));
  4710. EXPECT_EQ(0U, res->body.size());
  4711. }
  4712. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4713. auto res = cli_.Get(
  4714. "/with-range",
  4715. Headers{{"Range",
  4716. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4717. {"Accept-Encoding", ""}});
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4721. EXPECT_EQ(true, res->has_header("Content-Range"));
  4722. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4723. EXPECT_EQ(std::string("abcdefg"), res->body);
  4724. }
  4725. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4726. auto res = cli_.Get("/with-range", Headers{
  4727. {"Range", "bytes=0-"},
  4728. {"Accept-Encoding", ""},
  4729. });
  4730. ASSERT_TRUE(res);
  4731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4733. EXPECT_EQ(true, res->has_header("Content-Range"));
  4734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4735. EXPECT_EQ(std::string("abcdefg"), res->body);
  4736. }
  4737. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4738. auto res = cli_.Get("/streamed-with-range",
  4739. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4742. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4743. EXPECT_EQ(false, res->has_header("Content-Range"));
  4744. EXPECT_EQ(267U, res->body.size());
  4745. // Check that both range contents are present
  4746. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4747. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4748. // Check that Content-Range headers are present for both ranges
  4749. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4750. std::string::npos);
  4751. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4752. std::string::npos);
  4753. }
  4754. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4755. Ranges ranges;
  4756. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4757. ranges.emplace_back(0, -1);
  4758. }
  4759. auto res = cli_.Get("/streamed-with-range?error",
  4760. Headers{{make_range_header(ranges)}});
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4763. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4764. EXPECT_EQ(false, res->has_header("Content-Range"));
  4765. EXPECT_EQ(0U, res->body.size());
  4766. }
  4767. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4768. auto res = cli_.Get("/streamed-with-range",
  4769. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4770. ASSERT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4772. EXPECT_EQ(5U, res->body.size());
  4773. // Check that overlapping ranges are coalesced into a single range
  4774. EXPECT_EQ("bcdef", res->body);
  4775. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4776. // Should be single range, not multipart
  4777. EXPECT_TRUE(res->has_header("Content-Range"));
  4778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4779. }
  4780. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4781. auto res = cli_.Get("/streamed-with-range",
  4782. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4785. EXPECT_EQ(268U, res->body.size());
  4786. // Check that both range contents are present
  4787. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4788. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4789. // Check that Content-Range headers are present for both ranges
  4790. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4791. std::string::npos);
  4792. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4793. std::string::npos);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4796. auto res = cli_.Get("/streamed-with-range",
  4797. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ(269U, res->body.size());
  4801. // Check that both duplicate range contents are present
  4802. size_t first_abc = res->body.find("abc\r\n");
  4803. EXPECT_TRUE(first_abc != std::string::npos);
  4804. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4805. EXPECT_TRUE(second_abc != std::string::npos);
  4806. // Check that Content-Range headers are present for both ranges
  4807. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4808. EXPECT_TRUE(first_range != std::string::npos);
  4809. size_t second_range =
  4810. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4811. EXPECT_TRUE(second_range != std::string::npos);
  4812. }
  4813. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4814. auto res =
  4815. cli_.Get("/streamed-with-range?error",
  4816. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4819. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(false, res->has_header("Content-Range"));
  4821. EXPECT_EQ(0U, res->body.size());
  4822. }
  4823. TEST_F(ServerTest, GetStreamedEndless) {
  4824. uint64_t offset = 0;
  4825. auto res = cli_.Get("/streamed-cancel",
  4826. [&](const char * /*data*/, uint64_t data_length) {
  4827. if (offset < 100) {
  4828. offset += data_length;
  4829. return true;
  4830. }
  4831. return false;
  4832. });
  4833. ASSERT_TRUE(!res);
  4834. EXPECT_EQ(Error::Canceled, res.error());
  4835. }
  4836. TEST_F(ServerTest, ClientStop) {
  4837. std::atomic_size_t count{4};
  4838. std::vector<std::thread> threads;
  4839. for (auto i = count.load(); i != 0; --i) {
  4840. threads.emplace_back([&]() {
  4841. auto res = cli_.Get("/streamed-cancel",
  4842. [&](const char *, uint64_t) { return true; });
  4843. --count;
  4844. ASSERT_TRUE(!res);
  4845. EXPECT_TRUE(res.error() == Error::Canceled ||
  4846. res.error() == Error::Read || res.error() == Error::Write);
  4847. });
  4848. }
  4849. std::this_thread::sleep_for(std::chrono::seconds(2));
  4850. while (count != 0) {
  4851. cli_.stop();
  4852. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4853. }
  4854. for (auto &t : threads) {
  4855. t.join();
  4856. }
  4857. }
  4858. TEST_F(ServerTest, GetWithRange1) {
  4859. auto res = cli_.Get("/with-range", Headers{
  4860. make_range_header({{3, 5}}),
  4861. {"Accept-Encoding", ""},
  4862. });
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4865. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4866. EXPECT_EQ(true, res->has_header("Content-Range"));
  4867. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4868. EXPECT_EQ(std::string("def"), res->body);
  4869. }
  4870. TEST_F(ServerTest, GetWithRange2) {
  4871. auto res = cli_.Get("/with-range", Headers{
  4872. make_range_header({{1, -1}}),
  4873. {"Accept-Encoding", ""},
  4874. });
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4877. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ(true, res->has_header("Content-Range"));
  4879. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4880. EXPECT_EQ(std::string("bcdefg"), res->body);
  4881. }
  4882. TEST_F(ServerTest, GetWithRange3) {
  4883. auto res = cli_.Get("/with-range", Headers{
  4884. make_range_header({{0, 0}}),
  4885. {"Accept-Encoding", ""},
  4886. });
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4889. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4890. EXPECT_EQ(true, res->has_header("Content-Range"));
  4891. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4892. EXPECT_EQ(std::string("a"), res->body);
  4893. }
  4894. TEST_F(ServerTest, GetWithRange4) {
  4895. auto res = cli_.Get("/with-range", Headers{
  4896. make_range_header({{-1, 2}}),
  4897. {"Accept-Encoding", ""},
  4898. });
  4899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4901. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4902. EXPECT_EQ(true, res->has_header("Content-Range"));
  4903. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4904. EXPECT_EQ(std::string("fg"), res->body);
  4905. }
  4906. TEST_F(ServerTest, GetWithRange5) {
  4907. auto res = cli_.Get("/with-range", Headers{
  4908. make_range_header({{0, 5}}),
  4909. {"Accept-Encoding", ""},
  4910. });
  4911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4912. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4913. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4914. EXPECT_EQ(true, res->has_header("Content-Range"));
  4915. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4916. EXPECT_EQ(std::string("abcdef"), res->body);
  4917. }
  4918. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4919. auto res =
  4920. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  4921. ASSERT_TRUE(res);
  4922. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4923. }
  4924. TEST_F(ServerTest, GetWithRangeMultipart) {
  4925. auto res =
  4926. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4927. ASSERT_TRUE(res);
  4928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4929. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(false, res->has_header("Content-Range"));
  4931. EXPECT_EQ(267U, res->body.size());
  4932. }
  4933. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4934. auto res = cli_.Get("/with-range",
  4935. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4938. }
  4939. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4940. auto res = cli_.Get("/with-range-customized-response",
  4941. Headers{{make_range_header({{1, 2}})}});
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4944. EXPECT_EQ(true, res->has_header("Content-Length"));
  4945. EXPECT_EQ(false, res->has_header("Content-Range"));
  4946. EXPECT_EQ(JSON_DATA, res->body);
  4947. }
  4948. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4949. auto res = cli_.Get("/with-range-customized-response",
  4950. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4951. ASSERT_TRUE(res);
  4952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4953. EXPECT_EQ(true, res->has_header("Content-Length"));
  4954. EXPECT_EQ(false, res->has_header("Content-Range"));
  4955. EXPECT_EQ(JSON_DATA, res->body);
  4956. }
  4957. TEST_F(ServerTest, Issue1772) {
  4958. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4961. }
  4962. TEST_F(ServerTest, Issue609) {
  4963. auto res = cli_.Delete("/issue609");
  4964. ASSERT_TRUE(res);
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ(std::string("ok"), res->body);
  4967. }
  4968. TEST_F(ServerTest, GetStreamedChunked) {
  4969. auto res = cli_.Get("/streamed-chunked");
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ(std::string("123456789"), res->body);
  4973. }
  4974. TEST_F(ServerTest, GetStreamedChunked2) {
  4975. auto res = cli_.Get("/streamed-chunked2");
  4976. ASSERT_TRUE(res);
  4977. EXPECT_EQ(StatusCode::OK_200, res->status);
  4978. EXPECT_EQ(std::string("123456789"), res->body);
  4979. }
  4980. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4981. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4982. ASSERT_TRUE(res);
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ(std::string("123456789"), res->body);
  4985. EXPECT_TRUE(res->has_header("Trailer"));
  4986. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4987. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4988. // Trailers are now stored separately from headers (security fix)
  4989. EXPECT_EQ(2U, res->trailers.size());
  4990. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4991. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4992. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4993. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4994. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4995. // Verify trailers are NOT in headers (security verification)
  4996. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4997. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4998. }
  4999. TEST_F(ServerTest, LargeChunkedPost) {
  5000. Request req;
  5001. req.method = "POST";
  5002. req.path = "/large-chunked";
  5003. std::string host_and_port;
  5004. host_and_port += HOST;
  5005. host_and_port += ":";
  5006. host_and_port += std::to_string(PORT);
  5007. req.headers.emplace("Host", host_and_port.c_str());
  5008. req.headers.emplace("Accept", "*/*");
  5009. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5010. req.headers.emplace("Content-Type", "text/plain");
  5011. req.headers.emplace("Content-Length", "0");
  5012. req.headers.emplace("Transfer-Encoding", "chunked");
  5013. std::string long_string(30 * 1024u, 'a');
  5014. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5015. // Attempt to make a large enough post to exceed OS buffers, to test that
  5016. // the server handles short reads if the full chunk data isn't available.
  5017. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5018. auto res = std::make_shared<Response>();
  5019. auto error = Error::Success;
  5020. auto ret = cli_.send(req, *res, error);
  5021. ASSERT_TRUE(ret);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. }
  5024. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5025. auto res = cli_.Get("/remote_addr");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5029. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5030. }
  5031. TEST_F(ServerTest, GetMethodLocalAddr) {
  5032. auto res = cli_.Get("/local_addr");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5037. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5038. }
  5039. TEST_F(ServerTest, HTTPResponseSplitting) {
  5040. auto res = cli_.Get("/http_response_splitting");
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. }
  5044. TEST_F(ServerTest, SlowRequest) {
  5045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5046. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5047. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5048. }
  5049. #if 0
  5050. TEST_F(ServerTest, SlowPost) {
  5051. char buffer[64 * 1024];
  5052. memset(buffer, 0x42, sizeof(buffer));
  5053. auto res = cli_.Post(
  5054. "/slowpost", 64 * 1024 * 1024,
  5055. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5056. auto ret = sink.write(buffer, sizeof(buffer));
  5057. EXPECT_TRUE(ret);
  5058. return true;
  5059. },
  5060. "text/plain");
  5061. ASSERT_TRUE(res);
  5062. EXPECT_EQ(StatusCode::OK_200, res->status);
  5063. }
  5064. TEST_F(ServerTest, SlowPostFail) {
  5065. char buffer[64 * 1024];
  5066. memset(buffer, 0x42, sizeof(buffer));
  5067. cli_.set_write_timeout(std::chrono::seconds(0));
  5068. auto res = cli_.Post(
  5069. "/slowpost", 64 * 1024 * 1024,
  5070. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5071. sink.write(buffer, sizeof(buffer));
  5072. return true;
  5073. },
  5074. "text/plain");
  5075. ASSERT_TRUE(!res);
  5076. EXPECT_EQ(Error::Write, res.error());
  5077. }
  5078. #endif
  5079. TEST_F(ServerTest, Put) {
  5080. auto res = cli_.Put("/put", "PUT", "text/plain");
  5081. ASSERT_TRUE(res);
  5082. EXPECT_EQ(StatusCode::OK_200, res->status);
  5083. EXPECT_EQ("PUT", res->body);
  5084. }
  5085. TEST_F(ServerTest, PutWithContentProvider) {
  5086. auto res = cli_.Put(
  5087. "/put", 3,
  5088. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5089. sink.os << "PUT";
  5090. return true;
  5091. },
  5092. "text/plain");
  5093. ASSERT_TRUE(res);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. EXPECT_EQ("PUT", res->body);
  5096. }
  5097. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5098. auto res = cli_.Post(
  5099. "/post", 42,
  5100. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5101. return false;
  5102. },
  5103. "text/plain");
  5104. ASSERT_TRUE(!res);
  5105. EXPECT_EQ(Error::Canceled, res.error());
  5106. }
  5107. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5108. auto res = cli_.Put(
  5109. "/put",
  5110. [](size_t /*offset*/, DataSink &sink) {
  5111. sink.os << "PUT";
  5112. sink.done();
  5113. return true;
  5114. },
  5115. "text/plain");
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ("PUT", res->body);
  5119. }
  5120. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5121. auto res = cli_.Post(
  5122. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5123. "text/plain");
  5124. ASSERT_TRUE(!res);
  5125. EXPECT_EQ(Error::Canceled, res.error());
  5126. }
  5127. TEST_F(ServerTest, PostLoopBack) {
  5128. std::string body;
  5129. auto res = cli_.Post(
  5130. "/post-loopback", 9,
  5131. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5132. EXPECT_EQ(9u, length);
  5133. sink.write("123", 3);
  5134. sink.write("456", 3);
  5135. sink.write("789", 3);
  5136. return true;
  5137. },
  5138. "text/plain",
  5139. [&body](const char *data, size_t data_length) {
  5140. body.append(data, data_length);
  5141. return true;
  5142. });
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("123456789", body);
  5146. }
  5147. TEST_F(ServerTest, PutLoopBack) {
  5148. std::string body;
  5149. auto res = cli_.Put(
  5150. "/put-loopback", 9,
  5151. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5152. EXPECT_EQ(9u, length);
  5153. sink.write("123", 3);
  5154. sink.write("456", 3);
  5155. sink.write("789", 3);
  5156. return true;
  5157. },
  5158. "text/plain",
  5159. [&body](const char *data, size_t data_length) {
  5160. body.append(data, data_length);
  5161. return true;
  5162. });
  5163. ASSERT_TRUE(res);
  5164. EXPECT_EQ(StatusCode::OK_200, res->status);
  5165. EXPECT_EQ("123456789", body);
  5166. }
  5167. TEST_F(ServerTest, PatchLoopBack) {
  5168. std::string body;
  5169. auto res = cli_.Patch(
  5170. "/patch-loopback", 9,
  5171. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5172. EXPECT_EQ(9u, length);
  5173. sink.write("123", 3);
  5174. sink.write("456", 3);
  5175. sink.write("789", 3);
  5176. return true;
  5177. },
  5178. "text/plain",
  5179. [&body](const char *data, size_t data_length) {
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("123456789", body);
  5186. }
  5187. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5188. std::string body;
  5189. auto res = cli_.Post(
  5190. "/post-loopback",
  5191. [](size_t /*offset*/, DataSink &sink) {
  5192. sink.write("123", 3);
  5193. sink.write("456", 3);
  5194. sink.write("789", 3);
  5195. sink.done();
  5196. return true;
  5197. },
  5198. "text/plain",
  5199. [&body](const char *data, size_t data_length) {
  5200. body.append(data, data_length);
  5201. return true;
  5202. });
  5203. ASSERT_TRUE(res);
  5204. EXPECT_EQ(StatusCode::OK_200, res->status);
  5205. EXPECT_EQ("123456789", body);
  5206. }
  5207. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5208. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5209. cli_.set_compress(true);
  5210. auto res = cli_.Put(
  5211. "/put", 3,
  5212. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5213. sink.os << "PUT";
  5214. return true;
  5215. },
  5216. "text/plain");
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ(StatusCode::OK_200, res->status);
  5219. EXPECT_EQ("PUT", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5222. cli_.set_compress(true);
  5223. auto res = cli_.Post(
  5224. "/post", 42,
  5225. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5226. return false;
  5227. },
  5228. "text/plain");
  5229. ASSERT_TRUE(!res);
  5230. EXPECT_EQ(Error::Canceled, res.error());
  5231. }
  5232. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5233. cli_.set_compress(true);
  5234. auto res = cli_.Put(
  5235. "/put",
  5236. [](size_t /*offset*/, DataSink &sink) {
  5237. sink.os << "PUT";
  5238. sink.done();
  5239. return true;
  5240. },
  5241. "text/plain");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ("PUT", res->body);
  5245. }
  5246. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5247. cli_.set_compress(true);
  5248. auto res = cli_.Post(
  5249. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5250. "text/plain");
  5251. ASSERT_TRUE(!res);
  5252. EXPECT_EQ(Error::Canceled, res.error());
  5253. }
  5254. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5255. cli_.set_compress(true);
  5256. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5257. ASSERT_TRUE(res);
  5258. EXPECT_EQ(StatusCode::OK_200, res->status);
  5259. EXPECT_EQ(LARGE_DATA, res->body);
  5260. }
  5261. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5262. #ifdef CPPHTTPLIB_SSL_ENABLED
  5263. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5264. Client cli(s.c_str());
  5265. cli.enable_server_certificate_verification(false);
  5266. #else
  5267. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5268. Client cli(s.c_str());
  5269. #endif
  5270. cli.set_compress(true);
  5271. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5272. ASSERT_TRUE(res);
  5273. EXPECT_EQ(StatusCode::OK_200, res->status);
  5274. EXPECT_EQ(LARGE_DATA, res->body);
  5275. // The compressed size should be less than a 10th of the original. May vary
  5276. // depending on the zlib library.
  5277. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5278. static_cast<uint64_t>(10 * 1024 * 1024));
  5279. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5280. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5281. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5282. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5283. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5284. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5285. #endif
  5286. }
  5287. TEST_F(ServerTest, PutContentWithDeflate) {
  5288. cli_.set_compress(false);
  5289. Headers headers;
  5290. headers.emplace("Content-Encoding", "deflate");
  5291. // PUT in deflate format:
  5292. auto res = cli_.Put("/put", headers,
  5293. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ(StatusCode::OK_200, res->status);
  5296. EXPECT_EQ("PUT", res->body);
  5297. }
  5298. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5299. Headers headers;
  5300. headers.emplace("Accept-Encoding", "gzip, deflate");
  5301. auto res = cli_.Get("/streamed-chunked", headers);
  5302. ASSERT_TRUE(res);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ(std::string("123456789"), res->body);
  5305. }
  5306. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5307. Headers headers;
  5308. headers.emplace("Accept-Encoding", "gzip, deflate");
  5309. auto res = cli_.Get("/streamed-chunked2", headers);
  5310. ASSERT_TRUE(res);
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ(std::string("123456789"), res->body);
  5313. }
  5314. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5315. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5316. ASSERT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. }
  5319. TEST(GzipDecompressor, ChunkedDecompression) {
  5320. std::string data;
  5321. for (size_t i = 0; i < 32 * 1024; ++i) {
  5322. data.push_back(static_cast<char>('a' + i % 26));
  5323. }
  5324. std::string compressed_data;
  5325. {
  5326. httplib::detail::gzip_compressor compressor;
  5327. bool result = compressor.compress(
  5328. data.data(), data.size(),
  5329. /*last=*/true,
  5330. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5331. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5332. compressed_data_size);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(result);
  5336. }
  5337. std::string decompressed_data;
  5338. {
  5339. httplib::detail::gzip_decompressor decompressor;
  5340. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5341. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5342. size_t chunk_size = 130;
  5343. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5344. chunk_begin += chunk_size) {
  5345. size_t current_chunk_size =
  5346. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5347. bool result = decompressor.decompress(
  5348. compressed_data.data() + chunk_begin, current_chunk_size,
  5349. [&](const char *decompressed_data_chunk,
  5350. size_t decompressed_data_chunk_size) {
  5351. decompressed_data.insert(decompressed_data.size(),
  5352. decompressed_data_chunk,
  5353. decompressed_data_chunk_size);
  5354. return true;
  5355. });
  5356. ASSERT_TRUE(result);
  5357. }
  5358. }
  5359. ASSERT_EQ(data, decompressed_data);
  5360. }
  5361. TEST(GzipDecompressor, DeflateDecompression) {
  5362. std::string original_text = "Raw deflate without gzip";
  5363. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5364. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5365. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5366. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5367. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5368. std::string decompressed_data;
  5369. {
  5370. httplib::detail::gzip_decompressor decompressor;
  5371. bool result = decompressor.decompress(
  5372. compressed_data.data(), compressed_data.size(),
  5373. [&](const char *decompressed_data_chunk,
  5374. size_t decompressed_data_chunk_size) {
  5375. decompressed_data.insert(decompressed_data.size(),
  5376. decompressed_data_chunk,
  5377. decompressed_data_chunk_size);
  5378. return true;
  5379. });
  5380. ASSERT_TRUE(result);
  5381. }
  5382. ASSERT_EQ(original_text, decompressed_data);
  5383. }
  5384. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5385. std::string original_text = "Raw deflate without gzip";
  5386. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5387. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5388. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5389. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5390. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5391. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5392. std::string decompressed_data;
  5393. {
  5394. httplib::detail::gzip_decompressor decompressor;
  5395. bool result = decompressor.decompress(
  5396. compressed_data.data(), compressed_data.size(),
  5397. [&](const char *decompressed_data_chunk,
  5398. size_t decompressed_data_chunk_size) {
  5399. decompressed_data.insert(decompressed_data.size(),
  5400. decompressed_data_chunk,
  5401. decompressed_data_chunk_size);
  5402. return true;
  5403. });
  5404. ASSERT_TRUE(result);
  5405. }
  5406. ASSERT_EQ(original_text, decompressed_data);
  5407. }
  5408. #endif
  5409. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5410. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "br");
  5413. auto res = cli_.Get("/streamed-chunked", headers);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ(std::string("123456789"), res->body);
  5417. }
  5418. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5419. Headers headers;
  5420. headers.emplace("Accept-Encoding", "br");
  5421. auto res = cli_.Get("/streamed-chunked2", headers);
  5422. ASSERT_TRUE(res);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. EXPECT_EQ(std::string("123456789"), res->body);
  5425. }
  5426. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5427. cli_.set_compress(true);
  5428. auto res = cli_.Put(
  5429. "/put", 3,
  5430. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5431. sink.os << "PUT";
  5432. return true;
  5433. },
  5434. "text/plain");
  5435. ASSERT_TRUE(res);
  5436. EXPECT_EQ(StatusCode::OK_200, res->status);
  5437. EXPECT_EQ("PUT", res->body);
  5438. }
  5439. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5440. cli_.set_compress(true);
  5441. auto res = cli_.Put(
  5442. "/put",
  5443. [](size_t /*offset*/, DataSink &sink) {
  5444. sink.os << "PUT";
  5445. sink.done();
  5446. return true;
  5447. },
  5448. "text/plain");
  5449. ASSERT_TRUE(res);
  5450. EXPECT_EQ(StatusCode::OK_200, res->status);
  5451. EXPECT_EQ("PUT", res->body);
  5452. }
  5453. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5454. cli_.set_compress(true);
  5455. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ(LARGE_DATA, res->body);
  5459. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5460. }
  5461. #endif
  5462. TEST_F(ServerTest, Patch) {
  5463. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("PATCH", res->body);
  5467. }
  5468. TEST_F(ServerTest, Delete) {
  5469. auto res = cli_.Delete("/delete");
  5470. ASSERT_TRUE(res);
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("DELETE", res->body);
  5473. }
  5474. TEST_F(ServerTest, DeleteContentReceiver) {
  5475. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5476. ASSERT_TRUE(res);
  5477. EXPECT_EQ(StatusCode::OK_200, res->status);
  5478. EXPECT_EQ("content", res->body);
  5479. }
  5480. TEST_F(ServerTest, Options) {
  5481. auto res = cli_.Options("*");
  5482. ASSERT_TRUE(res);
  5483. EXPECT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5485. EXPECT_TRUE(res->body.empty());
  5486. }
  5487. TEST_F(ServerTest, URL) {
  5488. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5489. ASSERT_TRUE(res);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. }
  5492. TEST_F(ServerTest, ArrayParam) {
  5493. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5494. ASSERT_TRUE(res);
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. }
  5497. TEST_F(ServerTest, ArrayParamValues) {
  5498. auto res =
  5499. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5500. ASSERT_TRUE(res);
  5501. EXPECT_EQ(StatusCode::OK_200, res->status);
  5502. }
  5503. TEST_F(ServerTest, NoMultipleHeaders) {
  5504. Headers headers = {{"Content-Length", "5"}};
  5505. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. }
  5510. TEST_F(ServerTest, PostContentReceiver) {
  5511. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5512. ASSERT_TRUE(res);
  5513. ASSERT_EQ(StatusCode::OK_200, res->status);
  5514. ASSERT_EQ("content", res->body);
  5515. }
  5516. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5517. UploadFormDataItems items = {
  5518. {"text1", "text default", "", ""},
  5519. {"text2", "aωb", "", ""},
  5520. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5521. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5522. {"file3", "", "", "application/octet-stream"},
  5523. };
  5524. auto res = cli_.Post("/content_receiver", items);
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5529. UploadFormDataItems items = {
  5530. {"text1", "text default", "", ""},
  5531. {"text2", "aωb", "", ""},
  5532. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5533. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5534. {"file3", "", "", "application/octet-stream"},
  5535. };
  5536. auto boundary = std::string("+++++");
  5537. std::string body;
  5538. for (const auto &item : items) {
  5539. body += "--" + boundary + "\r\n";
  5540. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5541. if (!item.filename.empty()) {
  5542. body += "; filename=\"" + item.filename + "\"";
  5543. }
  5544. body += "\r\n";
  5545. if (!item.content_type.empty()) {
  5546. body += "Content-Type: " + item.content_type + "\r\n";
  5547. }
  5548. body += "\r\n";
  5549. body += item.content + "\r\n";
  5550. }
  5551. body += "--" + boundary + "--\r\n";
  5552. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5553. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST(MultipartFormDataTest, FieldEscaping) {
  5558. Server svr;
  5559. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5560. const ContentReader &content_reader) {
  5561. ASSERT_TRUE(req.is_multipart_form_data());
  5562. std::vector<FormData> received;
  5563. content_reader(
  5564. [&](const FormData &file) {
  5565. received.push_back(file);
  5566. return true;
  5567. },
  5568. [&](const char *data, size_t data_length) {
  5569. received.back().content.append(data, data_length);
  5570. return true;
  5571. });
  5572. // '"', CR and LF in names and filenames are escaped following the
  5573. // WHATWG HTML standard, so each part still parses as a single part
  5574. // with no injected headers. Content types get CR/LF escaped too,
  5575. // while '"' (legal there, e.g. quoted charset) is preserved.
  5576. ASSERT_EQ(4U, received.size());
  5577. EXPECT_EQ("na%22me", received[0].name);
  5578. EXPECT_EQ("quoted name", received[0].content);
  5579. EXPECT_EQ("file", received[1].name);
  5580. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5581. received[1].filename);
  5582. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5583. EXPECT_EQ("injected", received[1].content);
  5584. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5585. EXPECT_EQ("my%22file.txt", received[2].filename);
  5586. EXPECT_EQ("cr lf name", received[2].content);
  5587. EXPECT_EQ("typed", received[3].name);
  5588. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5589. received[3].content_type);
  5590. EXPECT_EQ("typed content", received[3].content);
  5591. });
  5592. auto port = svr.bind_to_any_port("localhost");
  5593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5594. auto se = detail::scope_exit([&] {
  5595. svr.stop();
  5596. t.join();
  5597. ASSERT_FALSE(svr.is_running());
  5598. });
  5599. svr.wait_until_ready();
  5600. Client cli("localhost", port);
  5601. UploadFormDataItems items = {
  5602. {"na\"me", "quoted name", "", ""},
  5603. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5604. "application/octet-stream"},
  5605. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5606. {"typed", "typed content", "",
  5607. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5608. };
  5609. auto res = cli.Post("/post", items);
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. }
  5613. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5614. const UploadFormDataItems items = {
  5615. {"name1", "Content 1", "", ""},
  5616. {"name2", "Content 2", "file2.txt", "text/plain"},
  5617. };
  5618. Server svr;
  5619. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5620. const ContentReader &content_reader) {
  5621. ASSERT_TRUE(req.is_multipart_form_data());
  5622. std::vector<FormData> received;
  5623. content_reader(
  5624. [&](const FormData &file) {
  5625. received.push_back(file);
  5626. return true;
  5627. },
  5628. [&](const char *data, size_t data_length) {
  5629. received.back().content.append(data, data_length);
  5630. return true;
  5631. });
  5632. ASSERT_EQ(2U, received.size());
  5633. EXPECT_EQ("name1", received[0].name);
  5634. EXPECT_EQ("Content 1", received[0].content);
  5635. EXPECT_EQ("name2", received[1].name);
  5636. EXPECT_EQ("Content 2", received[1].content);
  5637. EXPECT_EQ("file2.txt", received[1].filename);
  5638. EXPECT_EQ("text/plain", received[1].content_type);
  5639. });
  5640. auto port = svr.bind_to_any_port("localhost");
  5641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5642. auto se = detail::scope_exit([&] {
  5643. svr.stop();
  5644. t.join();
  5645. ASSERT_FALSE(svr.is_running());
  5646. });
  5647. svr.wait_until_ready();
  5648. Client cli("localhost", port);
  5649. // Whole-body serialization with a generated boundary
  5650. {
  5651. MultipartFormDataWriter writer;
  5652. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5653. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5654. writer.content_type());
  5655. auto body = writer.serialize(items);
  5656. EXPECT_EQ(body.size(), writer.content_length(items));
  5657. auto res = cli.Post("/post", body, writer.content_type());
  5658. ASSERT_TRUE(res);
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. }
  5661. // Per-part framing with a custom boundary via a content provider
  5662. {
  5663. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5664. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5665. MultipartFormDataWriter writer("custom-boundary_123");
  5666. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5667. std::string body;
  5668. for (const auto &item : items) {
  5669. body += writer.item_begin(item);
  5670. body += item.content;
  5671. body += MultipartFormDataWriter::item_end();
  5672. }
  5673. body += writer.finish();
  5674. EXPECT_EQ(body.size(), writer.content_length(items));
  5675. auto res = cli.Post(
  5676. "/post", body.size(),
  5677. [&](size_t offset, size_t length, DataSink &sink) {
  5678. sink.write(body.data() + offset, length);
  5679. return true;
  5680. },
  5681. writer.content_type());
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::OK_200, res->status);
  5684. }
  5685. }
  5686. TEST_F(ServerTest, PostContentReceiverGzip) {
  5687. cli_.set_compress(true);
  5688. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5689. ASSERT_TRUE(res);
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("content", res->body);
  5692. }
  5693. TEST_F(ServerTest, PutContentReceiver) {
  5694. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5695. ASSERT_TRUE(res);
  5696. ASSERT_EQ(StatusCode::OK_200, res->status);
  5697. ASSERT_EQ("content", res->body);
  5698. }
  5699. TEST_F(ServerTest, PatchContentReceiver) {
  5700. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5701. ASSERT_TRUE(res);
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ("content", res->body);
  5704. }
  5705. template <typename ClientType>
  5706. void TestWithHeadersAndContentReceiver(
  5707. ClientType &cli,
  5708. std::function<Result(ClientType &, const std::string &, const Headers &,
  5709. const std::string &, const std::string &,
  5710. ContentReceiver, DownloadProgress)>
  5711. request_func) {
  5712. Headers headers;
  5713. headers.emplace("X-Custom-Header", "test-value");
  5714. std::string received_body;
  5715. auto res = request_func(
  5716. cli, "/content_receiver", headers, "content", "application/json",
  5717. [&](const char *data, size_t data_length) {
  5718. received_body.append(data, data_length);
  5719. return true;
  5720. },
  5721. nullptr);
  5722. ASSERT_TRUE(res);
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("content", received_body);
  5725. }
  5726. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5727. #ifdef CPPHTTPLIB_SSL_ENABLED
  5728. using ClientT = SSLClient;
  5729. #else
  5730. using ClientT = Client;
  5731. #endif
  5732. TestWithHeadersAndContentReceiver<ClientT>(
  5733. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5734. const std::string &body, const std::string &content_type,
  5735. ContentReceiver receiver, DownloadProgress progress) {
  5736. return cli.Post(path, headers, body, content_type, receiver, progress);
  5737. });
  5738. }
  5739. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5740. #ifdef CPPHTTPLIB_SSL_ENABLED
  5741. using ClientT = SSLClient;
  5742. #else
  5743. using ClientT = Client;
  5744. #endif
  5745. TestWithHeadersAndContentReceiver<ClientT>(
  5746. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5747. const std::string &body, const std::string &content_type,
  5748. ContentReceiver receiver, DownloadProgress progress) {
  5749. return cli.Put(path, headers, body, content_type, receiver, progress);
  5750. });
  5751. }
  5752. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5753. #ifdef CPPHTTPLIB_SSL_ENABLED
  5754. using ClientT = SSLClient;
  5755. #else
  5756. using ClientT = Client;
  5757. #endif
  5758. TestWithHeadersAndContentReceiver<ClientT>(
  5759. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5760. const std::string &body, const std::string &content_type,
  5761. ContentReceiver receiver, DownloadProgress progress) {
  5762. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5763. });
  5764. }
  5765. template <typename ClientType>
  5766. void TestWithHeadersAndContentReceiverWithProgress(
  5767. ClientType &cli,
  5768. std::function<Result(ClientType &, const std::string &, const Headers &,
  5769. const std::string &, const std::string &,
  5770. ContentReceiver, DownloadProgress)>
  5771. request_func) {
  5772. Headers headers;
  5773. headers.emplace("X-Test-Header", "progress-test");
  5774. std::string received_body;
  5775. auto progress_called = false;
  5776. auto res = request_func(
  5777. cli, "/content_receiver", headers, "content", "text/plain",
  5778. [&](const char *data, size_t data_length) {
  5779. received_body.append(data, data_length);
  5780. return true;
  5781. },
  5782. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5783. progress_called = true;
  5784. return true;
  5785. });
  5786. ASSERT_TRUE(res);
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. EXPECT_EQ("content", received_body);
  5789. EXPECT_TRUE(progress_called);
  5790. }
  5791. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5792. #ifdef CPPHTTPLIB_SSL_ENABLED
  5793. using ClientT = SSLClient;
  5794. #else
  5795. using ClientT = Client;
  5796. #endif
  5797. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5798. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5799. const std::string &body, const std::string &content_type,
  5800. ContentReceiver receiver, DownloadProgress progress) {
  5801. return cli.Post(path, headers, body, content_type, receiver, progress);
  5802. });
  5803. }
  5804. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5805. #ifdef CPPHTTPLIB_SSL_ENABLED
  5806. using ClientT = SSLClient;
  5807. #else
  5808. using ClientT = Client;
  5809. #endif
  5810. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5811. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5812. const std::string &body, const std::string &content_type,
  5813. ContentReceiver receiver, DownloadProgress progress) {
  5814. return cli.Put(path, headers, body, content_type, receiver, progress);
  5815. });
  5816. }
  5817. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5818. #ifdef CPPHTTPLIB_SSL_ENABLED
  5819. using ClientT = SSLClient;
  5820. #else
  5821. using ClientT = Client;
  5822. #endif
  5823. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5824. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5825. const std::string &body, const std::string &content_type,
  5826. ContentReceiver receiver, DownloadProgress progress) {
  5827. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5828. });
  5829. }
  5830. template <typename ClientType>
  5831. void TestWithHeadersAndContentReceiverError(
  5832. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5833. const Headers &, const std::string &,
  5834. const std::string &, ContentReceiver)>
  5835. request_func) {
  5836. Headers headers;
  5837. headers.emplace("X-Error-Test", "true");
  5838. std::string received_body;
  5839. auto receiver_failed = false;
  5840. auto res =
  5841. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5842. [&](const char *data, size_t data_length) {
  5843. received_body.append(data, data_length);
  5844. receiver_failed = true;
  5845. return false;
  5846. });
  5847. ASSERT_FALSE(res);
  5848. EXPECT_TRUE(receiver_failed);
  5849. }
  5850. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5851. #ifdef CPPHTTPLIB_SSL_ENABLED
  5852. using ClientT = SSLClient;
  5853. #else
  5854. using ClientT = Client;
  5855. #endif
  5856. TestWithHeadersAndContentReceiverError<ClientT>(
  5857. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5858. const std::string &body, const std::string &content_type,
  5859. ContentReceiver receiver) {
  5860. return cli.Post(path, headers, body, content_type, receiver);
  5861. });
  5862. }
  5863. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5864. #ifdef CPPHTTPLIB_SSL_ENABLED
  5865. using ClientT = SSLClient;
  5866. #else
  5867. using ClientT = Client;
  5868. #endif
  5869. TestWithHeadersAndContentReceiverError<ClientT>(
  5870. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5871. const std::string &body, const std::string &content_type,
  5872. ContentReceiver receiver) {
  5873. return cli.Put(path, headers, body, content_type, receiver);
  5874. });
  5875. }
  5876. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5877. #ifdef CPPHTTPLIB_SSL_ENABLED
  5878. using ClientT = SSLClient;
  5879. #else
  5880. using ClientT = Client;
  5881. #endif
  5882. TestWithHeadersAndContentReceiverError<ClientT>(
  5883. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5884. const std::string &body, const std::string &content_type,
  5885. ContentReceiver receiver) {
  5886. return cli.Patch(path, headers, body, content_type, receiver);
  5887. });
  5888. }
  5889. TEST_F(ServerTest, PostQueryStringAndBody) {
  5890. auto res =
  5891. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5892. ASSERT_TRUE(res);
  5893. ASSERT_EQ(StatusCode::OK_200, res->status);
  5894. }
  5895. TEST_F(ServerTest, HTTP2Magic) {
  5896. Request req;
  5897. req.method = "PRI";
  5898. req.path = "*";
  5899. req.body = "SM";
  5900. auto res = std::make_shared<Response>();
  5901. auto error = Error::Success;
  5902. auto ret = cli_.send(req, *res, error);
  5903. ASSERT_TRUE(ret);
  5904. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5905. }
  5906. TEST_F(ServerTest, KeepAlive) {
  5907. auto res = cli_.Get("/hi");
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("Hello World!", res->body);
  5912. res = cli_.Get("/hi");
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5916. EXPECT_EQ("Hello World!", res->body);
  5917. res = cli_.Get("/hi");
  5918. ASSERT_TRUE(res);
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. EXPECT_EQ("Hello World!", res->body);
  5922. res = cli_.Get("/not-exist");
  5923. ASSERT_TRUE(res);
  5924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5925. res = cli_.Post("/empty", "", "text/plain");
  5926. ASSERT_TRUE(res);
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5929. EXPECT_EQ("empty", res->body);
  5930. EXPECT_EQ("close", res->get_header_value("Connection"));
  5931. res = cli_.Post(
  5932. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5933. "text/plain");
  5934. ASSERT_TRUE(res);
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5937. EXPECT_EQ("empty", res->body);
  5938. cli_.set_keep_alive(false);
  5939. res = cli_.Get("/last-request");
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. TEST_F(ServerTest, TooManyRedirect) {
  5945. cli_.set_follow_location(true);
  5946. auto res = cli_.Get("/redirect/0");
  5947. ASSERT_TRUE(!res);
  5948. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5949. }
  5950. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5951. Request req;
  5952. req.method = "FOOBAR";
  5953. req.path = "/hi";
  5954. cli_.set_keep_alive(true);
  5955. auto res = cli_.send(req);
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5958. EXPECT_EQ("close", res->get_header_value("Connection"));
  5959. EXPECT_FALSE(cli_.is_socket_open());
  5960. }
  5961. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5962. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5963. TEST_F(ServerTest, Gzip) {
  5964. Headers headers;
  5965. headers.emplace("Accept-Encoding", "gzip, deflate");
  5966. auto res = cli_.Get("/compress", headers);
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5971. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5972. "7890123456789012345678901234567890",
  5973. res->body);
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. }
  5976. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5977. Headers headers;
  5978. headers.emplace("Accept-Encoding", "gzip, deflate");
  5979. auto res = cli_.Get("/compress-with-charset", headers);
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5982. EXPECT_EQ("application/json; charset=utf-8",
  5983. res->get_header_value("Content-Type"));
  5984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5985. "7890123456789012345678901234567890",
  5986. res->body);
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. }
  5989. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5990. Headers headers;
  5991. headers.emplace("Accept-Encoding", "");
  5992. auto res = cli_.Get("/compress", headers);
  5993. ASSERT_TRUE(res);
  5994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5998. "7890123456789012345678901234567890",
  5999. res->body);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. TEST_F(ServerTest, GzipWithContentReceiver) {
  6003. Headers headers;
  6004. headers.emplace("Accept-Encoding", "gzip, deflate");
  6005. std::string body;
  6006. auto res = cli_.Get("/compress", headers,
  6007. [&](const char *data, uint64_t data_length) {
  6008. EXPECT_EQ(100U, data_length);
  6009. body.append(data, data_length);
  6010. return true;
  6011. });
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6015. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6017. "7890123456789012345678901234567890",
  6018. body);
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6022. Headers headers;
  6023. headers.emplace("Accept-Encoding", "gzip, deflate");
  6024. cli_.set_decompress(false);
  6025. auto res = cli_.Get("/compress", headers);
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(33U, res->body.size());
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. }
  6033. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6034. Headers headers;
  6035. headers.emplace("Accept-Encoding", "");
  6036. std::string body;
  6037. auto res = cli_.Get("/compress", headers,
  6038. [&](const char *data, uint64_t data_length) {
  6039. EXPECT_EQ(100U, data_length);
  6040. body.append(data, data_length);
  6041. return true;
  6042. });
  6043. ASSERT_TRUE(res);
  6044. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6046. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6047. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6048. "7890123456789012345678901234567890",
  6049. body);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. }
  6052. TEST_F(ServerTest, NoGzip) {
  6053. Headers headers;
  6054. headers.emplace("Accept-Encoding", "gzip, deflate");
  6055. auto res = cli_.Get("/nocompress", headers);
  6056. ASSERT_TRUE(res);
  6057. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6058. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6059. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6060. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6061. "7890123456789012345678901234567890",
  6062. res->body);
  6063. EXPECT_EQ(StatusCode::OK_200, res->status);
  6064. }
  6065. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6066. Headers headers;
  6067. headers.emplace("Accept-Encoding", "gzip, deflate");
  6068. std::string body;
  6069. auto res = cli_.Get("/nocompress", headers,
  6070. [&](const char *data, uint64_t data_length) {
  6071. EXPECT_EQ(100U, data_length);
  6072. body.append(data, data_length);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(res);
  6076. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6077. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6080. "7890123456789012345678901234567890",
  6081. body);
  6082. EXPECT_EQ(StatusCode::OK_200, res->status);
  6083. }
  6084. TEST_F(ServerTest, MultipartFormDataGzip) {
  6085. UploadFormDataItems items = {
  6086. {"key1", "test", "", ""},
  6087. {"key2", "--abcdefg123", "", ""},
  6088. };
  6089. cli_.set_compress(true);
  6090. auto res = cli_.Post("/compress-multipart", items);
  6091. ASSERT_TRUE(res);
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. }
  6094. #endif
  6095. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6096. TEST_F(ServerTest, Brotli) {
  6097. Headers headers;
  6098. headers.emplace("Accept-Encoding", "br");
  6099. auto res = cli_.Get("/compress", headers);
  6100. ASSERT_TRUE(res);
  6101. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6103. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6105. "7890123456789012345678901234567890",
  6106. res->body);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. #endif
  6110. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6111. TEST_F(ServerTest, Zstd) {
  6112. Headers headers;
  6113. headers.emplace("Accept-Encoding", "zstd");
  6114. auto res = cli_.Get("/compress", headers);
  6115. ASSERT_TRUE(res);
  6116. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6120. "7890123456789012345678901234567890",
  6121. res->body);
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. }
  6124. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6125. Headers headers;
  6126. headers.emplace("Accept-Encoding", "");
  6127. auto res = cli_.Get("/compress", headers);
  6128. ASSERT_TRUE(res);
  6129. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6130. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6131. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6133. "7890123456789012345678901234567890",
  6134. res->body);
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. }
  6137. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "zstd");
  6140. std::string body;
  6141. auto res = cli_.Get("/compress", headers,
  6142. [&](const char *data, uint64_t data_length) {
  6143. EXPECT_EQ(100U, data_length);
  6144. body.append(data, data_length);
  6145. return true;
  6146. });
  6147. ASSERT_TRUE(res);
  6148. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6150. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6151. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6152. "7890123456789012345678901234567890",
  6153. body);
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. }
  6156. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6157. Headers headers;
  6158. headers.emplace("Accept-Encoding", "zstd");
  6159. cli_.set_decompress(false);
  6160. auto res = cli_.Get("/compress", headers);
  6161. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6162. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6163. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6164. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6165. ASSERT_TRUE(res);
  6166. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. ASSERT_EQ(26U, res->body.size());
  6171. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6172. 0);
  6173. }
  6174. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6175. Headers headers;
  6176. headers.emplace("Accept-Encoding", "");
  6177. std::string body;
  6178. auto res = cli_.Get("/compress", headers,
  6179. [&](const char *data, uint64_t data_length) {
  6180. EXPECT_EQ(100U, data_length);
  6181. body.append(data, data_length);
  6182. return true;
  6183. });
  6184. ASSERT_TRUE(res);
  6185. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6189. "7890123456789012345678901234567890",
  6190. body);
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. }
  6193. TEST_F(ServerTest, NoZstd) {
  6194. Headers headers;
  6195. headers.emplace("Accept-Encoding", "zstd");
  6196. auto res = cli_.Get("/nocompress", headers);
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6199. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6200. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6201. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6202. "7890123456789012345678901234567890",
  6203. res->body);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. }
  6206. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6207. Headers headers;
  6208. headers.emplace("Accept-Encoding", "zstd");
  6209. std::string body;
  6210. auto res = cli_.Get("/nocompress", headers,
  6211. [&](const char *data, uint64_t data_length) {
  6212. EXPECT_EQ(100U, data_length);
  6213. body.append(data, data_length);
  6214. return true;
  6215. });
  6216. ASSERT_TRUE(res);
  6217. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6218. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6219. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6220. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6221. "7890123456789012345678901234567890",
  6222. body);
  6223. EXPECT_EQ(StatusCode::OK_200, res->status);
  6224. }
  6225. // TODO: How to enable zstd ??
  6226. TEST_F(ServerTest, MultipartFormDataZstd) {
  6227. UploadFormDataItems items = {
  6228. {"key1", "test", "", ""},
  6229. {"key2", "--abcdefg123", "", ""},
  6230. };
  6231. Headers headers;
  6232. headers.emplace("Accept-Encoding", "zstd");
  6233. cli_.set_compress(true);
  6234. auto res = cli_.Post("/compress-multipart", headers, items);
  6235. ASSERT_TRUE(res);
  6236. EXPECT_EQ(StatusCode::OK_200, res->status);
  6237. }
  6238. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6239. Headers headers;
  6240. headers.emplace("Accept-Encoding", "zstd");
  6241. cli_.set_compress(true);
  6242. auto res = cli_.Put(
  6243. "/put", headers, 3,
  6244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6245. sink.os << "PUT";
  6246. return true;
  6247. },
  6248. "text/plain");
  6249. ASSERT_TRUE(res);
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("PUT", res->body);
  6252. }
  6253. // Pre-compression logging tests
  6254. TEST_F(ServerTest, PreCompressionLogging) {
  6255. // Test data for compression (matches the actual /compress endpoint content)
  6256. const std::string test_content =
  6257. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6258. "3456789012345678901234567890";
  6259. // Variables to capture logging data
  6260. std::string pre_compression_body;
  6261. std::string pre_compression_content_type;
  6262. std::string pre_compression_content_encoding;
  6263. std::string post_compression_body;
  6264. std::string post_compression_content_type;
  6265. std::string post_compression_content_encoding;
  6266. // Set up pre-compression logger
  6267. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6268. const Response &res) {
  6269. pre_compression_body = res.body;
  6270. pre_compression_content_type = res.get_header_value("Content-Type");
  6271. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6272. });
  6273. // Set up post-compression logger
  6274. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6275. post_compression_body = res.body;
  6276. post_compression_content_type = res.get_header_value("Content-Type");
  6277. post_compression_content_encoding =
  6278. res.get_header_value("Content-Encoding");
  6279. });
  6280. // Test with gzip compression
  6281. Headers headers;
  6282. headers.emplace("Accept-Encoding", "gzip");
  6283. auto res = cli_.Get("/compress", headers);
  6284. // Verify response was compressed
  6285. ASSERT_TRUE(res);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6288. // Verify pre-compression logger captured uncompressed content
  6289. EXPECT_EQ(test_content, pre_compression_body);
  6290. EXPECT_EQ("text/plain", pre_compression_content_type);
  6291. EXPECT_TRUE(pre_compression_content_encoding
  6292. .empty()); // No encoding header before compression
  6293. // Verify post-compression logger captured compressed content
  6294. EXPECT_NE(test_content,
  6295. post_compression_body); // Should be different after compression
  6296. EXPECT_EQ("text/plain", post_compression_content_type);
  6297. EXPECT_EQ("gzip", post_compression_content_encoding);
  6298. // Verify compressed content is smaller
  6299. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6300. }
  6301. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6302. const std::string test_content =
  6303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6304. "3456789012345678901234567890";
  6305. std::string pre_compression_body;
  6306. std::string post_compression_body;
  6307. svr_.set_pre_compression_logger(
  6308. [&](const Request & /*req*/, const Response &res) {
  6309. pre_compression_body = res.body;
  6310. });
  6311. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6312. post_compression_body = res.body;
  6313. });
  6314. Headers headers;
  6315. headers.emplace("Accept-Encoding", "br");
  6316. auto res = cli_.Get("/compress", headers);
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6320. // Verify pre-compression content is uncompressed
  6321. EXPECT_EQ(test_content, pre_compression_body);
  6322. // Verify post-compression content is compressed
  6323. EXPECT_NE(test_content, post_compression_body);
  6324. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6325. }
  6326. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6327. const std::string test_content =
  6328. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6329. "3456789012345678901234567890";
  6330. std::string pre_compression_body;
  6331. std::string post_compression_body;
  6332. svr_.set_pre_compression_logger(
  6333. [&](const Request & /*req*/, const Response &res) {
  6334. pre_compression_body = res.body;
  6335. });
  6336. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6337. post_compression_body = res.body;
  6338. });
  6339. // Request without compression (use /nocompress endpoint)
  6340. Headers headers;
  6341. auto res = cli_.Get("/nocompress", headers);
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6345. // Pre-compression logger should not be called when no compression is applied
  6346. EXPECT_TRUE(
  6347. pre_compression_body.empty()); // Pre-compression logger not called
  6348. EXPECT_EQ(
  6349. test_content,
  6350. post_compression_body); // Post-compression logger captures final content
  6351. }
  6352. TEST_F(ServerTest, LoggerSeesContentLength) {
  6353. size_t logged_content_length = 0;
  6354. std::string logged_content_length_header;
  6355. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6356. logged_content_length = res.content_length_;
  6357. logged_content_length_header = res.get_header_value("Content-Length");
  6358. });
  6359. auto res = cli_.Get("/nocompress");
  6360. ASSERT_TRUE(res);
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ(res->body.size(), logged_content_length);
  6363. EXPECT_EQ(std::to_string(logged_content_length),
  6364. logged_content_length_header);
  6365. }
  6366. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6367. const std::string test_content =
  6368. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6369. "3456789012345678901234567890";
  6370. std::string pre_compression_body;
  6371. bool pre_logger_called = false;
  6372. // Set only pre-compression logger
  6373. svr_.set_pre_compression_logger(
  6374. [&](const Request & /*req*/, const Response &res) {
  6375. pre_compression_body = res.body;
  6376. pre_logger_called = true;
  6377. });
  6378. Headers headers;
  6379. headers.emplace("Accept-Encoding", "gzip");
  6380. auto res = cli_.Get("/compress", headers);
  6381. ASSERT_TRUE(res);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6384. // Verify pre-compression logger was called
  6385. EXPECT_TRUE(pre_logger_called);
  6386. EXPECT_EQ(test_content, pre_compression_body);
  6387. }
  6388. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6389. {
  6390. // Test with Expect: 100-continue header - success case
  6391. // Server returns 100 Continue, client sends body, server returns 200 OK
  6392. Request req;
  6393. req.method = "POST";
  6394. req.path = "/post-large";
  6395. req.set_header("Expect", "100-continue");
  6396. req.body = LARGE_DATA;
  6397. Response res;
  6398. auto error = Error::Success;
  6399. cli_.set_keep_alive(true);
  6400. auto ret = cli_.send(req, res, error);
  6401. EXPECT_TRUE(ret);
  6402. EXPECT_EQ(StatusCode::OK_200, res.status);
  6403. EXPECT_EQ(LARGE_DATA, res.body);
  6404. }
  6405. {
  6406. // Test with Expect: 100-continue header - error case
  6407. // Client should not send the body when server returns an error
  6408. Request req;
  6409. req.method = "POST";
  6410. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6411. req.set_header("Expect", "100-continue");
  6412. req.body = LARGE_DATA;
  6413. Response res;
  6414. auto error = Error::Success;
  6415. auto start = std::chrono::high_resolution_clock::now();
  6416. cli_.set_keep_alive(true);
  6417. auto ret = cli_.send(req, res, error);
  6418. auto end = std::chrono::high_resolution_clock::now();
  6419. auto elapsed =
  6420. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6421. .count();
  6422. // With Expect: 100-continue, request completes successfully but with error
  6423. EXPECT_TRUE(ret);
  6424. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6425. EXPECT_EQ("close", res.get_header_value("Connection"));
  6426. EXPECT_FALSE(cli_.is_socket_open());
  6427. EXPECT_LE(elapsed, 2000);
  6428. }
  6429. {
  6430. // Send an extra GET request to ensure error recovery without hanging
  6431. Request req;
  6432. req.method = "GET";
  6433. req.path = "/hi";
  6434. auto start = std::chrono::high_resolution_clock::now();
  6435. auto res = cli_.send(req);
  6436. auto end = std::chrono::high_resolution_clock::now();
  6437. auto elapsed =
  6438. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6439. .count();
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("Hello World!", res->body);
  6443. EXPECT_LE(elapsed, 500);
  6444. }
  6445. }
  6446. TEST(ZstdDecompressor, ChunkedDecompression) {
  6447. std::string data;
  6448. for (size_t i = 0; i < 32 * 1024; ++i) {
  6449. data.push_back(static_cast<char>('a' + i % 26));
  6450. }
  6451. std::string compressed_data;
  6452. {
  6453. httplib::detail::zstd_compressor compressor;
  6454. bool result = compressor.compress(
  6455. data.data(), data.size(),
  6456. /*last=*/true,
  6457. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6458. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6459. compressed_data_size);
  6460. return true;
  6461. });
  6462. ASSERT_TRUE(result);
  6463. }
  6464. std::string decompressed_data;
  6465. {
  6466. httplib::detail::zstd_decompressor decompressor;
  6467. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6468. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6469. size_t chunk_size = 130;
  6470. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6471. chunk_begin += chunk_size) {
  6472. size_t current_chunk_size =
  6473. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6474. bool result = decompressor.decompress(
  6475. compressed_data.data() + chunk_begin, current_chunk_size,
  6476. [&](const char *decompressed_data_chunk,
  6477. size_t decompressed_data_chunk_size) {
  6478. decompressed_data.insert(decompressed_data.size(),
  6479. decompressed_data_chunk,
  6480. decompressed_data_chunk_size);
  6481. return true;
  6482. });
  6483. ASSERT_TRUE(result);
  6484. }
  6485. }
  6486. ASSERT_EQ(data, decompressed_data);
  6487. }
  6488. TEST(ZstdDecompressor, Decompress) {
  6489. std::string original_text = "Compressed with ZSTD";
  6490. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6491. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6492. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6493. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6494. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6495. std::string decompressed_data;
  6496. {
  6497. httplib::detail::zstd_decompressor decompressor;
  6498. bool result = decompressor.decompress(
  6499. compressed_data.data(), compressed_data.size(),
  6500. [&](const char *decompressed_data_chunk,
  6501. size_t decompressed_data_chunk_size) {
  6502. decompressed_data.insert(decompressed_data.size(),
  6503. decompressed_data_chunk,
  6504. decompressed_data_chunk_size);
  6505. return true;
  6506. });
  6507. ASSERT_TRUE(result);
  6508. }
  6509. ASSERT_EQ(original_text, decompressed_data);
  6510. }
  6511. #endif
  6512. // Sends a raw request to a server listening at HOST:PORT.
  6513. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6514. std::string *resp = nullptr) {
  6515. auto error = Error::Success;
  6516. auto client_sock = detail::create_client_socket(
  6517. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6518. /*connection_timeout_sec=*/5, 0,
  6519. /*read_timeout_sec=*/5, 0,
  6520. /*write_timeout_sec=*/5, 0, std::string(), error);
  6521. if (client_sock == INVALID_SOCKET) { return false; }
  6522. auto ret = detail::process_client_socket(
  6523. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6524. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6525. if (req.size() !=
  6526. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6527. return false;
  6528. }
  6529. char buf[512];
  6530. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6531. while (line_reader.getline()) {
  6532. if (resp) { *resp += line_reader.ptr(); }
  6533. }
  6534. return true;
  6535. });
  6536. detail::close_socket(client_sock);
  6537. return ret;
  6538. }
  6539. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6540. Server svr;
  6541. std::string header_value;
  6542. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6543. header_value = req.get_header_value("foo");
  6544. res.set_content("ok", "text/plain");
  6545. });
  6546. thread t = thread([&] { svr.listen(HOST, PORT); });
  6547. auto se = detail::scope_exit([&] {
  6548. svr.stop();
  6549. t.join();
  6550. ASSERT_FALSE(svr.is_running());
  6551. });
  6552. svr.wait_until_ready();
  6553. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6554. // like characters are not treated the same - use vertical tab and escape.
  6555. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6556. "foo: \t \v bar \x1B\t \r\n"
  6557. "Connection: close\r\n"
  6558. "\r\n";
  6559. std::string res;
  6560. ASSERT_TRUE(send_request(5, req, &res));
  6561. EXPECT_EQ(header_value, "");
  6562. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6563. }
  6564. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6565. Server svr;
  6566. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6567. auto i = new int(0);
  6568. res.set_header("Trailer", "X-Safe, X-Reflected");
  6569. res.set_chunked_content_provider(
  6570. "text/plain",
  6571. [i](size_t /*offset*/, DataSink &sink) {
  6572. if (*i == 0) {
  6573. sink.os << "body";
  6574. } else {
  6575. Headers trailer;
  6576. // A valid trailer that must survive.
  6577. trailer.emplace("X-Safe", "safe");
  6578. // Attacker-controlled value carrying CR/LF (response splitting).
  6579. trailer.emplace("X-Reflected",
  6580. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6581. // Attacker-controlled name carrying CR/LF.
  6582. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6583. sink.done_with_trailer(trailer);
  6584. }
  6585. (*i)++;
  6586. return true;
  6587. },
  6588. [i](bool /*success*/) { delete i; });
  6589. });
  6590. thread t = thread([&] { svr.listen(HOST, PORT); });
  6591. auto se = detail::scope_exit([&] {
  6592. svr.stop();
  6593. t.join();
  6594. ASSERT_FALSE(svr.is_running());
  6595. });
  6596. svr.wait_until_ready();
  6597. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6598. "Host: " + HOST +
  6599. "\r\n"
  6600. "Connection: close\r\n"
  6601. "\r\n";
  6602. std::string res;
  6603. ASSERT_TRUE(send_request(5, req, &res));
  6604. // The injected fields must not appear anywhere in the raw response.
  6605. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6606. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6607. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6608. // Invalid trailers are dropped entirely, matching set_header().
  6609. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6610. // The valid trailer still passes through.
  6611. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6612. }
  6613. // Sends a raw request and verifies that there isn't a crash or exception.
  6614. static void test_raw_request(const std::string &req,
  6615. std::string *out = nullptr) {
  6616. Server svr;
  6617. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6618. res.set_content("ok", "text/plain");
  6619. });
  6620. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6621. res.set_content("ok", "text/plain");
  6622. });
  6623. svr.Get("/header_field_value_check",
  6624. [&](const Request & /*req*/, Response &res) {
  6625. res.set_content("ok", "text/plain");
  6626. });
  6627. // Server read timeout must be longer than the client read timeout for the
  6628. // bug to reproduce, probably to force the server to process a request
  6629. // without a trailing blank line.
  6630. const time_t client_read_timeout_sec = 1;
  6631. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6632. bool listen_thread_ok = false;
  6633. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6634. auto se = detail::scope_exit([&] {
  6635. svr.stop();
  6636. t.join();
  6637. ASSERT_FALSE(svr.is_running());
  6638. EXPECT_TRUE(listen_thread_ok);
  6639. });
  6640. svr.wait_until_ready();
  6641. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6642. }
  6643. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6644. // A certain header line causes an exception if the header property is parsed
  6645. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6646. test_raw_request(
  6647. "GET /hi HTTP/1.1\r\n"
  6648. " : "
  6649. " "
  6650. " ");
  6651. }
  6652. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6653. // A certain header line causes an exception if the header property *name* is
  6654. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6655. // greedy matcher and requires backtracking when there are a lot of ":"
  6656. // characters.
  6657. // This occurs with libc++ but not libstdc++.
  6658. test_raw_request(
  6659. "GET /hi HTTP/1.1\r\n"
  6660. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6661. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6662. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6663. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6664. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6665. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6666. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6667. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6668. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6669. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6670. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6671. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6672. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6673. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6674. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6675. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6676. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6677. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6678. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6679. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6680. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6681. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6682. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6683. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6684. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6685. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6686. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6687. "&&&%%%");
  6688. }
  6689. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6690. // Make sure this doesn't crash the server.
  6691. // In a previous version of the header line regex, the "\r" rendered the line
  6692. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6693. // a new position where the leading white space ended and the field value
  6694. // began.
  6695. // The crash occurs with libc++ but not libstdc++.
  6696. test_raw_request("GET /hi HTTP/1.1\r\n"
  6697. "a:" +
  6698. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6699. "\r\n"
  6700. "\r\n");
  6701. }
  6702. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6703. std::string out;
  6704. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6705. "Content-Type: text/plain\r\n"
  6706. "Transfer-Encoding: chunked\r\n"
  6707. "\r\n"
  6708. "nothex\r\n",
  6709. &out);
  6710. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6711. }
  6712. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6713. std::string out;
  6714. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6715. "Content-Type: text/plain\r\n"
  6716. "Transfer-Encoding: chunked\r\n"
  6717. "\r\n"
  6718. "3\r\n"
  6719. "xyz\r\n"
  6720. "NaN\r\n",
  6721. &out);
  6722. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6723. }
  6724. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6725. std::string out;
  6726. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6727. "Content-Type: text/plain\r\n"
  6728. "Transfer-Encoding: chunked\r\n"
  6729. "\r\n"
  6730. // Length is too large for 64 bits.
  6731. "1ffffffffffffffff\r\n"
  6732. "xyz\r\n",
  6733. &out);
  6734. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6735. }
  6736. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6737. test_raw_request("GET /hi HTTP/1.1\r\n"
  6738. "Content-Type: text/plain\r\n\r");
  6739. }
  6740. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6741. std::string out;
  6742. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6743. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6744. }
  6745. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6746. Server svr;
  6747. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6748. EXPECT_TRUE(!req.remote_addr.empty());
  6749. });
  6750. thread t = thread([&] { svr.listen(HOST, PORT); });
  6751. auto se = detail::scope_exit([&] {
  6752. svr.stop();
  6753. t.join();
  6754. ASSERT_FALSE(svr.is_running());
  6755. });
  6756. svr.wait_until_ready();
  6757. // Send an invalid request line to trigger Bad Request
  6758. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6759. std::string out;
  6760. ASSERT_TRUE(send_request(5, bad_req, &out));
  6761. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6762. }
  6763. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6764. std::string out;
  6765. std::string request(
  6766. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6767. test_raw_request(request, &out);
  6768. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6769. }
  6770. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6771. std::string out;
  6772. std::string request(
  6773. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6774. test_raw_request(request, &out);
  6775. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6776. }
  6777. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6778. std::string out;
  6779. std::string request(
  6780. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6781. test_raw_request(request, &out);
  6782. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6783. }
  6784. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6785. std::string out;
  6786. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6787. "Test: \r\n\r\n",
  6788. &out);
  6789. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6790. }
  6791. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6792. Server svr;
  6793. std::string x_custom;
  6794. std::string cookie;
  6795. std::string xff;
  6796. std::string x_unicode;
  6797. std::string x_iis;
  6798. svr.Get("/check", [&](const Request &req, Response &res) {
  6799. x_custom = req.get_header_value("X-Custom");
  6800. cookie = req.get_header_value("Cookie");
  6801. xff = req.get_header_value("X-Forwarded-For");
  6802. x_unicode = req.get_header_value("X-Unicode");
  6803. x_iis = req.get_header_value("X-IIS");
  6804. res.set_content("ok", "text/plain");
  6805. });
  6806. thread t = thread([&] { svr.listen(HOST, PORT); });
  6807. auto se = detail::scope_exit([&] {
  6808. svr.stop();
  6809. t.join();
  6810. ASSERT_FALSE(svr.is_running());
  6811. });
  6812. svr.wait_until_ready();
  6813. const std::string req = "GET /check HTTP/1.1\r\n"
  6814. "Host: localhost\r\n"
  6815. "X-Custom: a%0D%0AInjected: b\r\n"
  6816. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6817. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6818. "X-Unicode: %E3%81%82\r\n"
  6819. "X-IIS: %u00E9\r\n"
  6820. "Connection: close\r\n"
  6821. "\r\n";
  6822. std::string res;
  6823. ASSERT_TRUE(send_request(5, req, &res));
  6824. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6825. // Every value must be returned verbatim (wire form), with no decoding.
  6826. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6827. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6828. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6829. EXPECT_EQ("%E3%81%82", x_unicode);
  6830. EXPECT_EQ("%u00E9", x_iis);
  6831. }
  6832. // Applications that previously relied on automatic percent-decoding can
  6833. // reproduce the old behavior by explicitly calling decode_path_component()
  6834. // or, for RFC 3986 conformance, decode_uri_component().
  6835. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6836. Server svr;
  6837. std::string decoded;
  6838. svr.Get("/check", [&](const Request &req, Response &res) {
  6839. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6840. res.set_content("ok", "text/plain");
  6841. });
  6842. thread t = thread([&] { svr.listen(HOST, PORT); });
  6843. auto se = detail::scope_exit([&] {
  6844. svr.stop();
  6845. t.join();
  6846. ASSERT_FALSE(svr.is_running());
  6847. });
  6848. svr.wait_until_ready();
  6849. const std::string req = "GET /check HTTP/1.1\r\n"
  6850. "Host: localhost\r\n"
  6851. "X-Custom: hello%20world\r\n"
  6852. "Connection: close\r\n"
  6853. "\r\n";
  6854. std::string res;
  6855. ASSERT_TRUE(send_request(5, req, &res));
  6856. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6857. EXPECT_EQ("hello world", decoded);
  6858. }
  6859. // Regression test for #2033. Browsers send Referer values that include
  6860. // percent-encoded characters such as %0A inside the URL. Decoding the
  6861. // header value would either trip the post-decode CR/LF/NUL guard (the
  6862. // original bug, returning 400) or, after that guard was relaxed, silently
  6863. // store a literal LF — both unacceptable. The wire form must round-trip.
  6864. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6865. Server svr;
  6866. std::string referer;
  6867. svr.Get("/check", [&](const Request &req, Response &res) {
  6868. referer = req.get_header_value("Referer");
  6869. res.set_content("ok", "text/plain");
  6870. });
  6871. thread t = thread([&] { svr.listen(HOST, PORT); });
  6872. auto se = detail::scope_exit([&] {
  6873. svr.stop();
  6874. t.join();
  6875. ASSERT_FALSE(svr.is_running());
  6876. });
  6877. svr.wait_until_ready();
  6878. const std::string req = "GET /check HTTP/1.1\r\n"
  6879. "Host: localhost\r\n"
  6880. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6881. "Connection: close\r\n"
  6882. "\r\n";
  6883. std::string res;
  6884. ASSERT_TRUE(send_request(5, req, &res));
  6885. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6886. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6887. }
  6888. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6889. Server svr;
  6890. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6891. res.set_header("Cache-Control", "no-cache");
  6892. res.set_chunked_content_provider(
  6893. "text/event-stream", [](size_t offset, DataSink &sink) {
  6894. std::string s = "data:";
  6895. s += std::to_string(offset);
  6896. s += "\n\n";
  6897. auto ret = sink.write(s.data(), s.size());
  6898. EXPECT_TRUE(ret);
  6899. std::this_thread::sleep_for(std::chrono::seconds(1));
  6900. return true;
  6901. });
  6902. });
  6903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6904. svr.wait_until_ready();
  6905. Client client(HOST, PORT);
  6906. const Headers headers = {{"Accept", "text/event-stream"}};
  6907. auto get_thread = std::thread([&client, &headers]() {
  6908. auto res = client.Get(
  6909. "/events", headers,
  6910. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6911. });
  6912. auto se = detail::scope_exit([&] {
  6913. svr.stop();
  6914. get_thread.join();
  6915. listen_thread.join();
  6916. ASSERT_FALSE(svr.is_running());
  6917. });
  6918. // Give GET time to get a few messages.
  6919. std::this_thread::sleep_for(std::chrono::seconds(2));
  6920. }
  6921. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6922. httplib::Server svr;
  6923. svr.Post("/hi",
  6924. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6925. res.status = StatusCode::OK_200;
  6926. });
  6927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6928. svr.wait_until_ready();
  6929. Client cli(HOST, PORT);
  6930. auto res = cli.Post("/hi", "data", "text/plain");
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. svr.stop();
  6934. thread.join();
  6935. ASSERT_FALSE(svr.is_running());
  6936. res = cli.Post("/hi", "data", "text/plain");
  6937. ASSERT_FALSE(res);
  6938. }
  6939. TEST(ServerStopTest, ListenFailure) {
  6940. Server svr;
  6941. auto t = thread([&]() {
  6942. auto ret = svr.listen("????", PORT);
  6943. EXPECT_FALSE(ret);
  6944. });
  6945. svr.wait_until_ready();
  6946. svr.stop();
  6947. t.join();
  6948. }
  6949. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6950. TEST(ServerStopTest, Decommision) {
  6951. Server svr;
  6952. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6953. for (int i = 0; i < 4; i++) {
  6954. auto is_even = !(i % 2);
  6955. std::thread t{[&] {
  6956. try {
  6957. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6958. if (is_even) {
  6959. throw std::runtime_error("Some thing that happens to go wrong.");
  6960. }
  6961. svr.listen(HOST, PORT);
  6962. } catch (...) { svr.decommission(); }
  6963. }};
  6964. svr.wait_until_ready();
  6965. // Server is up
  6966. {
  6967. Client cli(HOST, PORT);
  6968. auto res = cli.Get("/hi");
  6969. if (is_even) {
  6970. EXPECT_FALSE(res);
  6971. } else {
  6972. EXPECT_TRUE(res);
  6973. EXPECT_EQ("hi...", res->body);
  6974. }
  6975. }
  6976. svr.stop();
  6977. t.join();
  6978. // Server is down...
  6979. {
  6980. Client cli(HOST, PORT);
  6981. auto res = cli.Get("/hi");
  6982. EXPECT_FALSE(res);
  6983. }
  6984. }
  6985. }
  6986. #endif
  6987. // Helper function for string body upload progress tests
  6988. template <typename SetupHandler, typename ClientCall>
  6989. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6990. ClientCall &&client_call,
  6991. const string &body) {
  6992. Server svr;
  6993. setup_handler(svr);
  6994. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6995. auto se = detail::scope_exit([&] {
  6996. svr.stop();
  6997. t.join();
  6998. });
  6999. svr.wait_until_ready();
  7000. Client cli(HOST, PORT);
  7001. vector<uint64_t> progress_values;
  7002. bool progress_called = false;
  7003. auto res =
  7004. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7005. progress_values.push_back(current);
  7006. progress_called = true;
  7007. return true;
  7008. });
  7009. ASSERT_TRUE(res);
  7010. EXPECT_EQ(200, res->status);
  7011. EXPECT_TRUE(progress_called);
  7012. }
  7013. TEST(UploadProgressTest, PostStringBodyBasic) {
  7014. TestStringBodyUploadProgress(
  7015. [](Server &svr) {
  7016. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7017. res.set_content("received", "text/plain");
  7018. });
  7019. },
  7020. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7021. return cli.Post("/test", body, "text/plain", progress_callback);
  7022. },
  7023. "test data for upload progress");
  7024. }
  7025. TEST(UploadProgressTest, PutStringBodyBasic) {
  7026. TestStringBodyUploadProgress(
  7027. [](Server &svr) {
  7028. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7029. res.set_content("put received", "text/plain");
  7030. });
  7031. },
  7032. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7033. return cli.Put("/test", body, "text/plain", progress_callback);
  7034. },
  7035. "put test data for upload progress");
  7036. }
  7037. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7038. TestStringBodyUploadProgress(
  7039. [](Server &svr) {
  7040. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7041. res.set_content("patch received", "text/plain");
  7042. });
  7043. },
  7044. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7045. return cli.Patch("/test", body, "text/plain", progress_callback);
  7046. },
  7047. "patch test data for upload progress");
  7048. }
  7049. // Helper function for content provider upload progress tests
  7050. template <typename SetupHandler, typename ClientCall>
  7051. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7052. ClientCall &&client_call) {
  7053. Server svr;
  7054. setup_handler(svr);
  7055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7056. auto se = detail::scope_exit([&] {
  7057. svr.stop();
  7058. t.join();
  7059. });
  7060. svr.wait_until_ready();
  7061. Client cli(HOST, PORT);
  7062. vector<uint64_t> progress_values;
  7063. auto res =
  7064. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7065. progress_values.push_back(current);
  7066. return true;
  7067. });
  7068. ASSERT_TRUE(res);
  7069. EXPECT_EQ(200, res->status);
  7070. EXPECT_FALSE(progress_values.empty());
  7071. }
  7072. TEST(UploadProgressTest, PostContentProviderProgress) {
  7073. TestContentProviderUploadProgress(
  7074. [](Server &svr) {
  7075. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7076. res.set_content("provider received", "text/plain");
  7077. });
  7078. },
  7079. [](Client &cli, UploadProgress progress_callback) {
  7080. return cli.Post(
  7081. "/test", 10,
  7082. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7083. sink.os << "test data";
  7084. return true;
  7085. },
  7086. "text/plain", progress_callback);
  7087. });
  7088. }
  7089. // Helper function for multipart upload progress tests
  7090. template <typename SetupHandler, typename ClientCall>
  7091. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7092. ClientCall &&client_call,
  7093. const string &endpoint) {
  7094. Server svr;
  7095. setup_handler(svr);
  7096. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7097. auto se = detail::scope_exit([&] {
  7098. svr.stop();
  7099. t.join();
  7100. });
  7101. svr.wait_until_ready();
  7102. Client cli(HOST, PORT);
  7103. vector<uint64_t> progress_values;
  7104. UploadFormDataItems items = {
  7105. {"field1", "value1", "", ""},
  7106. {"field2", "longer value for progress tracking test", "", ""},
  7107. {"file1", "file content data for upload progress", "test.txt",
  7108. "text/plain"}};
  7109. auto res = client_call(cli, endpoint, items,
  7110. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7111. progress_values.push_back(current);
  7112. return true;
  7113. });
  7114. ASSERT_TRUE(res);
  7115. EXPECT_EQ(200, res->status);
  7116. EXPECT_FALSE(progress_values.empty());
  7117. }
  7118. TEST(UploadProgressTest, PostMultipartProgress) {
  7119. TestMultipartUploadProgress(
  7120. [](Server &svr) {
  7121. svr.Post("/multipart", [](const Request &req, Response &res) {
  7122. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7123. res.set_content("multipart received", "text/plain");
  7124. });
  7125. },
  7126. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7127. UploadProgress progress_callback) {
  7128. return cli.Post(endpoint, items, progress_callback);
  7129. },
  7130. "/multipart");
  7131. }
  7132. // Helper function for basic download progress tests
  7133. template <typename SetupHandler, typename ClientCall>
  7134. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7135. ClientCall &&client_call, const string &endpoint,
  7136. size_t expected_content_size) {
  7137. Server svr;
  7138. setup_handler(svr);
  7139. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7140. auto se = detail::scope_exit([&] {
  7141. svr.stop();
  7142. t.join();
  7143. });
  7144. svr.wait_until_ready();
  7145. Client cli(HOST, PORT);
  7146. vector<uint64_t> progress_values;
  7147. auto res = client_call(cli, endpoint,
  7148. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7149. progress_values.push_back(current);
  7150. return true;
  7151. });
  7152. ASSERT_TRUE(res);
  7153. EXPECT_EQ(200, res->status);
  7154. EXPECT_FALSE(progress_values.empty());
  7155. EXPECT_EQ(expected_content_size, res->body.size());
  7156. }
  7157. TEST(DownloadProgressTest, GetBasic) {
  7158. TestBasicDownloadProgress(
  7159. [](Server &svr) {
  7160. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7161. string content(1000, 'D');
  7162. res.set_content(content, "text/plain");
  7163. });
  7164. },
  7165. [](Client &cli, const string &endpoint,
  7166. DownloadProgress progress_callback) {
  7167. return cli.Get(endpoint, progress_callback);
  7168. },
  7169. "/download", 1000u);
  7170. }
  7171. // Helper function for content receiver download progress tests
  7172. template <typename SetupHandler, typename ClientCall>
  7173. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7174. ClientCall &&client_call,
  7175. const string &endpoint,
  7176. size_t expected_content_size) {
  7177. Server svr;
  7178. setup_handler(svr);
  7179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7180. auto se = detail::scope_exit([&] {
  7181. svr.stop();
  7182. t.join();
  7183. });
  7184. svr.wait_until_ready();
  7185. Client cli(HOST, PORT);
  7186. vector<uint64_t> progress_values;
  7187. string received_body;
  7188. auto res = client_call(
  7189. cli, endpoint,
  7190. [&](const char *data, size_t data_length) -> bool {
  7191. received_body.append(data, data_length);
  7192. return true;
  7193. },
  7194. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7195. progress_values.push_back(current);
  7196. return true;
  7197. });
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(200, res->status);
  7200. EXPECT_FALSE(progress_values.empty());
  7201. EXPECT_EQ(expected_content_size, received_body.size());
  7202. EXPECT_TRUE(res->body.empty());
  7203. }
  7204. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7205. TestContentReceiverDownloadProgress(
  7206. [](Server &svr) {
  7207. svr.Get("/download-receiver",
  7208. [](const Request & /*req*/, Response &res) {
  7209. string content(2000, 'R');
  7210. res.set_content(content, "text/plain");
  7211. });
  7212. },
  7213. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7214. DownloadProgress progress_callback) {
  7215. return cli.Get(endpoint, content_receiver, progress_callback);
  7216. },
  7217. "/download-receiver", 2000u);
  7218. }
  7219. TEST(StreamingTest, NoContentLengthStreaming) {
  7220. Server svr;
  7221. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7222. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7223. if (offset < 6) {
  7224. sink.os << (offset < 3 ? "a" : "b");
  7225. } else {
  7226. sink.done();
  7227. }
  7228. return true;
  7229. });
  7230. });
  7231. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7232. auto listen_se = detail::scope_exit([&] {
  7233. svr.stop();
  7234. listen_thread.join();
  7235. ASSERT_FALSE(svr.is_running());
  7236. });
  7237. svr.wait_until_ready();
  7238. Client client(HOST, PORT);
  7239. auto get_thread = std::thread([&client]() {
  7240. std::string s;
  7241. auto res =
  7242. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7243. s += std::string(data, len);
  7244. return true;
  7245. });
  7246. ASSERT_TRUE(res);
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. EXPECT_EQ("aaabbb", s);
  7249. });
  7250. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7251. // Give GET time to get a few messages.
  7252. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7253. }
  7254. TEST(MountTest, Unmount) {
  7255. Server svr;
  7256. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7257. auto se = detail::scope_exit([&] {
  7258. svr.stop();
  7259. listen_thread.join();
  7260. ASSERT_FALSE(svr.is_running());
  7261. });
  7262. svr.wait_until_ready();
  7263. Client cli("localhost", PORT);
  7264. svr.set_mount_point("/mount2", "./www2");
  7265. auto res = cli.Get("/");
  7266. ASSERT_TRUE(res);
  7267. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7268. res = cli.Get("/mount2/dir/test.html");
  7269. ASSERT_TRUE(res);
  7270. EXPECT_EQ(StatusCode::OK_200, res->status);
  7271. svr.set_mount_point("/", "./www");
  7272. res = cli.Get("/dir/");
  7273. ASSERT_TRUE(res);
  7274. EXPECT_EQ(StatusCode::OK_200, res->status);
  7275. svr.remove_mount_point("/");
  7276. res = cli.Get("/dir/");
  7277. ASSERT_TRUE(res);
  7278. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7279. svr.remove_mount_point("/mount2");
  7280. res = cli.Get("/mount2/dir/test.html");
  7281. ASSERT_TRUE(res);
  7282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7283. }
  7284. TEST(MountTest, Redicect) {
  7285. Server svr;
  7286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7287. auto se = detail::scope_exit([&] {
  7288. svr.stop();
  7289. listen_thread.join();
  7290. ASSERT_FALSE(svr.is_running());
  7291. });
  7292. svr.set_mount_point("/", "./www");
  7293. svr.wait_until_ready();
  7294. Client cli("localhost", PORT);
  7295. auto res = cli.Get("/dir/");
  7296. ASSERT_TRUE(res);
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. res = cli.Get("/dir");
  7299. ASSERT_TRUE(res);
  7300. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7301. res = cli.Get("/file");
  7302. ASSERT_TRUE(res);
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. res = cli.Get("/file/");
  7305. ASSERT_TRUE(res);
  7306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7307. cli.set_follow_location(true);
  7308. res = cli.Get("/dir");
  7309. ASSERT_TRUE(res);
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. }
  7312. TEST(MountTest, MultibytesPathName) {
  7313. Server svr;
  7314. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7315. auto se = detail::scope_exit([&] {
  7316. svr.stop();
  7317. listen_thread.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. });
  7320. svr.set_mount_point("/", "./www");
  7321. svr.wait_until_ready();
  7322. Client cli("localhost", PORT);
  7323. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7324. ASSERT_TRUE(res);
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7327. }
  7328. #ifdef _WIN32
  7329. // Issue #2435: mmap::open() must succeed even when another handle holds
  7330. // the file open for writing (e.g. an active log file).
  7331. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7332. const char *path = "mmap_concurrent_writer_test.txt";
  7333. const char *content = "hello";
  7334. {
  7335. std::ofstream f(path, std::ios::binary);
  7336. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7337. }
  7338. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7339. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7340. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7341. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7342. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7343. detail::mmap m(path);
  7344. ASSERT_TRUE(m.is_open());
  7345. EXPECT_EQ(strlen(content), m.size());
  7346. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7347. }
  7348. #endif
  7349. TEST(KeepAliveTest, ReadTimeout) {
  7350. Server svr;
  7351. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7352. std::this_thread::sleep_for(std::chrono::seconds(2));
  7353. res.set_content("a", "text/plain");
  7354. });
  7355. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7356. res.set_content("b", "text/plain");
  7357. });
  7358. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7359. auto se = detail::scope_exit([&] {
  7360. svr.stop();
  7361. listen_thread.join();
  7362. ASSERT_FALSE(svr.is_running());
  7363. });
  7364. svr.wait_until_ready();
  7365. Client cli("localhost", PORT);
  7366. cli.set_keep_alive(true);
  7367. cli.set_read_timeout(std::chrono::seconds(1));
  7368. auto resa = cli.Get("/a");
  7369. ASSERT_FALSE(resa);
  7370. EXPECT_EQ(Error::Read, resa.error());
  7371. auto resb = cli.Get("/b");
  7372. ASSERT_TRUE(resb);
  7373. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7374. EXPECT_EQ("b", resb->body);
  7375. }
  7376. TEST(KeepAliveTest, MaxCount) {
  7377. size_t keep_alive_max_count = 3;
  7378. Server svr;
  7379. svr.set_keep_alive_max_count(keep_alive_max_count);
  7380. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7381. res.set_content("Hello World!", "text/plain");
  7382. });
  7383. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. listen_thread.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. Client cli(HOST, PORT);
  7391. cli.set_keep_alive(true);
  7392. for (size_t i = 0; i < 5; i++) {
  7393. auto result = cli.Get("/hi");
  7394. ASSERT_TRUE(result);
  7395. EXPECT_EQ(StatusCode::OK_200, result->status);
  7396. if (i == keep_alive_max_count - 1) {
  7397. EXPECT_EQ("close", result->get_header_value("Connection"));
  7398. } else {
  7399. EXPECT_FALSE(result->has_header("Connection"));
  7400. }
  7401. }
  7402. }
  7403. TEST(KeepAliveTest, Issue1041) {
  7404. Server svr;
  7405. svr.set_keep_alive_timeout(3);
  7406. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7407. res.set_content("Hello World!", "text/plain");
  7408. });
  7409. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7410. auto se = detail::scope_exit([&] {
  7411. svr.stop();
  7412. listen_thread.join();
  7413. ASSERT_FALSE(svr.is_running());
  7414. });
  7415. svr.wait_until_ready();
  7416. Client cli(HOST, PORT);
  7417. cli.set_keep_alive(true);
  7418. auto result = cli.Get("/hi");
  7419. ASSERT_TRUE(result);
  7420. EXPECT_EQ(StatusCode::OK_200, result->status);
  7421. std::this_thread::sleep_for(std::chrono::seconds(5));
  7422. result = cli.Get("/hi");
  7423. ASSERT_TRUE(result);
  7424. EXPECT_EQ(StatusCode::OK_200, result->status);
  7425. }
  7426. TEST(KeepAliveTest, Issue1959) {
  7427. Server svr;
  7428. svr.set_keep_alive_timeout(5);
  7429. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7430. res.set_content("a", "text/plain");
  7431. });
  7432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7433. auto se = detail::scope_exit([&] {
  7434. if (!svr.is_running()) return;
  7435. svr.stop();
  7436. listen_thread.join();
  7437. ASSERT_FALSE(svr.is_running());
  7438. });
  7439. svr.wait_until_ready();
  7440. Client cli("localhost", PORT);
  7441. cli.set_keep_alive(true);
  7442. using namespace std::chrono;
  7443. auto start = steady_clock::now();
  7444. cli.Get("/a");
  7445. svr.stop();
  7446. listen_thread.join();
  7447. auto end = steady_clock::now();
  7448. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7449. EXPECT_LT(elapsed, 5000);
  7450. }
  7451. #ifdef CPPHTTPLIB_SSL_ENABLED
  7452. TEST(KeepAliveTest, SSLClientReconnection) {
  7453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7454. ASSERT_TRUE(svr.is_valid());
  7455. svr.set_keep_alive_timeout(1);
  7456. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7457. res.set_content("Hello World!", "text/plain");
  7458. });
  7459. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7460. auto se = detail::scope_exit([&] {
  7461. svr.stop();
  7462. listen_thread.join();
  7463. ASSERT_FALSE(svr.is_running());
  7464. });
  7465. svr.wait_until_ready();
  7466. SSLClient cli(HOST, PORT);
  7467. cli.enable_server_certificate_verification(false);
  7468. cli.set_keep_alive(true);
  7469. auto result = cli.Get("/hi");
  7470. ASSERT_TRUE(result);
  7471. EXPECT_EQ(StatusCode::OK_200, result->status);
  7472. result = cli.Get("/hi");
  7473. ASSERT_TRUE(result);
  7474. EXPECT_EQ(StatusCode::OK_200, result->status);
  7475. std::this_thread::sleep_for(std::chrono::seconds(2));
  7476. // Recoonect
  7477. result = cli.Get("/hi");
  7478. ASSERT_TRUE(result);
  7479. EXPECT_EQ(StatusCode::OK_200, result->status);
  7480. result = cli.Get("/hi");
  7481. ASSERT_TRUE(result);
  7482. EXPECT_EQ(StatusCode::OK_200, result->status);
  7483. }
  7484. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7486. ASSERT_TRUE(svr.is_valid());
  7487. svr.set_keep_alive_timeout(1);
  7488. std::string content = "reconnect";
  7489. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7490. res.set_content("Hello World!", "text/plain");
  7491. });
  7492. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7493. auto se = detail::scope_exit([&] {
  7494. svr.stop();
  7495. listen_thread.join();
  7496. ASSERT_FALSE(svr.is_running());
  7497. });
  7498. svr.wait_until_ready();
  7499. SSLClient cli(HOST, PORT);
  7500. cli.enable_server_certificate_verification(false);
  7501. cli.set_keep_alive(true);
  7502. auto result = cli.Post(
  7503. "/hi", content.size(),
  7504. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7505. sink.write(content.c_str(), content.size());
  7506. return true;
  7507. },
  7508. "text/plain");
  7509. ASSERT_TRUE(result);
  7510. EXPECT_EQ(200, result->status);
  7511. std::this_thread::sleep_for(std::chrono::seconds(2));
  7512. // Recoonect
  7513. result = cli.Post(
  7514. "/hi", content.size(),
  7515. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7516. sink.write(content.c_str(), content.size());
  7517. return true;
  7518. },
  7519. "text/plain");
  7520. ASSERT_TRUE(result);
  7521. EXPECT_EQ(200, result->status);
  7522. result = cli.Post(
  7523. "/hi", content.size(),
  7524. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7525. sink.write(content.c_str(), content.size());
  7526. return true;
  7527. },
  7528. "text/plain");
  7529. ASSERT_TRUE(result);
  7530. EXPECT_EQ(200, result->status);
  7531. }
  7532. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7533. using namespace httplib::tls;
  7534. {
  7535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7536. ASSERT_TRUE(svr.is_valid());
  7537. svr.Get("/sni", [&](const Request &req, Response &res) {
  7538. std::string expected = req.sni();
  7539. EXPECT_EQ(expected, req.get_param_value("expected"));
  7540. res.set_content("ok", "text/plain");
  7541. });
  7542. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7543. auto se = detail::scope_exit([&] {
  7544. svr.stop();
  7545. listen_thread.join();
  7546. ASSERT_FALSE(svr.is_running());
  7547. });
  7548. svr.wait_until_ready();
  7549. {
  7550. SSLClient cli("localhost", PORT);
  7551. cli.enable_server_certificate_verification(false);
  7552. auto res = cli.Get("/sni?expected=localhost");
  7553. ASSERT_TRUE(res);
  7554. }
  7555. {
  7556. SSLClient cli("::1", PORT);
  7557. cli.enable_server_certificate_verification(false);
  7558. auto res = cli.Get("/sni?expected=");
  7559. // NOTE: This may fail if the server is listening on IPv4 only
  7560. // (e.g., when localhost resolves to 127.0.0.1 only)
  7561. if (res) {
  7562. EXPECT_EQ(StatusCode::OK_200, res->status);
  7563. } else {
  7564. EXPECT_EQ(Error::Connection, res.error());
  7565. }
  7566. }
  7567. }
  7568. }
  7569. #endif
  7570. TEST(ClientProblemDetectionTest, ContentProvider) {
  7571. Server svr;
  7572. size_t content_length = 1024 * 1024;
  7573. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7574. res.set_content_provider(
  7575. content_length, "text/plain",
  7576. [&](size_t offset, size_t length, DataSink &sink) {
  7577. auto out_len = std::min(length, static_cast<size_t>(1024));
  7578. std::string out(out_len, '@');
  7579. sink.write(out.data(), out_len);
  7580. return offset < 4096;
  7581. },
  7582. [](bool success) { ASSERT_FALSE(success); });
  7583. });
  7584. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7585. res.set_content_provider(
  7586. 0, "text/plain",
  7587. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7588. EXPECT_TRUE(false);
  7589. return true;
  7590. },
  7591. [](bool success) { ASSERT_FALSE(success); });
  7592. });
  7593. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7594. auto se = detail::scope_exit([&] {
  7595. svr.stop();
  7596. listen_thread.join();
  7597. ASSERT_FALSE(svr.is_running());
  7598. });
  7599. svr.wait_until_ready();
  7600. Client cli("localhost", PORT);
  7601. {
  7602. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7603. size_t /*data_length*/) { return false; });
  7604. ASSERT_FALSE(res);
  7605. }
  7606. {
  7607. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7608. size_t /*data_length*/) { return false; });
  7609. ASSERT_TRUE(res);
  7610. }
  7611. }
  7612. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7613. Server svr;
  7614. svr.set_error_handler([](Request const &, Response &res) -> void {
  7615. res.set_chunked_content_provider(
  7616. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7617. sink.os << "hello";
  7618. sink.os << "world";
  7619. sink.done();
  7620. return true;
  7621. });
  7622. });
  7623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7624. auto se = detail::scope_exit([&] {
  7625. svr.stop();
  7626. listen_thread.join();
  7627. ASSERT_FALSE(svr.is_running());
  7628. });
  7629. svr.wait_until_ready();
  7630. Client cli("localhost", PORT);
  7631. auto res = cli.Get("/");
  7632. ASSERT_TRUE(res);
  7633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7634. EXPECT_EQ("helloworld", res->body);
  7635. }
  7636. TEST(LongPollingTest, ClientCloseDetection) {
  7637. Server svr;
  7638. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7639. res.set_chunked_content_provider(
  7640. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7641. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7642. sink.os << "hello";
  7643. auto count = 10;
  7644. while (count > 0 && sink.is_writable()) {
  7645. this_thread::sleep_for(chrono::milliseconds(10));
  7646. count--;
  7647. }
  7648. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7649. return true;
  7650. });
  7651. });
  7652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7653. auto se = detail::scope_exit([&] {
  7654. svr.stop();
  7655. listen_thread.join();
  7656. ASSERT_FALSE(svr.is_running());
  7657. });
  7658. svr.wait_until_ready();
  7659. Client cli("localhost", PORT);
  7660. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7661. EXPECT_EQ("hello", string(data, data_length));
  7662. return false; // close the socket immediately.
  7663. });
  7664. ASSERT_FALSE(res);
  7665. }
  7666. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7667. Server svr;
  7668. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7669. res.set_chunked_content_provider(
  7670. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7671. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7672. sink.os << "hello";
  7673. EXPECT_TRUE(sink.os.good());
  7674. // Wait for the client to close the connection
  7675. auto count = 10;
  7676. while (count > 0 && sink.is_writable()) {
  7677. this_thread::sleep_for(chrono::milliseconds(10));
  7678. count--;
  7679. }
  7680. // After client disconnect, write repeatedly until the socket
  7681. // write actually fails (small writes may be absorbed by the
  7682. // kernel buffer)
  7683. std::string chunk(1024, 'x');
  7684. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7685. sink.os << chunk;
  7686. }
  7687. EXPECT_TRUE(sink.os.fail());
  7688. return true;
  7689. });
  7690. });
  7691. auto port = svr.bind_to_any_port("localhost");
  7692. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. listen_thread.join();
  7696. ASSERT_FALSE(svr.is_running());
  7697. });
  7698. svr.wait_until_ready();
  7699. Client cli("localhost", port);
  7700. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7701. EXPECT_EQ("hello", string(data, data_length));
  7702. return false; // close the socket immediately.
  7703. });
  7704. ASSERT_FALSE(res);
  7705. }
  7706. TEST(GetWithParametersTest, GetWithParameters) {
  7707. Server svr;
  7708. svr.Get("/", [&](const Request &req, Response &) {
  7709. EXPECT_EQ("world", req.get_param_value("hello"));
  7710. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7711. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7712. });
  7713. svr.Get("/params", [&](const Request &req, Response &) {
  7714. EXPECT_EQ("world", req.get_param_value("hello"));
  7715. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7716. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7717. });
  7718. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7719. EXPECT_EQ("resource-id", req.matches[1]);
  7720. EXPECT_EQ("foo", req.get_param_value("param1"));
  7721. EXPECT_EQ("bar", req.get_param_value("param2"));
  7722. });
  7723. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7724. EXPECT_EQ("user-id", req.path_params.at("id"));
  7725. EXPECT_EQ("foo", req.get_param_value("param1"));
  7726. EXPECT_EQ("bar", req.get_param_value("param2"));
  7727. });
  7728. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. listen_thread.join();
  7732. ASSERT_FALSE(svr.is_running());
  7733. });
  7734. svr.wait_until_ready();
  7735. {
  7736. Client cli(HOST, PORT);
  7737. Params params;
  7738. params.emplace("hello", "world");
  7739. params.emplace("hello2", "world2");
  7740. params.emplace("hello3", "world3");
  7741. auto res = cli.Get("/", params, Headers{});
  7742. ASSERT_TRUE(res);
  7743. EXPECT_EQ(StatusCode::OK_200, res->status);
  7744. }
  7745. {
  7746. Client cli(HOST, PORT);
  7747. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7748. ASSERT_TRUE(res);
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. }
  7751. {
  7752. Client cli(HOST, PORT);
  7753. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7754. ASSERT_TRUE(res);
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. }
  7757. {
  7758. Client cli(HOST, PORT);
  7759. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. }
  7764. TEST(GetWithParametersTest, GetWithParameters2) {
  7765. Server svr;
  7766. svr.Get("/", [&](const Request &req, Response &res) {
  7767. auto text = req.get_param_value("hello");
  7768. res.set_content(text, "text/plain");
  7769. });
  7770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7771. auto se = detail::scope_exit([&] {
  7772. svr.stop();
  7773. listen_thread.join();
  7774. ASSERT_FALSE(svr.is_running());
  7775. });
  7776. svr.wait_until_ready();
  7777. Client cli("localhost", PORT);
  7778. Params params;
  7779. params.emplace("hello", "world");
  7780. std::string body;
  7781. auto res = cli.Get("/", params, Headers{},
  7782. [&](const char *data, size_t data_length) {
  7783. body.append(data, data_length);
  7784. return true;
  7785. });
  7786. ASSERT_TRUE(res);
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. EXPECT_EQ("world", body);
  7789. }
  7790. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7791. Server svr;
  7792. svr.Get("/search", [&](const Request &req, Response &res) {
  7793. auto q = req.get_param_value("q");
  7794. res.set_content(q, "text/plain");
  7795. });
  7796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7797. auto se = detail::scope_exit([&] {
  7798. svr.stop();
  7799. listen_thread.join();
  7800. ASSERT_FALSE(svr.is_running());
  7801. });
  7802. svr.wait_until_ready();
  7803. Client cli("localhost", PORT);
  7804. // Verify that Get(path, params) works without requiring Headers argument
  7805. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_EQ("cpp-httplib", res->body);
  7809. }
  7810. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7811. auto host = "httpbingo.org";
  7812. auto path = std::string{"/range/32"};
  7813. #ifdef CPPHTTPLIB_SSL_ENABLED
  7814. SSLClient cli(host);
  7815. #else
  7816. Client cli(host);
  7817. #endif
  7818. cli.set_default_headers({make_range_header({{1, 10}})});
  7819. cli.set_connection_timeout(5);
  7820. {
  7821. auto res = cli.Get(path);
  7822. ASSERT_TRUE(res);
  7823. EXPECT_EQ("bcdefghijk", res->body);
  7824. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7825. }
  7826. {
  7827. auto res = cli.Get(path);
  7828. ASSERT_TRUE(res);
  7829. EXPECT_EQ("bcdefghijk", res->body);
  7830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7831. }
  7832. }
  7833. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7834. Server svr;
  7835. svr.set_default_headers({{"Hello", "World"}});
  7836. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7837. res.set_content("ok", "text/plain");
  7838. });
  7839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7840. auto se = detail::scope_exit([&] {
  7841. svr.stop();
  7842. listen_thread.join();
  7843. ASSERT_FALSE(svr.is_running());
  7844. });
  7845. svr.wait_until_ready();
  7846. Client cli("localhost", PORT);
  7847. auto res = cli.Get("/");
  7848. ASSERT_TRUE(res);
  7849. EXPECT_EQ(StatusCode::OK_200, res->status);
  7850. EXPECT_EQ("ok", res->body);
  7851. EXPECT_EQ("World", res->get_header_value("Hello"));
  7852. }
  7853. #ifdef CPPHTTPLIB_SSL_ENABLED
  7854. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7856. ASSERT_TRUE(svr.is_valid());
  7857. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7858. std::this_thread::sleep_for(std::chrono::seconds(2));
  7859. res.set_content("a", "text/plain");
  7860. });
  7861. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7862. res.set_content("b", "text/plain");
  7863. });
  7864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7865. auto se = detail::scope_exit([&] {
  7866. svr.stop();
  7867. listen_thread.join();
  7868. ASSERT_FALSE(svr.is_running());
  7869. });
  7870. svr.wait_until_ready();
  7871. SSLClient cli("localhost", PORT);
  7872. cli.enable_server_certificate_verification(false);
  7873. cli.set_keep_alive(true);
  7874. cli.set_read_timeout(std::chrono::seconds(1));
  7875. auto resa = cli.Get("/a");
  7876. ASSERT_TRUE(!resa);
  7877. EXPECT_EQ(Error::Read, resa.error());
  7878. auto resb = cli.Get("/b");
  7879. ASSERT_TRUE(resb);
  7880. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7881. EXPECT_EQ("b", resb->body);
  7882. }
  7883. #endif
  7884. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7885. protected:
  7886. ServerTestWithAI_PASSIVE()
  7887. : cli_(HOST, PORT)
  7888. #ifdef CPPHTTPLIB_SSL_ENABLED
  7889. ,
  7890. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7891. #endif
  7892. {
  7893. #ifdef CPPHTTPLIB_SSL_ENABLED
  7894. cli_.enable_server_certificate_verification(false);
  7895. #endif
  7896. }
  7897. virtual void SetUp() {
  7898. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7899. res.set_content("Hello World!", "text/plain");
  7900. });
  7901. t_ = thread(
  7902. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7903. svr_.wait_until_ready();
  7904. }
  7905. virtual void TearDown() {
  7906. svr_.stop();
  7907. t_.join();
  7908. }
  7909. #ifdef CPPHTTPLIB_SSL_ENABLED
  7910. SSLClient cli_;
  7911. SSLServer svr_;
  7912. #else
  7913. Client cli_;
  7914. Server svr_;
  7915. #endif
  7916. thread t_;
  7917. };
  7918. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7919. auto res = cli_.Get("/hi");
  7920. ASSERT_TRUE(res);
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7923. EXPECT_EQ("Hello World!", res->body);
  7924. }
  7925. class ServerUpDownTest : public ::testing::Test {
  7926. protected:
  7927. ServerUpDownTest() : cli_(HOST, PORT) {}
  7928. virtual void SetUp() {
  7929. t_ = thread([&]() {
  7930. svr_.bind_to_any_port(HOST);
  7931. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7932. ASSERT_TRUE(svr_.listen_after_bind());
  7933. });
  7934. svr_.wait_until_ready();
  7935. }
  7936. virtual void TearDown() {
  7937. svr_.stop();
  7938. t_.join();
  7939. }
  7940. Client cli_;
  7941. Server svr_;
  7942. thread t_;
  7943. };
  7944. TEST_F(ServerUpDownTest, QuickStartStop) {
  7945. // Should not crash, especially when run with
  7946. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7947. }
  7948. class PayloadMaxLengthTest : public ::testing::Test {
  7949. protected:
  7950. PayloadMaxLengthTest()
  7951. : cli_(HOST, PORT)
  7952. #ifdef CPPHTTPLIB_SSL_ENABLED
  7953. ,
  7954. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7955. #endif
  7956. {
  7957. #ifdef CPPHTTPLIB_SSL_ENABLED
  7958. cli_.enable_server_certificate_verification(false);
  7959. #endif
  7960. }
  7961. virtual void SetUp() {
  7962. svr_.set_payload_max_length(8);
  7963. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7964. res.set_content("test", "text/plain");
  7965. });
  7966. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7967. svr_.wait_until_ready();
  7968. }
  7969. virtual void TearDown() {
  7970. svr_.stop();
  7971. t_.join();
  7972. }
  7973. #ifdef CPPHTTPLIB_SSL_ENABLED
  7974. SSLClient cli_;
  7975. SSLServer svr_;
  7976. #else
  7977. Client cli_;
  7978. Server svr_;
  7979. #endif
  7980. thread t_;
  7981. };
  7982. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7983. auto res = cli_.Post("/test", "123456789", "text/plain");
  7984. ASSERT_TRUE(res);
  7985. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7986. res = cli_.Post("/test", "12345678", "text/plain");
  7987. ASSERT_TRUE(res);
  7988. EXPECT_EQ(StatusCode::OK_200, res->status);
  7989. }
  7990. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7991. // Test chunked encoding with payload exceeding the 8-byte limit
  7992. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7993. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7994. ASSERT_TRUE(res);
  7995. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7996. }
  7997. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7998. // Test chunked encoding with payload within the 8-byte limit
  7999. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8000. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8001. ASSERT_TRUE(res);
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. }
  8004. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8005. // Test using send_request to send chunked data exceeding payload limit
  8006. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8007. "Host: " +
  8008. std::string(HOST) + ":" + std::to_string(PORT) +
  8009. "\r\n"
  8010. "Transfer-Encoding: chunked\r\n"
  8011. "Connection: close\r\n"
  8012. "\r\n"
  8013. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8014. "0123456789\r\n"
  8015. "0\r\n" // End chunk
  8016. "\r\n";
  8017. std::string response;
  8018. bool result = send_request(1, chunked_request, &response);
  8019. if (!result) {
  8020. // If send_request fails, it might be because the server closed the
  8021. // connection due to payload limit enforcement, which is acceptable
  8022. SUCCEED()
  8023. << "Server rejected oversized chunked request (connection closed)";
  8024. } else {
  8025. // If we got a response, check if it's an error response or connection was
  8026. // closed early Short response length indicates connection was closed due to
  8027. // payload limit
  8028. if (response.length() <= 10) {
  8029. SUCCEED() << "Server closed connection for oversized chunked request";
  8030. } else {
  8031. // Check for error status codes
  8032. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8033. response.find("Payload Too Large") != std::string::npos ||
  8034. response.find("400") != std::string::npos);
  8035. }
  8036. }
  8037. }
  8038. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8039. // Test request without Content-Length header exceeding payload limit
  8040. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8041. "Host: " +
  8042. std::string(HOST) + ":" +
  8043. std::to_string(PORT) +
  8044. "\r\n"
  8045. "Connection: close\r\n"
  8046. "\r\n";
  8047. // Add payload exceeding the 8-byte limit
  8048. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8049. request_without_content_length += large_payload;
  8050. std::string response;
  8051. bool result = send_request(1, request_without_content_length, &response);
  8052. if (!result) {
  8053. // If send_request fails, server likely closed connection due to payload
  8054. // limit
  8055. SUCCEED() << "Server rejected oversized request without Content-Length "
  8056. "(connection closed)";
  8057. } else {
  8058. // Check if server responded with error or closed connection early
  8059. if (response.length() <= 10) {
  8060. SUCCEED() << "Server closed connection for oversized request without "
  8061. "Content-Length";
  8062. } else {
  8063. // Check for error status codes
  8064. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8065. response.find("Payload Too Large") != std::string::npos ||
  8066. response.find("400") != std::string::npos);
  8067. }
  8068. }
  8069. }
  8070. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8071. // Test request without Content-Length header within payload limit
  8072. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8073. "Host: " +
  8074. std::string(HOST) + ":" +
  8075. std::to_string(PORT) +
  8076. "\r\n"
  8077. "Connection: close\r\n"
  8078. "\r\n";
  8079. // Add payload within the 8-byte limit
  8080. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8081. request_without_content_length += small_payload;
  8082. std::string response;
  8083. bool result = send_request(1, request_without_content_length, &response);
  8084. // For requests without Content-Length, the server may have different behavior
  8085. // The key is that it should not reject due to payload limit for small
  8086. // payloads
  8087. if (result) {
  8088. // Check for any HTTP response (success or error, but not connection closed)
  8089. if (response.length() > 10) {
  8090. SUCCEED()
  8091. << "Server processed request without Content-Length within limit";
  8092. } else {
  8093. // Short response might indicate connection closed, which is acceptable
  8094. SUCCEED() << "Server closed connection for request without "
  8095. "Content-Length (acceptable behavior)";
  8096. }
  8097. } else {
  8098. // Connection failure might be due to protocol requirements
  8099. SUCCEED() << "Connection issue with request without Content-Length "
  8100. "(environment-specific)";
  8101. }
  8102. }
  8103. class LargePayloadMaxLengthTest : public ::testing::Test {
  8104. protected:
  8105. LargePayloadMaxLengthTest()
  8106. : cli_(HOST, PORT)
  8107. #ifdef CPPHTTPLIB_SSL_ENABLED
  8108. ,
  8109. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8110. #endif
  8111. {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. cli_.enable_server_certificate_verification(false);
  8114. #endif
  8115. }
  8116. virtual void SetUp() {
  8117. // Set 10MB payload limit
  8118. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8119. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8120. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8121. res.set_content("Large payload test", "text/plain");
  8122. });
  8123. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8124. svr_.wait_until_ready();
  8125. }
  8126. virtual void TearDown() {
  8127. svr_.stop();
  8128. t_.join();
  8129. }
  8130. #ifdef CPPHTTPLIB_SSL_ENABLED
  8131. SSLClient cli_;
  8132. SSLServer svr_;
  8133. #else
  8134. Client cli_;
  8135. Server svr_;
  8136. #endif
  8137. thread t_;
  8138. };
  8139. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8140. // Test chunked encoding with payload within 10MB limit
  8141. std::string medium_payload(5 * 1024 * 1024,
  8142. 'A'); // 5MB payload, within 10MB limit
  8143. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8144. ASSERT_TRUE(res);
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8148. // Test chunked encoding with payload exceeding 10MB limit
  8149. std::string large_payload(12 * 1024 * 1024,
  8150. 'B'); // 12MB payload, exceeds 10MB limit
  8151. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8152. // Server may either return 413 or close the connection
  8153. if (res) {
  8154. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8155. } else {
  8156. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8157. }
  8158. }
  8159. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8160. // Test request without Content-Length header within 10MB limit
  8161. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8162. "Host: " +
  8163. std::string(HOST) + ":" +
  8164. std::to_string(PORT) +
  8165. "\r\n"
  8166. "Connection: close\r\n"
  8167. "\r\n";
  8168. // Add 1MB payload (within 10MB limit)
  8169. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8170. request_without_content_length += medium_payload;
  8171. std::string response;
  8172. bool result = send_request(5, request_without_content_length, &response);
  8173. if (result) {
  8174. // Should get a proper HTTP response for payloads within limit
  8175. if (response.length() > 10) {
  8176. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8177. "10MB limit";
  8178. } else {
  8179. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8180. "Content-Length)";
  8181. }
  8182. } else {
  8183. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8184. }
  8185. }
  8186. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8187. // Test request without Content-Length header exceeding 10MB limit
  8188. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8189. "Host: " +
  8190. std::string(HOST) + ":" +
  8191. std::to_string(PORT) +
  8192. "\r\n"
  8193. "Connection: close\r\n"
  8194. "\r\n";
  8195. // Add 12MB payload (exceeds 10MB limit)
  8196. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8197. request_without_content_length += large_payload;
  8198. std::string response;
  8199. bool result = send_request(10, request_without_content_length, &response);
  8200. if (!result) {
  8201. // Server should close connection due to payload limit
  8202. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8203. "(connection closed)";
  8204. } else {
  8205. // Check for error response
  8206. if (response.length() <= 10) {
  8207. SUCCEED()
  8208. << "Server closed connection for 12MB request exceeding 10MB limit";
  8209. } else {
  8210. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8211. response.find("Payload Too Large") != std::string::npos ||
  8212. response.find("400") != std::string::npos);
  8213. }
  8214. }
  8215. }
  8216. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8217. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8218. // path.
  8219. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8220. Server svr;
  8221. const size_t LIMIT = 64 * 1024; // 64KB
  8222. svr.set_payload_max_length(LIMIT);
  8223. size_t total = 0;
  8224. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8225. const ContentReader &content_reader) {
  8226. content_reader([&](const char * /*data*/, size_t len) {
  8227. total += len;
  8228. return true;
  8229. });
  8230. res.status = 200;
  8231. res.set_content("stream_ok", "text/plain");
  8232. });
  8233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8234. auto se = detail::scope_exit([&] {
  8235. svr.stop();
  8236. thread.join();
  8237. ASSERT_FALSE(svr.is_running());
  8238. });
  8239. svr.wait_until_ready();
  8240. // Prepare 256KB raw data and gzip-compress it
  8241. std::string raw(256 * 1024, 'A');
  8242. std::string gz;
  8243. {
  8244. z_stream zs{};
  8245. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8246. Z_DEFAULT_STRATEGY);
  8247. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8248. zs.avail_in = static_cast<uInt>(raw.size());
  8249. char outbuf[4096];
  8250. int ret;
  8251. do {
  8252. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8253. zs.avail_out = sizeof(outbuf);
  8254. ret = deflate(&zs, Z_FINISH);
  8255. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8256. } while (ret != Z_STREAM_END);
  8257. deflateEnd(&zs);
  8258. }
  8259. Client cli(HOST, PORT);
  8260. cli.set_connection_timeout(std::chrono::seconds(5));
  8261. Headers headers = {{"Content-Encoding", "gzip"}};
  8262. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8263. "application/octet-stream");
  8264. ASSERT_TRUE(res);
  8265. // Server must reject oversized decompressed payloads with 413.
  8266. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8267. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8268. EXPECT_LE(total, LIMIT);
  8269. }
  8270. #endif
  8271. // Regression test for DoS vulnerability: a malicious server sending a response
  8272. // without Content-Length header must not cause unbounded memory consumption on
  8273. // the client side. The client should stop reading after a reasonable limit,
  8274. // similar to the server-side set_payload_max_length protection.
  8275. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8276. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8277. #ifndef _WIN32
  8278. signal(SIGPIPE, SIG_IGN);
  8279. #endif
  8280. auto server_thread = std::thread([] {
  8281. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8282. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8283. default_socket_options(srv);
  8284. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8285. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8286. sockaddr_in addr{};
  8287. addr.sin_family = AF_INET;
  8288. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8289. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8290. int opt = 1;
  8291. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8292. #ifdef _WIN32
  8293. reinterpret_cast<const char *>(&opt),
  8294. #else
  8295. &opt,
  8296. #endif
  8297. sizeof(opt));
  8298. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8299. ::listen(srv, 1);
  8300. sockaddr_in cli_addr{};
  8301. socklen_t cli_len = sizeof(cli_addr);
  8302. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8303. if (cli != INVALID_SOCKET) {
  8304. char buf[4096];
  8305. ::recv(cli, buf, sizeof(buf), 0);
  8306. // Malicious response: no Content-Length, no chunked encoding
  8307. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8308. "Connection: close\r\n"
  8309. "\r\n";
  8310. ::send(cli,
  8311. #ifdef _WIN32
  8312. static_cast<const char *>(response_header.c_str()),
  8313. static_cast<int>(response_header.size()),
  8314. #else
  8315. response_header.c_str(), response_header.size(),
  8316. #endif
  8317. 0);
  8318. // Send 10MB of data
  8319. std::string chunk(64 * 1024, 'A');
  8320. size_t total_sent = 0;
  8321. while (total_sent < MALICIOUS_DATA_SIZE) {
  8322. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8323. auto sent = ::send(cli,
  8324. #ifdef _WIN32
  8325. static_cast<const char *>(chunk.c_str()),
  8326. static_cast<int>(to_send),
  8327. #else
  8328. chunk.c_str(), to_send,
  8329. #endif
  8330. 0);
  8331. if (sent <= 0) break;
  8332. total_sent += static_cast<size_t>(sent);
  8333. }
  8334. detail::close_socket(cli);
  8335. }
  8336. detail::close_socket(srv);
  8337. });
  8338. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8339. size_t total_read = 0;
  8340. {
  8341. Client cli("127.0.0.1", PORT + 2);
  8342. cli.set_read_timeout(5, 0);
  8343. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8344. auto stream = cli.open_stream("GET", "/malicious");
  8345. ASSERT_TRUE(stream.is_valid());
  8346. char buffer[64 * 1024];
  8347. ssize_t n;
  8348. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8349. total_read += static_cast<size_t>(n);
  8350. }
  8351. } // StreamHandle and Client destroyed here, closing the socket
  8352. server_thread.join();
  8353. // With set_payload_max_length, the client must stop reading before consuming
  8354. // all 10MB. The read loop should be cut off at or near the configured limit.
  8355. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8356. << "Client read " << total_read << " bytes, exceeding the configured "
  8357. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8358. }
  8359. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8360. // the entire response body without truncation.
  8361. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8362. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8363. #ifndef _WIN32
  8364. signal(SIGPIPE, SIG_IGN);
  8365. #endif
  8366. auto server_thread = std::thread([] {
  8367. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8368. default_socket_options(srv);
  8369. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8370. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8371. sockaddr_in addr{};
  8372. addr.sin_family = AF_INET;
  8373. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8374. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8375. int opt = 1;
  8376. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8377. #ifdef _WIN32
  8378. reinterpret_cast<const char *>(&opt),
  8379. #else
  8380. &opt,
  8381. #endif
  8382. sizeof(opt));
  8383. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8384. ::listen(srv, 1);
  8385. sockaddr_in cli_addr{};
  8386. socklen_t cli_len = sizeof(cli_addr);
  8387. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8388. if (cli != INVALID_SOCKET) {
  8389. char buf[4096];
  8390. ::recv(cli, buf, sizeof(buf), 0);
  8391. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8392. "Connection: close\r\n"
  8393. "\r\n";
  8394. ::send(cli,
  8395. #ifdef _WIN32
  8396. static_cast<const char *>(response_header.c_str()),
  8397. static_cast<int>(response_header.size()),
  8398. #else
  8399. response_header.c_str(), response_header.size(),
  8400. #endif
  8401. 0);
  8402. std::string chunk(64 * 1024, 'A');
  8403. size_t total_sent = 0;
  8404. while (total_sent < DATA_SIZE) {
  8405. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8406. auto sent = ::send(cli,
  8407. #ifdef _WIN32
  8408. static_cast<const char *>(chunk.c_str()),
  8409. static_cast<int>(to_send),
  8410. #else
  8411. chunk.c_str(), to_send,
  8412. #endif
  8413. 0);
  8414. if (sent <= 0) break;
  8415. total_sent += static_cast<size_t>(sent);
  8416. }
  8417. #ifdef _WIN32
  8418. ::shutdown(cli, SD_SEND);
  8419. #else
  8420. ::shutdown(cli, SHUT_WR);
  8421. #endif
  8422. // Drain until the client closes its end, ensuring all data is delivered
  8423. char drain[1024];
  8424. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8425. detail::close_socket(cli);
  8426. }
  8427. detail::close_socket(srv);
  8428. });
  8429. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8430. size_t total_read = 0;
  8431. {
  8432. Client cli("127.0.0.1", PORT + 2);
  8433. cli.set_read_timeout(5, 0);
  8434. cli.set_payload_max_length(0); // 0 means no limit
  8435. auto stream = cli.open_stream("GET", "/data");
  8436. ASSERT_TRUE(stream.is_valid());
  8437. char buffer[64 * 1024];
  8438. ssize_t n;
  8439. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8440. total_read += static_cast<size_t>(n);
  8441. }
  8442. }
  8443. server_thread.join();
  8444. EXPECT_EQ(total_read, DATA_SIZE)
  8445. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8446. << " bytes without truncation, but only read " << total_read << " bytes.";
  8447. }
  8448. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8449. // enormous Content-Length must not cause the client to pre-allocate a huge
  8450. // response body buffer. The reservation is capped at payload_max_length_, and
  8451. // the read itself fails when the body exceeds the limit.
  8452. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8453. #ifndef _WIN32
  8454. signal(SIGPIPE, SIG_IGN);
  8455. #endif
  8456. auto server_thread = std::thread([] {
  8457. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8458. default_socket_options(srv);
  8459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8460. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8461. sockaddr_in addr{};
  8462. addr.sin_family = AF_INET;
  8463. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8464. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8465. int opt = 1;
  8466. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8467. #ifdef _WIN32
  8468. reinterpret_cast<const char *>(&opt),
  8469. #else
  8470. &opt,
  8471. #endif
  8472. sizeof(opt));
  8473. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8474. ::listen(srv, 1);
  8475. sockaddr_in cli_addr{};
  8476. socklen_t cli_len = sizeof(cli_addr);
  8477. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8478. if (cli != INVALID_SOCKET) {
  8479. char buf[4096];
  8480. ::recv(cli, buf, sizeof(buf), 0);
  8481. // Malicious response: claim a 20GB body but send only a tiny payload.
  8482. std::string response = "HTTP/1.1 200 OK\r\n"
  8483. "Content-Length: 20000000000\r\n"
  8484. "\r\n"
  8485. "abc";
  8486. ::send(cli,
  8487. #ifdef _WIN32
  8488. static_cast<const char *>(response.c_str()),
  8489. static_cast<int>(response.size()),
  8490. #else
  8491. response.c_str(), response.size(),
  8492. #endif
  8493. 0);
  8494. detail::close_socket(cli);
  8495. }
  8496. detail::close_socket(srv);
  8497. });
  8498. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8499. {
  8500. Client cli("127.0.0.1", PORT + 2);
  8501. cli.set_read_timeout(5, 0);
  8502. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8503. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8504. // (server claims more bytes than payload_max_length permits), but it must
  8505. // not exhaust memory before getting there.
  8506. auto res = cli.Get("/malicious");
  8507. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8508. }
  8509. server_thread.join();
  8510. }
  8511. // Verify that content_receiver bypasses the default payload_max_length,
  8512. // allowing streaming downloads larger than 100MB without requiring an explicit
  8513. // set_payload_max_length call.
  8514. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8515. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8516. #ifndef _WIN32
  8517. signal(SIGPIPE, SIG_IGN);
  8518. #endif
  8519. auto server_thread = std::thread([] {
  8520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8521. default_socket_options(srv);
  8522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8524. sockaddr_in addr{};
  8525. addr.sin_family = AF_INET;
  8526. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8528. int opt = 1;
  8529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8530. #ifdef _WIN32
  8531. reinterpret_cast<const char *>(&opt),
  8532. #else
  8533. &opt,
  8534. #endif
  8535. sizeof(opt));
  8536. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8537. ::listen(srv, 1);
  8538. sockaddr_in cli_addr{};
  8539. socklen_t cli_len = sizeof(cli_addr);
  8540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8541. if (cli != INVALID_SOCKET) {
  8542. char buf[4096];
  8543. ::recv(cli, buf, sizeof(buf), 0);
  8544. // Response with Content-Length larger than default 100MB limit
  8545. auto content_length = std::to_string(DATA_SIZE);
  8546. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8547. "Content-Length: " +
  8548. content_length +
  8549. "\r\n"
  8550. "Connection: close\r\n"
  8551. "\r\n";
  8552. ::send(cli,
  8553. #ifdef _WIN32
  8554. static_cast<const char *>(response_header.c_str()),
  8555. static_cast<int>(response_header.size()),
  8556. #else
  8557. response_header.c_str(), response_header.size(),
  8558. #endif
  8559. 0);
  8560. std::string chunk(64 * 1024, 'A');
  8561. size_t total_sent = 0;
  8562. while (total_sent < DATA_SIZE) {
  8563. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8564. auto sent = ::send(cli,
  8565. #ifdef _WIN32
  8566. static_cast<const char *>(chunk.c_str()),
  8567. static_cast<int>(to_send),
  8568. #else
  8569. chunk.c_str(), to_send,
  8570. #endif
  8571. 0);
  8572. if (sent <= 0) break;
  8573. total_sent += static_cast<size_t>(sent);
  8574. }
  8575. detail::close_socket(cli);
  8576. }
  8577. detail::close_socket(srv);
  8578. });
  8579. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8580. size_t total_received = 0;
  8581. {
  8582. Client cli("127.0.0.1", PORT + 2);
  8583. cli.set_read_timeout(10, 0);
  8584. // Do NOT call set_payload_max_length — use the default 100MB limit
  8585. auto res =
  8586. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8587. total_received += data_length;
  8588. return true;
  8589. });
  8590. ASSERT_TRUE(res);
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. server_thread.join();
  8594. EXPECT_EQ(total_received, DATA_SIZE)
  8595. << "With content_receiver, the client should read all " << DATA_SIZE
  8596. << " bytes despite the default 100MB payload_max_length, but only read "
  8597. << total_received << " bytes.";
  8598. }
  8599. // Verify that an explicit set_payload_max_length smaller than the response is
  8600. // enforced even when a content_receiver is used.
  8601. TEST(ClientVulnerabilityTest,
  8602. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8603. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8604. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8605. #ifndef _WIN32
  8606. signal(SIGPIPE, SIG_IGN);
  8607. #endif
  8608. auto server_thread = std::thread([] {
  8609. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8610. default_socket_options(srv);
  8611. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8612. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8613. sockaddr_in addr{};
  8614. addr.sin_family = AF_INET;
  8615. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8616. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8617. int opt = 1;
  8618. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8619. #ifdef _WIN32
  8620. reinterpret_cast<const char *>(&opt),
  8621. #else
  8622. &opt,
  8623. #endif
  8624. sizeof(opt));
  8625. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8626. ::listen(srv, 1);
  8627. sockaddr_in cli_addr{};
  8628. socklen_t cli_len = sizeof(cli_addr);
  8629. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8630. if (cli != INVALID_SOCKET) {
  8631. char buf[4096];
  8632. ::recv(cli, buf, sizeof(buf), 0);
  8633. auto content_length = std::to_string(DATA_SIZE);
  8634. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8635. "Content-Length: " +
  8636. content_length +
  8637. "\r\n"
  8638. "Connection: close\r\n"
  8639. "\r\n";
  8640. ::send(cli,
  8641. #ifdef _WIN32
  8642. static_cast<const char *>(response_header.c_str()),
  8643. static_cast<int>(response_header.size()),
  8644. #else
  8645. response_header.c_str(), response_header.size(),
  8646. #endif
  8647. 0);
  8648. std::string chunk(64 * 1024, 'A');
  8649. size_t total_sent = 0;
  8650. while (total_sent < DATA_SIZE) {
  8651. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8652. auto sent = ::send(cli,
  8653. #ifdef _WIN32
  8654. static_cast<const char *>(chunk.c_str()),
  8655. static_cast<int>(to_send),
  8656. #else
  8657. chunk.c_str(), to_send,
  8658. #endif
  8659. 0);
  8660. if (sent <= 0) break;
  8661. total_sent += static_cast<size_t>(sent);
  8662. }
  8663. detail::close_socket(cli);
  8664. }
  8665. detail::close_socket(srv);
  8666. });
  8667. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8668. size_t total_received = 0;
  8669. {
  8670. Client cli("127.0.0.1", PORT + 2);
  8671. cli.set_read_timeout(10, 0);
  8672. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8673. auto res =
  8674. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8675. total_received += data_length;
  8676. return true;
  8677. });
  8678. // Should fail because 200MB exceeds the explicit 150MB limit
  8679. EXPECT_FALSE(res);
  8680. }
  8681. server_thread.join();
  8682. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8683. << "Client with content_receiver should respect the explicit "
  8684. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8685. << total_received << " bytes.";
  8686. }
  8687. // Verify that an explicit set_payload_max_length larger than the response
  8688. // allows the content_receiver to read all data successfully.
  8689. TEST(ClientVulnerabilityTest,
  8690. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8691. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8692. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8693. #ifndef _WIN32
  8694. signal(SIGPIPE, SIG_IGN);
  8695. #endif
  8696. auto server_thread = std::thread([] {
  8697. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8698. default_socket_options(srv);
  8699. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8700. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8701. sockaddr_in addr{};
  8702. addr.sin_family = AF_INET;
  8703. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8704. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8705. int opt = 1;
  8706. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8707. #ifdef _WIN32
  8708. reinterpret_cast<const char *>(&opt),
  8709. #else
  8710. &opt,
  8711. #endif
  8712. sizeof(opt));
  8713. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8714. ::listen(srv, 1);
  8715. sockaddr_in cli_addr{};
  8716. socklen_t cli_len = sizeof(cli_addr);
  8717. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8718. if (cli != INVALID_SOCKET) {
  8719. char buf[4096];
  8720. ::recv(cli, buf, sizeof(buf), 0);
  8721. auto content_length = std::to_string(DATA_SIZE);
  8722. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8723. "Content-Length: " +
  8724. content_length +
  8725. "\r\n"
  8726. "Connection: close\r\n"
  8727. "\r\n";
  8728. ::send(cli,
  8729. #ifdef _WIN32
  8730. static_cast<const char *>(response_header.c_str()),
  8731. static_cast<int>(response_header.size()),
  8732. #else
  8733. response_header.c_str(), response_header.size(),
  8734. #endif
  8735. 0);
  8736. std::string chunk(64 * 1024, 'A');
  8737. size_t total_sent = 0;
  8738. while (total_sent < DATA_SIZE) {
  8739. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8740. auto sent = ::send(cli,
  8741. #ifdef _WIN32
  8742. static_cast<const char *>(chunk.c_str()),
  8743. static_cast<int>(to_send),
  8744. #else
  8745. chunk.c_str(), to_send,
  8746. #endif
  8747. 0);
  8748. if (sent <= 0) break;
  8749. total_sent += static_cast<size_t>(sent);
  8750. }
  8751. #ifdef _WIN32
  8752. ::shutdown(cli, SD_SEND);
  8753. #else
  8754. ::shutdown(cli, SHUT_WR);
  8755. #endif
  8756. char drain[1024];
  8757. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8758. detail::close_socket(cli);
  8759. }
  8760. detail::close_socket(srv);
  8761. });
  8762. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8763. size_t total_received = 0;
  8764. {
  8765. Client cli("127.0.0.1", PORT + 2);
  8766. cli.set_read_timeout(10, 0);
  8767. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8768. auto res =
  8769. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8770. total_received += data_length;
  8771. return true;
  8772. });
  8773. ASSERT_TRUE(res);
  8774. EXPECT_EQ(StatusCode::OK_200, res->status);
  8775. }
  8776. server_thread.join();
  8777. EXPECT_EQ(total_received, DATA_SIZE)
  8778. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8779. << " bytes (larger than " << DATA_SIZE
  8780. << " bytes response), content_receiver should read all data, but only "
  8781. "read "
  8782. << total_received << " bytes.";
  8783. }
  8784. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8785. // Regression test for "zip bomb" attack on the client side: a malicious server
  8786. // sends a small gzip-compressed response that decompresses to a huge payload.
  8787. // The client must enforce payload_max_length on the decompressed size.
  8788. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8789. constexpr size_t DECOMPRESSED_SIZE =
  8790. 10 * 1024 * 1024; // 10MB after decompression
  8791. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8792. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8793. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8794. std::string compressed;
  8795. {
  8796. httplib::detail::gzip_compressor compressor;
  8797. bool ok =
  8798. compressor.compress(uncompressed.data(), uncompressed.size(),
  8799. /*last=*/true, [&](const char *buf, size_t len) {
  8800. compressed.append(buf, len);
  8801. return true;
  8802. });
  8803. ASSERT_TRUE(ok);
  8804. }
  8805. // Sanity: compressed data should be much smaller than the decompressed size
  8806. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8807. #ifndef _WIN32
  8808. signal(SIGPIPE, SIG_IGN);
  8809. #endif
  8810. // Set up the listening socket in the main thread so the server is guaranteed
  8811. // to be ready before the client connects (eliminates race condition).
  8812. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8813. default_socket_options(srv);
  8814. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8815. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8816. sockaddr_in addr{};
  8817. addr.sin_family = AF_INET;
  8818. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8819. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8820. int opt = 1;
  8821. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8822. #ifdef _WIN32
  8823. reinterpret_cast<const char *>(&opt),
  8824. #else
  8825. &opt,
  8826. #endif
  8827. sizeof(opt));
  8828. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8829. ASSERT_EQ(0, ::listen(srv, 1));
  8830. auto server_thread = std::thread([&compressed, srv] {
  8831. sockaddr_in cli_addr{};
  8832. socklen_t cli_len = sizeof(cli_addr);
  8833. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8834. if (cli != INVALID_SOCKET) {
  8835. // Read the full HTTP request (until \r\n\r\n)
  8836. char buf[4096];
  8837. size_t total = 0;
  8838. while (total < sizeof(buf)) {
  8839. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8840. if (n <= 0) break;
  8841. total += static_cast<size_t>(n);
  8842. // Check for end of headers
  8843. if (total >= 4) {
  8844. std::string req(buf, total);
  8845. if (req.find("\r\n\r\n") != std::string::npos) break;
  8846. }
  8847. }
  8848. // Malicious response: gzip-compressed body, no Content-Length
  8849. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8850. "Content-Encoding: gzip\r\n"
  8851. "Connection: close\r\n"
  8852. "\r\n";
  8853. ::send(cli,
  8854. #ifdef _WIN32
  8855. static_cast<const char *>(response_header.c_str()),
  8856. static_cast<int>(response_header.size()),
  8857. #else
  8858. response_header.c_str(), response_header.size(),
  8859. #endif
  8860. 0);
  8861. // Send the compressed payload (small on the wire, huge when decompressed)
  8862. size_t total_sent = 0;
  8863. while (total_sent < compressed.size()) {
  8864. auto to_send = std::min(compressed.size() - total_sent,
  8865. static_cast<size_t>(64 * 1024));
  8866. auto sent =
  8867. ::send(cli,
  8868. #ifdef _WIN32
  8869. static_cast<const char *>(compressed.c_str() + total_sent),
  8870. static_cast<int>(to_send),
  8871. #else
  8872. compressed.c_str() + total_sent, to_send,
  8873. #endif
  8874. 0);
  8875. if (sent <= 0) break;
  8876. total_sent += static_cast<size_t>(sent);
  8877. }
  8878. detail::close_socket(cli);
  8879. }
  8880. });
  8881. auto se = detail::scope_exit([&] {
  8882. detail::close_socket(srv);
  8883. server_thread.join();
  8884. });
  8885. size_t total_decompressed = 0;
  8886. {
  8887. Client cli("127.0.0.1", PORT + 3);
  8888. cli.set_read_timeout(5, 0);
  8889. cli.set_decompress(true);
  8890. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8891. auto stream = cli.open_stream("GET", "/zipbomb");
  8892. ASSERT_TRUE(stream.is_valid());
  8893. char buffer[64 * 1024];
  8894. ssize_t n;
  8895. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8896. total_decompressed += static_cast<size_t>(n);
  8897. }
  8898. }
  8899. // The decompressed size must be capped by payload_max_length. Without
  8900. // protection, the client would decompress the full 10MB from a tiny
  8901. // compressed payload, enabling a zip bomb DoS attack.
  8902. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8903. << "Client decompressed " << total_decompressed
  8904. << " bytes from a gzip response. The decompressed size should be "
  8905. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8906. }
  8907. #endif
  8908. TEST(HostAndPortPropertiesTest, NoSSL) {
  8909. httplib::Client cli("www.google.com", 1234);
  8910. ASSERT_EQ("www.google.com", cli.host());
  8911. ASSERT_EQ(1234, cli.port());
  8912. }
  8913. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8914. httplib::Client cli("www.google.com:1234");
  8915. ASSERT_EQ("www.google.com", cli.host());
  8916. ASSERT_EQ(1234, cli.port());
  8917. }
  8918. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8919. // Port number that overflows int — should not crash, client becomes invalid
  8920. httplib::Client cli("http://www.google.com:99999999999999999999");
  8921. ASSERT_FALSE(cli.is_valid());
  8922. }
  8923. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8924. // Port 99999 exceeds valid range (1-65535) — should not crash
  8925. httplib::Client cli("http://www.google.com:99999");
  8926. ASSERT_FALSE(cli.is_valid());
  8927. }
  8928. #ifdef CPPHTTPLIB_SSL_ENABLED
  8929. TEST(HostAndPortPropertiesTest, SSL) {
  8930. httplib::SSLClient cli("www.google.com");
  8931. ASSERT_EQ("www.google.com", cli.host());
  8932. ASSERT_EQ(443, cli.port());
  8933. }
  8934. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8935. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8936. std::string cert;
  8937. read_file(CA_CERT_FILE, cert);
  8938. httplib::SSLClient httplib_client("www.google.com");
  8939. // Load CA store first time
  8940. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8941. // Load CA store second time (update)
  8942. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8943. // Verify client is still valid and can make connections
  8944. httplib_client.enable_server_certificate_verification(true);
  8945. auto res = httplib_client.Get("/");
  8946. ASSERT_TRUE(res);
  8947. // Google may return 200 or 301 depending on various factors
  8948. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8949. res->status == StatusCode::MovedPermanently_301);
  8950. }
  8951. TEST(SSLClientTest, ServerNameIndication_Online) {
  8952. auto host = "httpbingo.org";
  8953. auto path = std::string{"/get"};
  8954. SSLClient cli(host, 443);
  8955. auto res = cli.Get(path);
  8956. ASSERT_TRUE(res);
  8957. ASSERT_EQ(StatusCode::OK_200, res->status);
  8958. }
  8959. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8960. // Use a site that will cause SSL verification failure due to self-signed cert
  8961. SSLClient cli("self-signed.badssl.com", 443);
  8962. cli.enable_server_certificate_verification(true);
  8963. auto res = cli.Get("/");
  8964. ASSERT_TRUE(!res);
  8965. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8966. // Verify backend error is captured for SSLServerVerification
  8967. // This occurs when certificate verification fails
  8968. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8969. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8970. EXPECT_NE(0UL, res.ssl_backend_error());
  8971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8972. // For OpenSSL, ssl_error is 0 for verification errors
  8973. EXPECT_EQ(0, res.ssl_error());
  8974. #if !defined(_WIN32) || \
  8975. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8976. // On non-Windows or when Windows Schannel is disabled, the error comes
  8977. // from OpenSSL's verification
  8978. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8979. res.ssl_backend_error());
  8980. #endif
  8981. #endif
  8982. }
  8983. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8984. // Use a site where hostname doesn't match the certificate
  8985. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8986. SSLClient cli("wrong.host.badssl.com", 443);
  8987. cli.enable_server_certificate_verification(true);
  8988. cli.enable_server_hostname_verification(true);
  8989. auto res = cli.Get("/");
  8990. ASSERT_TRUE(!res);
  8991. // The error type depends on when hostname verification occurs:
  8992. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8993. // - Mbed TLS: SSLServerVerification (during handshake)
  8994. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8995. res.error() == Error::SSLServerVerification);
  8996. // Verify backend error is captured for hostname verification failure
  8997. EXPECT_NE(0UL, res.ssl_backend_error());
  8998. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8999. // For OpenSSL, ssl_error is 0 for verification errors
  9000. EXPECT_EQ(0, res.ssl_error());
  9001. #if !defined(_WIN32) || \
  9002. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9003. // On non-Windows or when Windows Schannel is disabled, the error comes
  9004. // from OpenSSL's hostname verification
  9005. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9006. res.ssl_backend_error());
  9007. #endif
  9008. #endif
  9009. }
  9010. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9011. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9012. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9013. SSLClient cli("www.google.com", 443);
  9014. cli.enable_server_certificate_verification(true);
  9015. auto res = cli.Get("/");
  9016. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9017. }
  9018. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9019. SSLClient cli("www.google.com", 443);
  9020. cli.enable_server_certificate_verification(true);
  9021. cli.enable_windows_certificate_verification(false);
  9022. auto res = cli.Get("/");
  9023. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9024. }
  9025. #endif
  9026. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9027. Client cli("https://google.com");
  9028. auto res = cli.Get("/");
  9029. ASSERT_TRUE(res);
  9030. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9031. }
  9032. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9033. SSLClient cli("google.com");
  9034. cli.set_ca_cert_path(CA_CERT_FILE);
  9035. auto res = cli.Get("/");
  9036. ASSERT_TRUE(res);
  9037. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9038. }
  9039. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9040. SSLClient cli("google.com");
  9041. cli.enable_server_certificate_verification(true);
  9042. cli.set_ca_cert_path("hello");
  9043. auto res = cli.Get("/");
  9044. ASSERT_TRUE(!res);
  9045. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9046. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9047. // should be set
  9048. EXPECT_EQ(0, res.ssl_error());
  9049. // Verify backend error is captured for SSLLoadingCerts
  9050. // This error occurs when loading CA certificates fails
  9051. EXPECT_NE(0UL, res.ssl_backend_error());
  9052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9053. // OpenSSL specific error codes:
  9054. // > openssl errstr 0x80000002
  9055. // error:80000002:system library::No such file or directory
  9056. // > openssl errstr 0xA000126
  9057. // error:0A000126:SSL routines::unexpected eof while reading
  9058. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9059. res.ssl_backend_error() == 0xA000126);
  9060. #endif
  9061. }
  9062. TEST(SSLClientTest, ServerCertificateVerification4) {
  9063. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9064. ASSERT_TRUE(svr.is_valid());
  9065. svr.Get("/test", [&](const Request &, Response &res) {
  9066. res.set_content("test", "text/plain");
  9067. svr.stop();
  9068. ASSERT_TRUE(true);
  9069. });
  9070. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9071. auto se = detail::scope_exit([&] {
  9072. t.join();
  9073. ASSERT_FALSE(svr.is_running());
  9074. });
  9075. svr.wait_until_ready();
  9076. SSLClient cli("127.0.0.1", PORT);
  9077. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9078. cli.enable_server_certificate_verification(true);
  9079. cli.set_connection_timeout(30);
  9080. auto res = cli.Get("/test");
  9081. ASSERT_TRUE(res);
  9082. ASSERT_EQ(StatusCode::OK_200, res->status);
  9083. }
  9084. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9085. std::string cert;
  9086. read_file(CA_CERT_FILE, cert);
  9087. SSLClient cli("google.com");
  9088. cli.load_ca_cert_store(cert.data(), cert.size());
  9089. const auto res = cli.Get("/");
  9090. ASSERT_TRUE(res);
  9091. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9092. }
  9093. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9094. // clang-format off
  9095. static constexpr char cert[] =
  9096. "GlobalSign Root CA\n"
  9097. "==================\n"
  9098. "-----BEGIN CERTIFICATE-----\n"
  9099. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9100. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9101. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9102. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9103. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9104. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9105. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9106. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9107. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9108. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9109. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9110. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9111. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9112. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9113. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9114. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9115. "-----END CERTIFICATE-----\n";
  9116. // clang-format on
  9117. SSLClient cli("google.com");
  9118. cli.load_ca_cert_store(cert, sizeof(cert));
  9119. const auto res = cli.Get("/");
  9120. ASSERT_TRUE(res);
  9121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9122. }
  9123. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9124. SSLClient cli("www.youtube.com");
  9125. cli.set_ca_cert_path(CA_CERT_FILE);
  9126. cli.enable_server_certificate_verification(true);
  9127. cli.set_follow_location(true);
  9128. auto res = cli.Get("/");
  9129. ASSERT_TRUE(res);
  9130. ASSERT_EQ(StatusCode::OK_200, res->status);
  9131. }
  9132. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9133. SSLClient cli("wWw.YouTube.Com");
  9134. cli.set_ca_cert_path(CA_CERT_FILE);
  9135. cli.enable_server_certificate_verification(true);
  9136. cli.enable_server_hostname_verification(true);
  9137. cli.set_follow_location(true);
  9138. auto res = cli.Get("/");
  9139. ASSERT_TRUE(res);
  9140. ASSERT_EQ(StatusCode::OK_200, res->status);
  9141. }
  9142. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9143. SSLClient cli("gOoGlE.COm");
  9144. cli.enable_server_certificate_verification(true);
  9145. cli.enable_server_hostname_verification(true);
  9146. cli.set_follow_location(true);
  9147. auto res = cli.Get("/");
  9148. ASSERT_TRUE(res);
  9149. ASSERT_EQ(StatusCode::OK_200, res->status);
  9150. }
  9151. TEST(SSLClientTest, Issue2004_Online) {
  9152. Client client("https://google.com");
  9153. client.set_follow_location(true);
  9154. auto res = client.Get("/");
  9155. ASSERT_TRUE(res);
  9156. ASSERT_EQ(StatusCode::OK_200, res->status);
  9157. auto body = res->body;
  9158. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9159. }
  9160. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9161. // Create SSLClient with invalid cert/key to make is_valid() return false
  9162. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9163. "nonexistent_key.pem");
  9164. // is_valid() should be false due to cert loading failure
  9165. ASSERT_FALSE(cli.is_valid());
  9166. auto res = cli.Get("/");
  9167. ASSERT_FALSE(res);
  9168. EXPECT_EQ(Error::SSLConnection, res.error());
  9169. }
  9170. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9171. // Test for Issue #2251: SSL error not properly reported when client cert
  9172. // and key paths are swapped or mismatched
  9173. // This simulates the scenario where user accidentally swaps the cert and key
  9174. // files
  9175. // Using client cert file as private key and vice versa (completely wrong)
  9176. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9177. // Should fail validation due to cert/key mismatch
  9178. ASSERT_FALSE(cli.is_valid());
  9179. // Attempt to make a request should fail with proper error
  9180. auto res = cli.Get("/");
  9181. ASSERT_FALSE(res);
  9182. EXPECT_EQ(Error::SSLConnection, res.error());
  9183. // SSL error should be recorded in the Result object (this is the key fix for
  9184. // Issue #2251)
  9185. auto backend_error = res.ssl_backend_error();
  9186. EXPECT_NE(0u, backend_error);
  9187. }
  9188. // Tests cert/key mismatch detection at the TLS context level
  9189. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9190. // Test that using mismatched cert/key causes connection failure.
  9191. // We verify this at the SSLClient level rather than through internal
  9192. // TLS API functions.
  9193. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9194. cli.enable_server_certificate_verification(false);
  9195. cli.set_connection_timeout(2);
  9196. // The mismatch should cause a connection or handshake error
  9197. auto res = cli.Get("/test");
  9198. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9199. // Either way, the request should fail
  9200. EXPECT_FALSE(res);
  9201. }
  9202. #endif
  9203. #if 0
  9204. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9205. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9206. ASSERT_TRUE(cli != nullptr);
  9207. cli->set_address_family(AF_INET6);
  9208. cli->set_interface("en0");
  9209. auto res = cli->Get("/get");
  9210. ASSERT_TRUE(res);
  9211. ASSERT_EQ(StatusCode::OK_200, res->status);
  9212. }
  9213. #endif
  9214. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9215. #ifdef CPPHTTPLIB_SSL_ENABLED
  9216. void ClientCertPresent(
  9217. const std::string &client_cert_file,
  9218. const std::string &client_private_key_file,
  9219. const std::string &client_encrypted_private_key_pass = std::string()) {
  9220. using namespace httplib::tls;
  9221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9222. CLIENT_CA_CERT_DIR);
  9223. ASSERT_TRUE(svr.is_valid());
  9224. svr.Get("/test", [&](const Request &req, Response &res) {
  9225. res.set_content("test", "text/plain");
  9226. auto cert = req.peer_cert();
  9227. ASSERT_TRUE(static_cast<bool>(cert));
  9228. std::string common_name = cert.subject_cn();
  9229. EXPECT_EQ("Common Name", common_name);
  9230. });
  9231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. t.join();
  9235. ASSERT_FALSE(svr.is_running());
  9236. });
  9237. svr.wait_until_ready();
  9238. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9239. client_encrypted_private_key_pass);
  9240. cli.enable_server_certificate_verification(false);
  9241. cli.set_connection_timeout(30);
  9242. auto res = cli.Get("/test");
  9243. ASSERT_TRUE(res);
  9244. ASSERT_EQ(StatusCode::OK_200, res->status);
  9245. }
  9246. TEST(SSLClientServerTest, ClientCertPresent) {
  9247. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9248. }
  9249. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9250. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9251. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9252. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9253. }
  9254. // PEM memory-based constructor tests (works with all TLS backends)
  9255. void PemMemoryClientCertPresent(
  9256. const std::string &client_cert_file,
  9257. const std::string &client_private_key_file,
  9258. const std::string &client_encrypted_private_key_pass = std::string()) {
  9259. // Read PEM files into memory
  9260. std::string server_cert_pem, server_key_pem;
  9261. std::string client_ca_pem;
  9262. std::string client_cert_pem, client_key_pem;
  9263. read_file(SERVER_CERT_FILE, server_cert_pem);
  9264. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9265. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9266. read_file(client_cert_file, client_cert_pem);
  9267. read_file(client_private_key_file, client_key_pem);
  9268. // Create server with PEM memory
  9269. SSLServer::PemMemory server_pem = {
  9270. server_cert_pem.c_str(),
  9271. server_cert_pem.size(),
  9272. server_key_pem.c_str(),
  9273. server_key_pem.size(),
  9274. client_ca_pem.c_str(),
  9275. client_ca_pem.size(),
  9276. nullptr // no password for server key
  9277. };
  9278. SSLServer svr(server_pem);
  9279. ASSERT_TRUE(svr.is_valid());
  9280. svr.Get("/test", [&](const Request &, Response &res) {
  9281. res.set_content("test", "text/plain");
  9282. });
  9283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. ASSERT_FALSE(svr.is_running());
  9288. });
  9289. svr.wait_until_ready();
  9290. // Create client with PEM memory
  9291. const char *password = client_encrypted_private_key_pass.empty()
  9292. ? nullptr
  9293. : client_encrypted_private_key_pass.c_str();
  9294. SSLClient::PemMemory client_pem = {
  9295. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9296. client_key_pem.size(), password};
  9297. SSLClient cli(HOST, PORT, client_pem);
  9298. cli.enable_server_certificate_verification(false);
  9299. cli.set_connection_timeout(30);
  9300. auto res = cli.Get("/test");
  9301. ASSERT_TRUE(res);
  9302. ASSERT_EQ(StatusCode::OK_200, res->status);
  9303. }
  9304. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9305. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9306. }
  9307. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9308. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9309. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9310. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9311. }
  9312. TEST(SSLClientServerTest, ClientCertMissing) {
  9313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9314. CLIENT_CA_CERT_DIR);
  9315. ASSERT_TRUE(svr.is_valid());
  9316. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9317. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9318. auto se = detail::scope_exit([&] {
  9319. svr.stop();
  9320. t.join();
  9321. ASSERT_FALSE(svr.is_running());
  9322. });
  9323. svr.wait_until_ready();
  9324. SSLClient cli(HOST, PORT);
  9325. cli.set_connection_timeout(30);
  9326. auto res = cli.Get("/test");
  9327. ASSERT_TRUE(!res);
  9328. // When client cert is missing and server requires it, connection fails
  9329. // Error type depends on backend implementation
  9330. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9331. res.error() == Error::SSLConnection);
  9332. // Verify backend error is captured
  9333. // Note: This test may have different error codes depending on the exact
  9334. // verification failure
  9335. EXPECT_NE(0UL, res.ssl_backend_error());
  9336. }
  9337. TEST(SSLClientServerTest, TrustDirOptional) {
  9338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9339. ASSERT_TRUE(svr.is_valid());
  9340. svr.Get("/test", [&](const Request &, Response &res) {
  9341. res.set_content("test", "text/plain");
  9342. });
  9343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. ASSERT_FALSE(svr.is_running());
  9348. });
  9349. svr.wait_until_ready();
  9350. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9351. cli.enable_server_certificate_verification(false);
  9352. cli.set_connection_timeout(30);
  9353. auto res = cli.Get("/test");
  9354. ASSERT_TRUE(res);
  9355. ASSERT_EQ(StatusCode::OK_200, res->status);
  9356. }
  9357. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9358. class NoListenSSLServer : public SSLServer {
  9359. public:
  9360. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9361. const char *client_ca_cert_file_path,
  9362. const char *client_ca_cert_dir_path = nullptr)
  9363. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9364. client_ca_cert_dir_path),
  9365. stop_(false) {}
  9366. std::atomic_bool stop_;
  9367. private:
  9368. bool process_and_close_socket(socket_t /*sock*/) override {
  9369. // Don't create SSL context
  9370. while (!stop_.load()) {
  9371. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9372. }
  9373. return true;
  9374. }
  9375. };
  9376. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9377. CLIENT_CA_CERT_FILE);
  9378. ASSERT_TRUE(svr.is_valid());
  9379. svr.Get("/test", [&](const Request &, Response &res) {
  9380. res.set_content("test", "text/plain");
  9381. });
  9382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9383. auto se = detail::scope_exit([&] {
  9384. svr.stop_ = true;
  9385. svr.stop();
  9386. t.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9391. cli.enable_server_certificate_verification(false);
  9392. cli.set_connection_timeout(1);
  9393. auto res = cli.Get("/test");
  9394. ASSERT_TRUE(!res);
  9395. EXPECT_EQ(Error::SSLConnection, res.error());
  9396. // Timeout results in WantRead error code (maps to backend-specific value)
  9397. EXPECT_NE(0, res.ssl_error());
  9398. }
  9399. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9400. // Test SSLServer with client certificate verification using the standard
  9401. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9403. CLIENT_CA_CERT_DIR);
  9404. ASSERT_TRUE(svr.is_valid());
  9405. svr.Get("/test", [&](const Request &req, Response &res) {
  9406. res.set_content("test", "text/plain");
  9407. auto cert = req.peer_cert();
  9408. ASSERT_TRUE(static_cast<bool>(cert));
  9409. auto common_name = cert.subject_cn();
  9410. EXPECT_EQ("Common Name", common_name);
  9411. });
  9412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9413. auto se = detail::scope_exit([&] {
  9414. svr.stop();
  9415. t.join();
  9416. ASSERT_FALSE(svr.is_running());
  9417. });
  9418. svr.wait_until_ready();
  9419. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9420. cli.enable_server_certificate_verification(false);
  9421. cli.set_connection_timeout(30);
  9422. auto res = cli.Get("/test");
  9423. ASSERT_TRUE(res);
  9424. ASSERT_EQ(StatusCode::OK_200, res->status);
  9425. }
  9426. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9427. // Verifies that wildcard matching and exact matching work consistently
  9428. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9429. using namespace httplib::tls;
  9430. // We need a running server to test against
  9431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9432. ASSERT_TRUE(svr.is_valid());
  9433. svr.Get("/test", [](const Request &, Response &res) {
  9434. res.set_content("ok", "text/plain");
  9435. });
  9436. thread t([&]() { svr.listen(HOST, PORT); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. t.join();
  9440. });
  9441. svr.wait_until_ready();
  9442. bool verify_callback_called = false;
  9443. bool verify_result_wrong = false;
  9444. SSLClient cli(HOST, PORT);
  9445. cli.enable_server_certificate_verification(true);
  9446. cli.set_ca_cert_path(CA_CERT_FILE);
  9447. cli.set_connection_timeout(5);
  9448. // Note: Test certificate has CN="Common Name", not "localhost"
  9449. bool verify_result_cn = false;
  9450. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9451. verify_callback_called = true;
  9452. if (!ctx.cert) return false;
  9453. // Test 1: "Common Name" should match (our test server cert CN)
  9454. verify_result_cn = ctx.check_hostname("Common Name");
  9455. // Test 2: wrong hostname should not match
  9456. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9457. return true; // Accept for the purpose of this test
  9458. });
  9459. auto res = cli.Get("/test");
  9460. // The request may succeed or fail depending on cert configuration
  9461. // but the callback should have been called
  9462. ASSERT_TRUE(verify_callback_called)
  9463. << "Verify callback should have been called";
  9464. // CN="Common Name" should match our test certificate
  9465. //
  9466. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9467. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9468. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9469. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9470. // <openssl/base.h>, which is included transitively when
  9471. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9472. #if defined(OPENSSL_IS_BORINGSSL)
  9473. EXPECT_FALSE(verify_result_cn)
  9474. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9475. #else
  9476. EXPECT_TRUE(verify_result_cn)
  9477. << "verify_hostname should match 'Common Name' (certificate CN)";
  9478. #endif
  9479. // Wrong hostname should not match
  9480. EXPECT_FALSE(verify_result_wrong)
  9481. << "verify_hostname should not match 'wronghost.example.com'";
  9482. }
  9483. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9484. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9485. // X509_check_ip behavior and must hold for every backend.
  9486. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9487. using namespace httplib::tls;
  9488. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9489. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9490. ASSERT_TRUE(svr.is_valid());
  9491. svr.Get("/test", [](const Request &, Response &res) {
  9492. res.set_content("ok", "text/plain");
  9493. });
  9494. thread t([&]() { svr.listen(HOST, PORT); });
  9495. auto se = detail::scope_exit([&] {
  9496. svr.stop();
  9497. t.join();
  9498. });
  9499. svr.wait_until_ready();
  9500. bool verify_callback_called = false;
  9501. bool ip_matched_via_cn = true;
  9502. SSLClient cli(HOST, PORT);
  9503. cli.enable_server_certificate_verification(true);
  9504. cli.set_ca_cert_path(CA_CERT_FILE);
  9505. cli.set_connection_timeout(5);
  9506. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9507. verify_callback_called = true;
  9508. if (!ctx.cert) return false;
  9509. // The IP appears only in the CN, so it must NOT be accepted.
  9510. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9511. return true; // Accept for the purpose of this test
  9512. });
  9513. cli.Get("/test");
  9514. ASSERT_TRUE(verify_callback_called)
  9515. << "Verify callback should have been called";
  9516. EXPECT_FALSE(ip_matched_via_cn)
  9517. << "An IP host must not be authenticated via the certificate CN";
  9518. }
  9519. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9520. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9521. using namespace httplib::tls;
  9522. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9523. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9524. ASSERT_TRUE(svr.is_valid());
  9525. svr.Get("/test", [](const Request &, Response &res) {
  9526. res.set_content("ok", "text/plain");
  9527. });
  9528. thread t([&]() { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. });
  9533. svr.wait_until_ready();
  9534. bool verify_callback_called = false;
  9535. bool san_matched = false;
  9536. bool wrong_ipv6_matched = true;
  9537. bool cn_ipv6_matched = true;
  9538. SSLClient cli(HOST, PORT);
  9539. cli.enable_server_certificate_verification(true);
  9540. cli.set_ca_cert_path(CA_CERT_FILE);
  9541. cli.set_connection_timeout(5);
  9542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9543. verify_callback_called = true;
  9544. if (!ctx.cert) return false;
  9545. // Matches the IPv6 iPAddress SAN.
  9546. san_matched = ctx.check_hostname("2001:db8::1");
  9547. // A different IPv6 address must not match.
  9548. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9549. // "::1" lives only in the CN, so it must not be accepted.
  9550. cn_ipv6_matched = ctx.check_hostname("::1");
  9551. return true; // Accept for the purpose of this test
  9552. });
  9553. cli.Get("/test");
  9554. ASSERT_TRUE(verify_callback_called)
  9555. << "Verify callback should have been called";
  9556. EXPECT_TRUE(san_matched)
  9557. << "verify_hostname should match an IPv6 iPAddress SAN";
  9558. EXPECT_FALSE(wrong_ipv6_matched)
  9559. << "verify_hostname should not match a non-matching IPv6 address";
  9560. EXPECT_FALSE(cn_ipv6_matched)
  9561. << "An IPv6 host must not be authenticated via the certificate CN";
  9562. }
  9563. #endif
  9564. // mbedTLS-specific callback constructor test
  9565. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9566. #ifdef CPPHTTPLIB_SSL_ENABLED
  9567. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9569. ASSERT_TRUE(svr.is_valid());
  9570. // Set up a handler to verify client certificate is present
  9571. bool client_cert_verified = false;
  9572. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9573. // Verify that client certificate was provided
  9574. client_cert_verified = true;
  9575. res.set_content("success", "text/plain");
  9576. });
  9577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. // Client with certificate
  9585. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9586. cli.enable_server_certificate_verification(false);
  9587. cli.set_connection_timeout(30);
  9588. auto res = cli.Get("/test");
  9589. ASSERT_TRUE(res);
  9590. ASSERT_EQ(StatusCode::OK_200, res->status);
  9591. ASSERT_TRUE(client_cert_verified);
  9592. EXPECT_EQ("success", res->body);
  9593. }
  9594. #endif
  9595. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9596. // backends
  9597. #ifdef CPPHTTPLIB_SSL_ENABLED
  9598. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9599. using namespace httplib::tls;
  9600. // Test that when client CA cert file is provided,
  9601. // the server properly requests and validates client certificates
  9602. // Create a server with client authentication
  9603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9604. ASSERT_TRUE(svr.is_valid());
  9605. bool handler_called = false;
  9606. svr.Get("/test", [&](const Request &req, Response &res) {
  9607. handler_called = true;
  9608. // Verify that a client certificate was provided
  9609. auto cert = req.peer_cert();
  9610. ASSERT_TRUE(static_cast<bool>(cert));
  9611. // Get the issuer name
  9612. std::string issuer_str = cert.issuer_name();
  9613. ASSERT_FALSE(issuer_str.empty());
  9614. // The client certificate should be issued by our test CA
  9615. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9616. res.set_content("authenticated", "text/plain");
  9617. });
  9618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. // Connect with a client certificate issued by the CA
  9626. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9627. cli.enable_server_certificate_verification(false);
  9628. cli.set_connection_timeout(30);
  9629. auto res = cli.Get("/test");
  9630. ASSERT_TRUE(res);
  9631. ASSERT_EQ(StatusCode::OK_200, res->status);
  9632. ASSERT_TRUE(handler_called);
  9633. EXPECT_EQ("authenticated", res->body);
  9634. }
  9635. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9636. using namespace httplib::tls;
  9637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9638. ASSERT_TRUE(svr.is_valid());
  9639. svr.Get("/test", [](const Request &, Response &res) {
  9640. res.set_content("ok", "text/plain");
  9641. });
  9642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. t.join();
  9646. });
  9647. svr.wait_until_ready();
  9648. SSLClient cli(HOST, PORT);
  9649. cli.enable_server_certificate_verification(false);
  9650. cli.set_connection_timeout(30);
  9651. bool cert_checked = false;
  9652. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9653. if (ctx.cert) {
  9654. auto sans = ctx.sans();
  9655. // Test certificate may or may not have SANs - just verify the API
  9656. // works If SANs exist, verify the types are valid
  9657. for (const auto &san : sans) {
  9658. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9659. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9660. san.type == SanType::OTHER);
  9661. EXPECT_FALSE(san.value.empty());
  9662. }
  9663. cert_checked = true;
  9664. }
  9665. return true;
  9666. });
  9667. auto res = cli.Get("/test");
  9668. ASSERT_TRUE(res);
  9669. EXPECT_TRUE(cert_checked);
  9670. }
  9671. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9672. using namespace httplib::tls;
  9673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9674. ASSERT_TRUE(svr.is_valid());
  9675. svr.Get("/test", [](const Request &, Response &res) {
  9676. res.set_content("ok", "text/plain");
  9677. });
  9678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. });
  9683. svr.wait_until_ready();
  9684. SSLClient cli(HOST, PORT);
  9685. cli.enable_server_certificate_verification(false);
  9686. cli.set_connection_timeout(30);
  9687. bool validity_checked = false;
  9688. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9689. if (ctx.cert) {
  9690. time_t not_before = 0, not_after = 0;
  9691. bool result = ctx.validity(not_before, not_after);
  9692. EXPECT_TRUE(result);
  9693. // Verify that not_before < now < not_after for a valid cert
  9694. time_t now = time(nullptr);
  9695. EXPECT_LT(not_before, now);
  9696. EXPECT_GT(not_after, now);
  9697. validity_checked = true;
  9698. }
  9699. return true;
  9700. });
  9701. auto res = cli.Get("/test");
  9702. ASSERT_TRUE(res);
  9703. EXPECT_TRUE(validity_checked);
  9704. }
  9705. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9706. using namespace httplib::tls;
  9707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9708. ASSERT_TRUE(svr.is_valid());
  9709. svr.Get("/test", [](const Request &, Response &res) {
  9710. res.set_content("ok", "text/plain");
  9711. });
  9712. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9713. auto se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. t.join();
  9716. });
  9717. svr.wait_until_ready();
  9718. SSLClient cli(HOST, PORT);
  9719. cli.enable_server_certificate_verification(false);
  9720. cli.set_connection_timeout(30);
  9721. bool serial_checked = false;
  9722. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9723. if (ctx.cert) {
  9724. std::string serial = ctx.serial();
  9725. EXPECT_FALSE(serial.empty());
  9726. // Serial should be a hex string
  9727. for (char c : serial) {
  9728. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9729. (c >= 'a' && c <= 'f'));
  9730. }
  9731. serial_checked = true;
  9732. }
  9733. return true;
  9734. });
  9735. auto res = cli.Get("/test");
  9736. ASSERT_TRUE(res);
  9737. EXPECT_TRUE(serial_checked);
  9738. }
  9739. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9740. // Test 1: Valid CA file - no error should be recorded
  9741. {
  9742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9743. CLIENT_CA_CERT_FILE);
  9744. ASSERT_TRUE(svr.is_valid());
  9745. // With valid setup, last_ssl_error should be 0
  9746. EXPECT_EQ(0, svr.ssl_last_error());
  9747. }
  9748. // Test 2: Invalid CA file content
  9749. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9750. {
  9751. // Create a temporary file with completely invalid content
  9752. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9753. {
  9754. std::ofstream ofs(temp_invalid_ca);
  9755. ofs << "This is not a certificate file at all\n";
  9756. ofs << "Just plain text content\n";
  9757. }
  9758. // Create server with invalid CA file
  9759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9760. // Clean up temporary file
  9761. std::remove(temp_invalid_ca);
  9762. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9763. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9764. // Note: SSL_CTX_load_verify_locations typically fails first,
  9765. // but our error handling code path is still exercised
  9766. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9767. }
  9768. }
  9769. TEST(VerifyCallbackTest, VerifyContextFields) {
  9770. using namespace httplib::tls;
  9771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9772. ASSERT_TRUE(svr.is_valid());
  9773. svr.Get("/test", [](const Request &, Response &res) {
  9774. res.set_content("ok", "text/plain");
  9775. });
  9776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9777. auto se = detail::scope_exit([&] {
  9778. svr.stop();
  9779. t.join();
  9780. });
  9781. svr.wait_until_ready();
  9782. SSLClient cli(HOST, PORT);
  9783. cli.enable_server_certificate_verification(false);
  9784. cli.set_connection_timeout(30);
  9785. int callback_count = 0;
  9786. bool saw_leaf_cert = false;
  9787. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9788. if (ctx.cert) {
  9789. callback_count++;
  9790. // We should see at least one certificate (the leaf)
  9791. std::string cn = ctx.subject_cn();
  9792. if (!cn.empty()) { saw_leaf_cert = true; }
  9793. // Verify context fields are populated
  9794. EXPECT_NE(ctx.session, nullptr);
  9795. EXPECT_GE(ctx.depth, 0);
  9796. }
  9797. return true;
  9798. });
  9799. auto res = cli.Get("/test");
  9800. ASSERT_TRUE(res);
  9801. EXPECT_GT(callback_count, 0);
  9802. EXPECT_TRUE(saw_leaf_cert);
  9803. }
  9804. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9805. using httplib::tls::TlsError;
  9806. // Test that verify_error_to_string returns empty for success
  9807. std::string success_str = TlsError::verify_error_to_string(0);
  9808. EXPECT_TRUE(success_str.empty());
  9809. // Test that verify_error_to_string returns non-empty for error codes
  9810. // Using a common error code (certificate expired)
  9811. std::string error_str =
  9812. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9813. EXPECT_FALSE(error_str.empty());
  9814. }
  9815. TEST(SessionVerifierTest, CertificateAccepted) {
  9816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9817. ASSERT_TRUE(svr.is_valid());
  9818. svr.Get("/test", [](const Request &, Response &res) {
  9819. res.set_content("ok", "text/plain");
  9820. });
  9821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9822. auto se = detail::scope_exit([&] {
  9823. svr.stop();
  9824. t.join();
  9825. });
  9826. svr.wait_until_ready();
  9827. SSLClient cli(HOST, PORT);
  9828. cli.enable_server_certificate_verification(false);
  9829. cli.set_connection_timeout(30);
  9830. bool callback_called = false;
  9831. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9832. EXPECT_NE(session, nullptr);
  9833. callback_called = true;
  9834. return SSLVerifierResponse::CertificateAccepted;
  9835. });
  9836. auto res = cli.Get("/test");
  9837. ASSERT_TRUE(res);
  9838. EXPECT_EQ(200, res->status);
  9839. EXPECT_TRUE(callback_called);
  9840. }
  9841. TEST(SessionVerifierTest, CertificateRejected) {
  9842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9843. ASSERT_TRUE(svr.is_valid());
  9844. svr.Get("/test", [](const Request &, Response &res) {
  9845. res.set_content("ok", "text/plain");
  9846. });
  9847. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9848. auto se = detail::scope_exit([&] {
  9849. svr.stop();
  9850. t.join();
  9851. });
  9852. svr.wait_until_ready();
  9853. SSLClient cli(HOST, PORT);
  9854. cli.enable_server_certificate_verification(false);
  9855. cli.set_connection_timeout(30);
  9856. bool callback_called = false;
  9857. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9858. EXPECT_NE(session, nullptr);
  9859. callback_called = true;
  9860. return SSLVerifierResponse::CertificateRejected;
  9861. });
  9862. auto res = cli.Get("/test");
  9863. EXPECT_FALSE(res);
  9864. EXPECT_TRUE(callback_called);
  9865. }
  9866. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9868. ASSERT_TRUE(svr.is_valid());
  9869. svr.Get("/test", [](const Request &, Response &res) {
  9870. res.set_content("ok", "text/plain");
  9871. });
  9872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9873. auto se = detail::scope_exit([&] {
  9874. svr.stop();
  9875. t.join();
  9876. });
  9877. svr.wait_until_ready();
  9878. // NoDecisionMade with verification disabled should succeed (no default check)
  9879. SSLClient cli(HOST, PORT);
  9880. cli.enable_server_certificate_verification(false);
  9881. cli.set_connection_timeout(30);
  9882. bool callback_called = false;
  9883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9884. EXPECT_NE(session, nullptr);
  9885. callback_called = true;
  9886. return SSLVerifierResponse::NoDecisionMade;
  9887. });
  9888. auto res = cli.Get("/test");
  9889. ASSERT_TRUE(res);
  9890. EXPECT_EQ(200, res->status);
  9891. EXPECT_TRUE(callback_called);
  9892. }
  9893. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9895. ASSERT_TRUE(svr.is_valid());
  9896. svr.Get("/test", [](const Request &, Response &res) {
  9897. res.set_content("ok", "text/plain");
  9898. });
  9899. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9900. auto se = detail::scope_exit([&] {
  9901. svr.stop();
  9902. t.join();
  9903. });
  9904. svr.wait_until_ready();
  9905. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9906. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9907. // so we only check that the request fails, not whether the callback was
  9908. // called.
  9909. SSLClient cli(HOST, PORT);
  9910. cli.enable_server_certificate_verification(true);
  9911. cli.set_connection_timeout(30);
  9912. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9913. EXPECT_NE(session, nullptr);
  9914. return SSLVerifierResponse::NoDecisionMade;
  9915. });
  9916. auto res = cli.Get("/test");
  9917. EXPECT_FALSE(res);
  9918. }
  9919. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9920. // Test SSL server using PemMemory constructor with client CA certificates
  9921. // Read PEM files
  9922. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9923. read_file(SERVER_CERT_FILE, server_cert_pem);
  9924. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9925. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9926. // Create SSLServer with PemMemory constructor including client CA
  9927. SSLServer::PemMemory server_pem = {
  9928. server_cert_pem.c_str(),
  9929. server_cert_pem.size(),
  9930. server_key_pem.c_str(),
  9931. server_key_pem.size(),
  9932. client_ca_pem.c_str(),
  9933. client_ca_pem.size(),
  9934. nullptr // no password for server key
  9935. };
  9936. SSLServer svr(server_pem);
  9937. ASSERT_TRUE(svr.is_valid());
  9938. // No SSL error should be recorded for valid setup
  9939. EXPECT_EQ(0, svr.ssl_last_error());
  9940. // Set up server endpoints
  9941. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9942. res.set_content("ok", "text/plain");
  9943. });
  9944. // Start server in a thread
  9945. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9946. svr.wait_until_ready();
  9947. // Connect with client certificate (using constructor with paths)
  9948. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9949. cli.enable_server_certificate_verification(false);
  9950. auto res = cli.Get("/test-pem-ca");
  9951. ASSERT_TRUE(res);
  9952. EXPECT_EQ(200, res->status);
  9953. EXPECT_EQ("ok", res->body);
  9954. svr.stop();
  9955. server_thread.join();
  9956. }
  9957. #endif
  9958. #ifdef _WIN32
  9959. TEST(CleanupTest, WSACleanup) {
  9960. int ret = WSACleanup();
  9961. ASSERT_EQ(0, ret);
  9962. }
  9963. #endif
  9964. #ifndef CPPHTTPLIB_SSL_ENABLED
  9965. TEST(NoSSLSupport, SimpleInterface) {
  9966. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9967. }
  9968. #endif
  9969. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9970. TEST(InvalidScheme, SimpleInterface) {
  9971. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9972. }
  9973. #endif
  9974. TEST(NoScheme, SimpleInterface) {
  9975. Client cli("yahoo.com:80");
  9976. ASSERT_TRUE(cli.is_valid());
  9977. }
  9978. TEST(SendAPI, SimpleInterface_Online) {
  9979. Client cli("http://yahoo.com");
  9980. Request req;
  9981. req.method = "GET";
  9982. req.path = "/";
  9983. auto res = cli.send(req);
  9984. ASSERT_TRUE(res);
  9985. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9986. }
  9987. TEST(SendAPI, WithParamsInRequest) {
  9988. Server svr;
  9989. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9990. EXPECT_TRUE(req.has_param("test"));
  9991. EXPECT_EQ("test_value", req.get_param_value("test"));
  9992. });
  9993. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. t.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. Client cli(HOST, PORT);
  10001. {
  10002. Request req;
  10003. req.method = "GET";
  10004. req.path = "/";
  10005. req.params.emplace("test", "test_value");
  10006. auto res = cli.send(req);
  10007. ASSERT_TRUE(res);
  10008. }
  10009. {
  10010. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10011. ASSERT_TRUE(res);
  10012. }
  10013. }
  10014. TEST(ClientImplMethods, GetSocketTest) {
  10015. httplib::Server svr;
  10016. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10017. res.status = StatusCode::OK_200;
  10018. });
  10019. auto port = svr.bind_to_any_port("127.0.0.1");
  10020. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. thread.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. {
  10028. httplib::Client cli("127.0.0.1", port);
  10029. cli.set_keep_alive(true);
  10030. // Use the behavior of cpp-httplib of opening the connection
  10031. // only when the first request happens. If that changes,
  10032. // this test would be obsolete.
  10033. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10034. // This also implicitly tests the server. But other tests would fail much
  10035. // earlier than this one to be considered.
  10036. auto res = cli.Get("/");
  10037. ASSERT_TRUE(res);
  10038. EXPECT_EQ(StatusCode::OK_200, res->status);
  10039. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10040. }
  10041. }
  10042. #ifdef CPPHTTPLIB_SSL_ENABLED
  10043. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10044. Client cli("http://yahoo.com");
  10045. auto res = cli.Get("/");
  10046. ASSERT_TRUE(res);
  10047. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10048. cli.set_follow_location(true);
  10049. res = cli.Get("/");
  10050. ASSERT_TRUE(res);
  10051. EXPECT_EQ(StatusCode::OK_200, res->status);
  10052. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10053. }
  10054. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10055. Client cli("https://yahoo.com");
  10056. auto res = cli.Get("/");
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10059. cli.set_follow_location(true);
  10060. res = cli.Get("/");
  10061. ASSERT_TRUE(res);
  10062. EXPECT_EQ(StatusCode::OK_200, res->status);
  10063. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10064. }
  10065. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10066. Client cli("https://yahoo.com");
  10067. auto res = cli.Get("/");
  10068. ASSERT_TRUE(res);
  10069. ASSERT_FALSE(!res);
  10070. ASSERT_TRUE(res);
  10071. ASSERT_FALSE(res == nullptr);
  10072. ASSERT_TRUE(res != nullptr);
  10073. EXPECT_EQ(Error::Success, res.error());
  10074. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10075. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10076. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10077. cli.set_follow_location(true);
  10078. res = cli.Get("/");
  10079. ASSERT_TRUE(res);
  10080. EXPECT_EQ(Error::Success, res.error());
  10081. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10082. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10083. EXPECT_EQ(StatusCode::OK_200, res->status);
  10084. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10085. }
  10086. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10087. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10088. Client cli("https://cdnjs.cloudflare.com");
  10089. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10090. Headers{{"Accept-Encoding", "br"}});
  10091. ASSERT_TRUE(res);
  10092. EXPECT_EQ(StatusCode::OK_200, res->status);
  10093. EXPECT_EQ(287630U, res->body.size());
  10094. EXPECT_EQ("application/javascript; charset=utf-8",
  10095. res->get_header_value("Content-Type"));
  10096. }
  10097. #endif
  10098. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10099. #undef REDIR_HOST // Silence compiler warning
  10100. #define REDIR_HOST "https://httpbingo.org"
  10101. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10102. Client cli(REDIR_HOST);
  10103. cli.set_follow_location(true);
  10104. auto res =
  10105. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10106. ASSERT_TRUE(res);
  10107. EXPECT_EQ(StatusCode::OK_200, res->status);
  10108. }
  10109. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10110. Client cli(REDIR_HOST);
  10111. cli.set_follow_location(true);
  10112. Params params;
  10113. params.emplace("url", "http://example.com");
  10114. params.emplace("status_code", "302");
  10115. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10116. ASSERT_TRUE(res);
  10117. EXPECT_EQ(StatusCode::OK_200, res->status);
  10118. }
  10119. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10120. Client cli(REDIR_HOST);
  10121. cli.set_follow_location(true);
  10122. Params params;
  10123. params.emplace("url", "http://example.com");
  10124. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10125. ASSERT_TRUE(res);
  10126. EXPECT_EQ(StatusCode::OK_200, res->status);
  10127. }
  10128. TEST(HttpToHttpsRedirectTest, CertFile) {
  10129. auto ssl_port = PORT + 1;
  10130. Server svr;
  10131. ASSERT_TRUE(svr.is_valid());
  10132. svr.Get("/index", [&](const Request &, Response &res) {
  10133. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10134. "/index");
  10135. svr.stop();
  10136. });
  10137. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10138. ASSERT_TRUE(ssl_svr.is_valid());
  10139. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10140. res.set_content("test", "text/plain");
  10141. ssl_svr.stop();
  10142. });
  10143. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10144. thread t2 =
  10145. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10146. auto se = detail::scope_exit([&] {
  10147. t2.join();
  10148. t.join();
  10149. ASSERT_FALSE(svr.is_running());
  10150. });
  10151. svr.wait_until_ready();
  10152. ssl_svr.wait_until_ready();
  10153. Client cli("127.0.0.1", PORT);
  10154. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10155. cli.enable_server_certificate_verification(true);
  10156. cli.set_follow_location(true);
  10157. cli.set_connection_timeout(30);
  10158. auto res = cli.Get("/index");
  10159. ASSERT_TRUE(res);
  10160. ASSERT_EQ(StatusCode::OK_200, res->status);
  10161. }
  10162. TEST(SSLClientRedirectTest, CertFile) {
  10163. auto ssl_port = PORT + 1;
  10164. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10165. ASSERT_TRUE(ssl_svr1.is_valid());
  10166. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10167. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10168. "/index");
  10169. ssl_svr1.stop();
  10170. });
  10171. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10172. ASSERT_TRUE(ssl_svr2.is_valid());
  10173. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10174. res.set_content("test", "text/plain");
  10175. ssl_svr2.stop();
  10176. });
  10177. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10178. thread t2 =
  10179. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10180. auto se = detail::scope_exit([&] {
  10181. t2.join();
  10182. t.join();
  10183. ASSERT_FALSE(ssl_svr1.is_running());
  10184. });
  10185. ssl_svr1.wait_until_ready();
  10186. ssl_svr2.wait_until_ready();
  10187. SSLClient cli("127.0.0.1", PORT);
  10188. std::string cert;
  10189. read_file(SERVER_CERT2_FILE, cert);
  10190. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10191. cli.enable_server_certificate_verification(true);
  10192. cli.set_follow_location(true);
  10193. cli.set_connection_timeout(30);
  10194. auto res = cli.Get("/index");
  10195. ASSERT_TRUE(res);
  10196. ASSERT_EQ(StatusCode::OK_200, res->status);
  10197. }
  10198. #endif
  10199. #ifdef CPPHTTPLIB_SSL_ENABLED
  10200. // Test that set_ca_cert_store() skips system certs (consistent with
  10201. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10202. // should be trusted - system certs should NOT be loaded.
  10203. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10204. // Load a specific cert that is NOT a system CA cert
  10205. std::string cert;
  10206. read_file(SERVER_CERT2_FILE, cert);
  10207. SSLClient cli("google.com");
  10208. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10209. cli.enable_server_certificate_verification(true);
  10210. // This should FAIL because:
  10211. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10212. // 2. System certs should NOT be loaded when custom store is set
  10213. // If system certs WERE loaded, this would succeed
  10214. auto res = cli.Get("/");
  10215. ASSERT_FALSE(res);
  10216. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10217. }
  10218. // Same as above, but through the native store handle path. Regression test:
  10219. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10220. // merged system certs into the user-provided store.
  10221. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10222. std::string cert;
  10223. read_file(SERVER_CERT2_FILE, cert);
  10224. SSLClient cli("google.com");
  10225. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10226. cli.enable_server_certificate_verification(true);
  10227. auto res = cli.Get("/");
  10228. ASSERT_FALSE(res);
  10229. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10230. }
  10231. // A custom store set via the native handle must still verify a server whose
  10232. // cert it does contain.
  10233. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10234. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10235. ASSERT_TRUE(svr.is_valid());
  10236. svr.Get("/test", [&](const Request &, Response &res) {
  10237. res.set_content("test", "text/plain");
  10238. });
  10239. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. t.join();
  10243. ASSERT_FALSE(svr.is_running());
  10244. });
  10245. svr.wait_until_ready();
  10246. SSLClient cli("127.0.0.1", PORT);
  10247. std::string cert;
  10248. read_file(SERVER_CERT2_FILE, cert);
  10249. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10250. cli.enable_server_certificate_verification(true);
  10251. cli.set_connection_timeout(30);
  10252. auto res = cli.Get("/test");
  10253. ASSERT_TRUE(res);
  10254. ASSERT_EQ(StatusCode::OK_200, res->status);
  10255. }
  10256. // CA certs loaded through the universal Client must be transferred to the
  10257. // client created internally for following an HTTPS redirect. Regression test:
  10258. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10259. // the CA data for redirect transfer.
  10260. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10261. auto ssl_port = PORT + 1;
  10262. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10263. ASSERT_TRUE(ssl_svr1.is_valid());
  10264. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10265. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10266. "/index");
  10267. });
  10268. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10269. ASSERT_TRUE(ssl_svr2.is_valid());
  10270. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10271. res.set_content("test", "text/plain");
  10272. });
  10273. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10274. thread t2 =
  10275. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10276. auto se = detail::scope_exit([&] {
  10277. ssl_svr2.stop();
  10278. ssl_svr1.stop();
  10279. t2.join();
  10280. t.join();
  10281. ASSERT_FALSE(ssl_svr1.is_running());
  10282. });
  10283. ssl_svr1.wait_until_ready();
  10284. ssl_svr2.wait_until_ready();
  10285. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10286. std::string cert;
  10287. read_file(SERVER_CERT2_FILE, cert);
  10288. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10289. cli.enable_server_certificate_verification(true);
  10290. cli.set_follow_location(true);
  10291. cli.set_connection_timeout(30);
  10292. auto res = cli.Get("/index");
  10293. ASSERT_TRUE(res);
  10294. ASSERT_EQ(StatusCode::OK_200, res->status);
  10295. }
  10296. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10297. // so a host signed by a system CA verifies even though a custom CA is set
  10298. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10299. std::string cert;
  10300. read_file(SERVER_CERT2_FILE, cert);
  10301. SSLClient cli("google.com");
  10302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10303. cli.enable_system_ca(true);
  10304. cli.enable_server_certificate_verification(true);
  10305. auto res = cli.Get("/");
  10306. ASSERT_TRUE(res);
  10307. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10308. }
  10309. // The custom CA remains effective when combined with the system CA
  10310. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10311. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10312. ASSERT_TRUE(svr.is_valid());
  10313. svr.Get("/test", [&](const Request &, Response &res) {
  10314. res.set_content("test", "text/plain");
  10315. });
  10316. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10317. auto se = detail::scope_exit([&] {
  10318. svr.stop();
  10319. t.join();
  10320. ASSERT_FALSE(svr.is_running());
  10321. });
  10322. svr.wait_until_ready();
  10323. SSLClient cli("127.0.0.1", PORT);
  10324. std::string cert;
  10325. read_file(SERVER_CERT2_FILE, cert);
  10326. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10327. cli.enable_system_ca(true);
  10328. cli.enable_server_certificate_verification(true);
  10329. cli.set_connection_timeout(30);
  10330. auto res = cli.Get("/test");
  10331. ASSERT_TRUE(res);
  10332. ASSERT_EQ(StatusCode::OK_200, res->status);
  10333. }
  10334. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10335. // skip chain verification entirely (only the certificate identity was
  10336. // checked), so a server presenting an untrusted certificate with a matching
  10337. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10338. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10340. ASSERT_TRUE(svr.is_valid());
  10341. svr.Get("/test", [&](const Request &, Response &res) {
  10342. res.set_content("test", "text/plain");
  10343. });
  10344. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. t.join();
  10348. ASSERT_FALSE(svr.is_running());
  10349. });
  10350. svr.wait_until_ready();
  10351. SSLClient cli("127.0.0.1", PORT);
  10352. std::string cert;
  10353. // A trusted CA that did not sign the server certificate. The server cert
  10354. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10355. // this connection.
  10356. read_file(CLIENT_CA_CERT_FILE, cert);
  10357. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10358. cli.enable_server_certificate_verification(true);
  10359. cli.set_connection_timeout(30);
  10360. auto res = cli.Get("/test");
  10361. ASSERT_FALSE(res);
  10362. }
  10363. // enable_system_ca(false) prevents system CA loading entirely
  10364. TEST(SSLClientTest, DisableSystemCa_Online) {
  10365. SSLClient cli("google.com");
  10366. cli.enable_system_ca(false);
  10367. cli.enable_server_certificate_verification(true);
  10368. auto res = cli.Get("/");
  10369. ASSERT_FALSE(res);
  10370. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10371. // itself when the CA chain is empty
  10372. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10373. res.error() == Error::SSLConnection);
  10374. }
  10375. // The universal Client forwards enable_system_ca()
  10376. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10377. std::string cert;
  10378. read_file(SERVER_CERT2_FILE, cert);
  10379. Client cli("https://google.com");
  10380. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10381. cli.enable_system_ca(true);
  10382. cli.enable_server_certificate_verification(true);
  10383. auto res = cli.Get("/");
  10384. ASSERT_TRUE(res);
  10385. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10386. }
  10387. // The system CA policy must carry over to the client created internally for
  10388. // following a cross-host HTTPS redirect
  10389. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10390. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10391. ASSERT_TRUE(svr.is_valid());
  10392. svr.Get("/index", [&](const Request &, Response &res) {
  10393. res.set_redirect("https://www.google.com/");
  10394. });
  10395. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10396. auto se = detail::scope_exit([&] {
  10397. svr.stop();
  10398. t.join();
  10399. ASSERT_FALSE(svr.is_running());
  10400. });
  10401. svr.wait_until_ready();
  10402. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10403. std::string cert;
  10404. read_file(SERVER_CERT2_FILE, cert);
  10405. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10406. cli.enable_system_ca(true);
  10407. cli.enable_server_certificate_verification(true);
  10408. cli.set_follow_location(true);
  10409. cli.set_connection_timeout(30);
  10410. // Receiving any response proves the redirect client completed the TLS
  10411. // handshake with a system-CA-signed host
  10412. auto res = cli.Get("/index");
  10413. ASSERT_TRUE(res);
  10414. }
  10415. TEST(MultipartFormDataTest, LargeData) {
  10416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10417. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10418. const ContentReader &content_reader) {
  10419. if (req.is_multipart_form_data()) {
  10420. std::vector<FormData> items;
  10421. content_reader(
  10422. [&](const FormData &file) {
  10423. items.push_back(file);
  10424. return true;
  10425. },
  10426. [&](const char *data, size_t data_length) {
  10427. items.back().content.append(data, data_length);
  10428. return true;
  10429. });
  10430. EXPECT_TRUE(std::string(items[0].name) == "document");
  10431. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10432. EXPECT_TRUE(items[0].filename == "2MB_data");
  10433. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10434. EXPECT_TRUE(items[1].name == "hello");
  10435. EXPECT_TRUE(items[1].content == "world");
  10436. EXPECT_TRUE(items[1].filename == "");
  10437. EXPECT_TRUE(items[1].content_type == "");
  10438. } else {
  10439. std::string body;
  10440. content_reader([&](const char *data, size_t data_length) {
  10441. body.append(data, data_length);
  10442. return true;
  10443. });
  10444. }
  10445. });
  10446. auto port = svr.bind_to_any_port(HOST);
  10447. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10448. auto se = detail::scope_exit([&] {
  10449. svr.stop();
  10450. t.join();
  10451. ASSERT_FALSE(svr.is_running());
  10452. });
  10453. svr.wait_until_ready();
  10454. {
  10455. std::string data(1024 * 1024 * 2, '.');
  10456. std::stringstream buffer;
  10457. buffer << data;
  10458. SSLClient cli(HOST, port);
  10459. cli.enable_server_certificate_verification(false);
  10460. UploadFormDataItems items{
  10461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10462. {"hello", "world", "", ""},
  10463. };
  10464. auto res = cli.Post("/post", items);
  10465. ASSERT_TRUE(res);
  10466. ASSERT_EQ(StatusCode::OK_200, res->status);
  10467. }
  10468. }
  10469. TEST(MultipartFormDataTest, DataProviderItems) {
  10470. std::random_device seed_gen;
  10471. std::mt19937 random(seed_gen());
  10472. std::string rand1;
  10473. rand1.resize(1000);
  10474. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10475. std::string rand2;
  10476. rand2.resize(3000);
  10477. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10479. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10480. const ContentReader &content_reader) {
  10481. ASSERT_FALSE(req.is_multipart_form_data());
  10482. std::string body;
  10483. content_reader([&](const char *data, size_t data_length) {
  10484. body.append(data, data_length);
  10485. return true;
  10486. });
  10487. EXPECT_EQ(body, "");
  10488. });
  10489. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10490. const ContentReader &content_reader) {
  10491. ASSERT_TRUE(req.is_multipart_form_data());
  10492. std::vector<FormData> items;
  10493. content_reader(
  10494. [&](const FormData &file) {
  10495. items.push_back(file);
  10496. return true;
  10497. },
  10498. [&](const char *data, size_t data_length) {
  10499. items.back().content.append(data, data_length);
  10500. return true;
  10501. });
  10502. ASSERT_TRUE(items.size() == 2);
  10503. EXPECT_EQ(std::string(items[0].name), "name1");
  10504. EXPECT_EQ(items[0].content, "Testing123");
  10505. EXPECT_EQ(items[0].filename, "filename1");
  10506. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10507. EXPECT_EQ(items[1].name, "name2");
  10508. EXPECT_EQ(items[1].content, "Testing456");
  10509. EXPECT_EQ(items[1].filename, "");
  10510. EXPECT_EQ(items[1].content_type, "");
  10511. });
  10512. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10513. const ContentReader &content_reader) {
  10514. ASSERT_TRUE(req.is_multipart_form_data());
  10515. std::vector<FormData> items;
  10516. content_reader(
  10517. [&](const FormData &file) {
  10518. items.push_back(file);
  10519. return true;
  10520. },
  10521. [&](const char *data, size_t data_length) {
  10522. items.back().content.append(data, data_length);
  10523. return true;
  10524. });
  10525. ASSERT_TRUE(items.size() == 2);
  10526. EXPECT_EQ(items[0].name, "name3");
  10527. EXPECT_EQ(items[0].content, rand1);
  10528. EXPECT_EQ(items[0].filename, "filename3");
  10529. EXPECT_EQ(items[0].content_type, "");
  10530. EXPECT_EQ(items[1].name, "name4");
  10531. EXPECT_EQ(items[1].content, rand2);
  10532. EXPECT_EQ(items[1].filename, "filename4");
  10533. EXPECT_EQ(items[1].content_type, "");
  10534. });
  10535. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10536. const ContentReader &content_reader) {
  10537. ASSERT_TRUE(req.is_multipart_form_data());
  10538. std::vector<FormData> items;
  10539. content_reader(
  10540. [&](const FormData &file) {
  10541. items.push_back(file);
  10542. return true;
  10543. },
  10544. [&](const char *data, size_t data_length) {
  10545. items.back().content.append(data, data_length);
  10546. return true;
  10547. });
  10548. ASSERT_TRUE(items.size() == 4);
  10549. EXPECT_EQ(std::string(items[0].name), "name1");
  10550. EXPECT_EQ(items[0].content, "Testing123");
  10551. EXPECT_EQ(items[0].filename, "filename1");
  10552. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10553. EXPECT_EQ(items[1].name, "name2");
  10554. EXPECT_EQ(items[1].content, "Testing456");
  10555. EXPECT_EQ(items[1].filename, "");
  10556. EXPECT_EQ(items[1].content_type, "");
  10557. EXPECT_EQ(items[2].name, "name3");
  10558. EXPECT_EQ(items[2].content, rand1);
  10559. EXPECT_EQ(items[2].filename, "filename3");
  10560. EXPECT_EQ(items[2].content_type, "");
  10561. EXPECT_EQ(items[3].name, "name4");
  10562. EXPECT_EQ(items[3].content, rand2);
  10563. EXPECT_EQ(items[3].filename, "filename4");
  10564. EXPECT_EQ(items[3].content_type, "");
  10565. });
  10566. auto port = svr.bind_to_any_port("localhost");
  10567. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10568. auto se = detail::scope_exit([&] {
  10569. svr.stop();
  10570. t.join();
  10571. ASSERT_FALSE(svr.is_running());
  10572. });
  10573. svr.wait_until_ready();
  10574. {
  10575. SSLClient cli("localhost", port);
  10576. cli.enable_server_certificate_verification(false);
  10577. UploadFormDataItems items{
  10578. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10579. {"name2", "Testing456", "", ""}, // not a file
  10580. };
  10581. {
  10582. auto res = cli.Post("/post-none", {}, {}, {});
  10583. ASSERT_TRUE(res);
  10584. ASSERT_EQ(StatusCode::OK_200, res->status);
  10585. }
  10586. FormDataProviderItems providers;
  10587. {
  10588. auto res =
  10589. cli.Post("/post-items", {}, items, providers); // empty providers
  10590. ASSERT_TRUE(res);
  10591. ASSERT_EQ(StatusCode::OK_200, res->status);
  10592. }
  10593. providers.push_back({"name3",
  10594. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10595. // test the offset is given correctly at each step
  10596. if (!offset)
  10597. sink.os.write(rand1.data(), 30);
  10598. else if (offset == 30)
  10599. sink.os.write(rand1.data() + 30, 300);
  10600. else if (offset == 330)
  10601. sink.os.write(rand1.data() + 330, 670);
  10602. else if (offset == rand1.size())
  10603. sink.done();
  10604. return true;
  10605. },
  10606. "filename3",
  10607. {}});
  10608. providers.push_back({"name4",
  10609. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10610. // test the offset is given correctly at each step
  10611. if (!offset)
  10612. sink.os.write(rand2.data(), 2000);
  10613. else if (offset == 2000)
  10614. sink.os.write(rand2.data() + 2000, 1);
  10615. else if (offset == 2001)
  10616. sink.os.write(rand2.data() + 2001, 999);
  10617. else if (offset == rand2.size())
  10618. sink.done();
  10619. return true;
  10620. },
  10621. "filename4",
  10622. {}});
  10623. {
  10624. auto res = cli.Post("/post-providers", {}, {}, providers);
  10625. ASSERT_TRUE(res);
  10626. ASSERT_EQ(StatusCode::OK_200, res->status);
  10627. }
  10628. {
  10629. auto res = cli.Post("/post-both", {}, items, providers);
  10630. ASSERT_TRUE(res);
  10631. ASSERT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. }
  10634. }
  10635. TEST(MultipartFormDataTest, BadHeader) {
  10636. Server svr;
  10637. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10638. res.set_content("ok", "text/plain");
  10639. });
  10640. thread t = thread([&] { svr.listen(HOST, PORT); });
  10641. auto se = detail::scope_exit([&] {
  10642. svr.stop();
  10643. t.join();
  10644. ASSERT_FALSE(svr.is_running());
  10645. });
  10646. svr.wait_until_ready();
  10647. const std::string body =
  10648. "This is the preamble. It is to be ignored, though it\r\n"
  10649. "is a handy place for composition agents to include an\r\n"
  10650. "explanatory note to non-MIME conformant readers.\r\n"
  10651. "\r\n"
  10652. "\r\n"
  10653. "--simple boundary\r\n"
  10654. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10655. ": BAD...\r\n"
  10656. "\r\n"
  10657. "value1\r\n"
  10658. "--simple boundary\r\n"
  10659. "Content-Disposition: form-data; name=\"field2\"; "
  10660. "filename=\"example.txt\"\r\n"
  10661. "\r\n"
  10662. "value2\r\n"
  10663. "--simple boundary--\r\n"
  10664. "This is the epilogue. It is also to be ignored.\r\n";
  10665. std::string content_type =
  10666. R"(multipart/form-data; boundary="simple boundary")";
  10667. Client cli(HOST, PORT);
  10668. auto res = cli.Post("/post", body, content_type.c_str());
  10669. ASSERT_TRUE(res);
  10670. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10671. }
  10672. TEST(MultipartFormDataTest, WithPreamble) {
  10673. Server svr;
  10674. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10675. res.set_content("ok", "text/plain");
  10676. });
  10677. thread t = thread([&] { svr.listen(HOST, PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. t.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. const std::string body =
  10685. "This is the preamble. It is to be ignored, though it\r\n"
  10686. "is a handy place for composition agents to include an\r\n"
  10687. "explanatory note to non-MIME conformant readers.\r\n"
  10688. "\r\n"
  10689. "\r\n"
  10690. "--simple boundary\r\n"
  10691. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10692. "\r\n"
  10693. "value1\r\n"
  10694. "--simple boundary\r\n"
  10695. "Content-Disposition: form-data; name=\"field2\"; "
  10696. "filename=\"example.txt\"\r\n"
  10697. "\r\n"
  10698. "value2\r\n"
  10699. "--simple boundary--\r\n"
  10700. "This is the epilogue. It is also to be ignored.\r\n";
  10701. std::string content_type =
  10702. R"(multipart/form-data; boundary="simple boundary")";
  10703. Client cli(HOST, PORT);
  10704. auto res = cli.Post("/post", body, content_type.c_str());
  10705. ASSERT_TRUE(res);
  10706. EXPECT_EQ(StatusCode::OK_200, res->status);
  10707. }
  10708. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10710. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10711. const ContentReader &content_reader) {
  10712. if (req.is_multipart_form_data()) {
  10713. std::vector<FormData> items;
  10714. content_reader(
  10715. [&](const FormData &file) {
  10716. items.push_back(file);
  10717. return true;
  10718. },
  10719. [&](const char *data, size_t data_length) {
  10720. items.back().content.append(data, data_length);
  10721. return true;
  10722. });
  10723. EXPECT_TRUE(std::string(items[0].name) == "document");
  10724. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10725. EXPECT_TRUE(items[0].filename == "2MB_data");
  10726. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10727. EXPECT_TRUE(items[1].name == "hello");
  10728. EXPECT_TRUE(items[1].content == "world");
  10729. EXPECT_TRUE(items[1].filename == "");
  10730. EXPECT_TRUE(items[1].content_type == "");
  10731. } else {
  10732. std::string body;
  10733. content_reader([&](const char *data, size_t data_length) {
  10734. body.append(data, data_length);
  10735. return true;
  10736. });
  10737. }
  10738. });
  10739. auto port = svr.bind_to_any_port("localhost");
  10740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10741. auto se = detail::scope_exit([&] {
  10742. svr.stop();
  10743. t.join();
  10744. ASSERT_FALSE(svr.is_running());
  10745. });
  10746. svr.wait_until_ready();
  10747. {
  10748. std::string data(1024 * 1024 * 2, '.');
  10749. std::stringstream buffer;
  10750. buffer << data;
  10751. SSLClient cli("localhost", port);
  10752. cli.enable_server_certificate_verification(false);
  10753. UploadFormDataItems items{
  10754. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10755. {"hello", "world", "", ""},
  10756. };
  10757. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10758. ASSERT_TRUE(res);
  10759. ASSERT_EQ(StatusCode::OK_200, res->status);
  10760. }
  10761. }
  10762. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10763. std::string data(1024 * 1024 * 2, '&');
  10764. std::stringstream buffer;
  10765. buffer << data;
  10766. Client cli("https://localhost:8080");
  10767. UploadFormDataItems items{
  10768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10769. {"hello", "world", "", ""},
  10770. };
  10771. for (const char &c : " \t\r\n") {
  10772. auto res =
  10773. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10774. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10775. ASSERT_FALSE(res);
  10776. }
  10777. }
  10778. TEST(MultipartFormDataTest, PutFormData) {
  10779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10780. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10781. const ContentReader &content_reader) {
  10782. if (req.is_multipart_form_data()) {
  10783. std::vector<FormData> items;
  10784. content_reader(
  10785. [&](const FormData &file) {
  10786. items.push_back(file);
  10787. return true;
  10788. },
  10789. [&](const char *data, size_t data_length) {
  10790. items.back().content.append(data, data_length);
  10791. return true;
  10792. });
  10793. EXPECT_TRUE(std::string(items[0].name) == "document");
  10794. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10795. EXPECT_TRUE(items[0].filename == "2MB_data");
  10796. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10797. EXPECT_TRUE(items[1].name == "hello");
  10798. EXPECT_TRUE(items[1].content == "world");
  10799. EXPECT_TRUE(items[1].filename == "");
  10800. EXPECT_TRUE(items[1].content_type == "");
  10801. } else {
  10802. std::string body;
  10803. content_reader([&](const char *data, size_t data_length) {
  10804. body.append(data, data_length);
  10805. return true;
  10806. });
  10807. }
  10808. });
  10809. auto port = svr.bind_to_any_port("localhost");
  10810. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. t.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. {
  10818. std::string data(1024 * 1024 * 2, '&');
  10819. std::stringstream buffer;
  10820. buffer << data;
  10821. SSLClient cli("localhost", port);
  10822. cli.enable_server_certificate_verification(false);
  10823. UploadFormDataItems items{
  10824. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10825. {"hello", "world", "", ""},
  10826. };
  10827. auto res = cli.Put("/put", items);
  10828. ASSERT_TRUE(res);
  10829. ASSERT_EQ(StatusCode::OK_200, res->status);
  10830. }
  10831. }
  10832. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10834. svr.Put("/put_customboundary",
  10835. [&](const Request &req, const Response & /*res*/,
  10836. const ContentReader &content_reader) {
  10837. if (req.is_multipart_form_data()) {
  10838. std::vector<FormData> items;
  10839. content_reader(
  10840. [&](const FormData &file) {
  10841. items.push_back(file);
  10842. return true;
  10843. },
  10844. [&](const char *data, size_t data_length) {
  10845. items.back().content.append(data, data_length);
  10846. return true;
  10847. });
  10848. EXPECT_TRUE(std::string(items[0].name) == "document");
  10849. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10850. EXPECT_TRUE(items[0].filename == "2MB_data");
  10851. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10852. EXPECT_TRUE(items[1].name == "hello");
  10853. EXPECT_TRUE(items[1].content == "world");
  10854. EXPECT_TRUE(items[1].filename == "");
  10855. EXPECT_TRUE(items[1].content_type == "");
  10856. } else {
  10857. std::string body;
  10858. content_reader([&](const char *data, size_t data_length) {
  10859. body.append(data, data_length);
  10860. return true;
  10861. });
  10862. }
  10863. });
  10864. auto port = svr.bind_to_any_port("localhost");
  10865. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10866. auto se = detail::scope_exit([&] {
  10867. svr.stop();
  10868. t.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. {
  10873. std::string data(1024 * 1024 * 2, '&');
  10874. std::stringstream buffer;
  10875. buffer << data;
  10876. SSLClient cli("localhost", port);
  10877. cli.enable_server_certificate_verification(false);
  10878. UploadFormDataItems items{
  10879. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10880. {"hello", "world", "", ""},
  10881. };
  10882. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10883. ASSERT_TRUE(res);
  10884. ASSERT_EQ(StatusCode::OK_200, res->status);
  10885. }
  10886. }
  10887. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10888. std::string data(1024 * 1024 * 2, '&');
  10889. std::stringstream buffer;
  10890. buffer << data;
  10891. Client cli("https://localhost:8080");
  10892. cli.enable_server_certificate_verification(false);
  10893. UploadFormDataItems items{
  10894. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10895. {"hello", "world", "", ""},
  10896. };
  10897. for (const char &c : " \t\r\n") {
  10898. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10899. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10900. ASSERT_FALSE(res);
  10901. }
  10902. }
  10903. TEST(MultipartFormDataTest, AlternateFilename) {
  10904. auto handled = false;
  10905. Server svr;
  10906. svr.Post("/test", [&](const Request &req, Response &res) {
  10907. ASSERT_EQ(2u, req.form.files.size());
  10908. ASSERT_EQ(1u, req.form.fields.size());
  10909. // Test files
  10910. const auto &file1 = req.form.get_file("file1");
  10911. ASSERT_EQ("file1", file1.name);
  10912. ASSERT_EQ("A.txt", file1.filename);
  10913. ASSERT_EQ("text/plain", file1.content_type);
  10914. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10915. const auto &file2 = req.form.get_file("file2");
  10916. ASSERT_EQ("file2", file2.name);
  10917. ASSERT_EQ("a.html", file2.filename);
  10918. ASSERT_EQ("text/html", file2.content_type);
  10919. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10920. file2.content);
  10921. // Test text field
  10922. const auto &text = req.form.get_field("text");
  10923. ASSERT_EQ("text default", text);
  10924. res.set_content("ok", "text/plain");
  10925. handled = true;
  10926. });
  10927. thread t = thread([&] { svr.listen(HOST, PORT); });
  10928. auto se = detail::scope_exit([&] {
  10929. svr.stop();
  10930. t.join();
  10931. ASSERT_FALSE(svr.is_running());
  10932. ASSERT_TRUE(handled);
  10933. });
  10934. svr.wait_until_ready();
  10935. auto req = "POST /test HTTP/1.1\r\n"
  10936. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10937. "Content-Length: 399\r\n"
  10938. "\r\n"
  10939. "----------\r\n"
  10940. "Content-Disposition: form-data; name=\"text\"\r\n"
  10941. "\r\n"
  10942. "text default\r\n"
  10943. "----------\r\n"
  10944. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10945. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10946. "Content-Type: text/plain\r\n"
  10947. "\r\n"
  10948. "Content of a.txt.\r\n"
  10949. "\r\n"
  10950. "----------\r\n"
  10951. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10952. "\"a.html\"\r\n"
  10953. "Content-Type: text/html\r\n"
  10954. "\r\n"
  10955. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10956. "\r\n"
  10957. "------------\r\n";
  10958. ASSERT_TRUE(send_request(1, req));
  10959. }
  10960. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10961. auto handled = false;
  10962. Server svr;
  10963. svr.Post("/test", [&](const Request &req, Response &res) {
  10964. // Case-insensitive "utf-8''" prefix with a long value
  10965. const auto &file = req.form.get_file("file1");
  10966. ASSERT_EQ("file1", file.name);
  10967. // 8000 chars exercises both the Content-Disposition parser and the
  10968. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10969. // Prior to the fix, std::regex_match on this header would cause O(N)
  10970. // stack recursion in libstdc++, leading to SIGSEGV.
  10971. std::string expected_filename(8000, 'A');
  10972. ASSERT_EQ(expected_filename, file.filename);
  10973. res.set_content("ok", "text/plain");
  10974. handled = true;
  10975. });
  10976. thread t = thread([&] { svr.listen(HOST, PORT); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. ASSERT_FALSE(svr.is_running());
  10981. ASSERT_TRUE(handled);
  10982. });
  10983. svr.wait_until_ready();
  10984. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10985. // Regression test for GHSA-qq6v-r583-3h69
  10986. std::string long_filename(8000, 'A');
  10987. std::string body = "----------\r\n"
  10988. "Content-Disposition: form-data; name=\"file1\"; "
  10989. "filename*=\"Utf-8''" +
  10990. long_filename +
  10991. "\"\r\n"
  10992. "\r\n"
  10993. "hello\r\n"
  10994. "------------\r\n";
  10995. auto req = "POST /test HTTP/1.1\r\n"
  10996. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10997. "Content-Length: " +
  10998. std::to_string(body.size()) + "\r\n\r\n" + body;
  10999. ASSERT_TRUE(send_request(1, req));
  11000. }
  11001. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11002. auto handled = false;
  11003. Server svr;
  11004. svr.Post("/test", [&](const Request &req, Response &) {
  11005. ASSERT_EQ(2u, req.form.fields.size());
  11006. const auto &text1 = req.form.get_field("text1");
  11007. ASSERT_EQ("text1", text1);
  11008. const auto &text2 = req.form.get_field("text2");
  11009. ASSERT_EQ("text2", text2);
  11010. handled = true;
  11011. });
  11012. thread t = thread([&] { svr.listen(HOST, PORT); });
  11013. auto se = detail::scope_exit([&] {
  11014. svr.stop();
  11015. t.join();
  11016. ASSERT_FALSE(svr.is_running());
  11017. ASSERT_TRUE(handled);
  11018. });
  11019. svr.wait_until_ready();
  11020. auto req = "POST /test HTTP/1.1\r\n"
  11021. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11022. "Content-Length: 146\r\n"
  11023. "\r\n----------\r\n"
  11024. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11025. "\r\n"
  11026. "text1"
  11027. "\r\n----------\r\n"
  11028. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11029. "\r\n"
  11030. "text2"
  11031. "\r\n------------";
  11032. std::string response;
  11033. ASSERT_TRUE(send_request(1, req, &response));
  11034. ASSERT_EQ("200", response.substr(9, 3));
  11035. }
  11036. TEST(MultipartFormDataTest, ContentLength) {
  11037. auto handled = false;
  11038. Server svr;
  11039. svr.Post("/test", [&](const Request &req, Response &) {
  11040. ASSERT_EQ(2u, req.form.fields.size());
  11041. const auto &text1 = req.form.get_field("text1");
  11042. ASSERT_EQ("text1", text1);
  11043. const auto &text2 = req.form.get_field("text2");
  11044. ASSERT_EQ("text2", text2);
  11045. handled = true;
  11046. });
  11047. thread t = thread([&] { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. ASSERT_TRUE(handled);
  11053. });
  11054. svr.wait_until_ready();
  11055. auto req = "POST /test HTTP/1.1\r\n"
  11056. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11057. "Content-Length: 167\r\n"
  11058. "\r\n----------\r\n"
  11059. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11060. "Content-Length: 5\r\n"
  11061. "\r\n"
  11062. "text1"
  11063. "\r\n----------\r\n"
  11064. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11065. "\r\n"
  11066. "text2"
  11067. "\r\n------------\r\n";
  11068. std::string response;
  11069. ASSERT_TRUE(send_request(1, req, &response));
  11070. ASSERT_EQ("200", response.substr(9, 3));
  11071. }
  11072. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11073. auto handled = false;
  11074. Server svr;
  11075. svr.Post("/test", [&](const Request &req, Response &) {
  11076. ASSERT_EQ(2u, req.form.fields.size());
  11077. const auto &text1 = req.form.get_field("text1");
  11078. ASSERT_EQ("text1", text1);
  11079. // TODO: Add header access for text fields if needed
  11080. const auto &text2 = req.form.get_field("text2");
  11081. ASSERT_EQ("text2", text2);
  11082. // TODO: Header access for text fields needs to be implemented
  11083. // auto &headers = it->second.headers;
  11084. // ASSERT_EQ(3U, headers.size());
  11085. // auto custom_header = headers.find("x-whatever");
  11086. // ASSERT_TRUE(custom_header != headers.end());
  11087. // ASSERT_NE("customvalue", custom_header->second);
  11088. // ASSERT_EQ("CustomValue", custom_header->second);
  11089. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11090. handled = true;
  11091. });
  11092. thread t = thread([&] { svr.listen(HOST, PORT); });
  11093. auto se = detail::scope_exit([&] {
  11094. svr.stop();
  11095. t.join();
  11096. ASSERT_FALSE(svr.is_running());
  11097. ASSERT_TRUE(handled);
  11098. });
  11099. svr.wait_until_ready();
  11100. auto req = "POST /test HTTP/1.1\r\n"
  11101. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11102. "Content-Length: 232\r\n"
  11103. "\r\n----------\r\n"
  11104. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11105. "Content-Length: 5\r\n"
  11106. "X-Test: 1\r\n"
  11107. "\r\n"
  11108. "text1"
  11109. "\r\n----------\r\n"
  11110. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11111. "Content-Type: text/plain\r\n"
  11112. "X-Whatever: CustomValue\r\n"
  11113. "\r\n"
  11114. "text2"
  11115. "\r\n------------\r\n"
  11116. "That should be disregarded. Not even read";
  11117. std::string response;
  11118. ASSERT_TRUE(send_request(1, req, &response));
  11119. ASSERT_EQ("200", response.substr(9, 3));
  11120. }
  11121. TEST(MultipartFormDataTest, LargeHeader) {
  11122. auto handled = false;
  11123. Server svr;
  11124. svr.Post("/test", [&](const Request &req, Response &) {
  11125. ASSERT_EQ(1u, req.form.fields.size());
  11126. const auto &text = req.form.get_field("name1");
  11127. ASSERT_EQ("text1", text);
  11128. handled = true;
  11129. });
  11130. thread t = thread([&] { svr.listen(HOST, PORT); });
  11131. auto se = detail::scope_exit([&] {
  11132. svr.stop();
  11133. t.join();
  11134. ASSERT_FALSE(svr.is_running());
  11135. ASSERT_TRUE(handled);
  11136. });
  11137. svr.wait_until_ready();
  11138. auto boundary = std::string("cpp-httplib-multipart-data");
  11139. std::string content = "--" + boundary +
  11140. "\r\n"
  11141. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11142. "\r\n"
  11143. "text1\r\n"
  11144. "--" +
  11145. boundary + "--\r\n";
  11146. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11147. "Content-Type: multipart/form-data;boundary=" +
  11148. boundary +
  11149. "\r\n"
  11150. "Content-Length: " +
  11151. std::to_string(content.size()) +
  11152. "\r\n"
  11153. "Dummy-Header: ";
  11154. std::string header_suffix = "\r\n"
  11155. "\r\n";
  11156. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11157. size_t header_dummy_size =
  11158. read_buff_size -
  11159. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11160. auto header_dummy = std::string(header_dummy_size, '@');
  11161. auto req = header_prefix + header_dummy + header_suffix + content;
  11162. std::string response;
  11163. ASSERT_TRUE(send_request(1, req, &response));
  11164. ASSERT_EQ("200", response.substr(9, 3));
  11165. }
  11166. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11167. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11168. // (not chunked Transfer-Encoding) after the streaming refactor.
  11169. auto handled = false;
  11170. Server svr;
  11171. svr.Post("/upload", [&](const Request &req, Response &res) {
  11172. auto cl_it = req.headers.find("Content-Length");
  11173. EXPECT_TRUE(cl_it != req.headers.end());
  11174. auto te_it = req.headers.find("Transfer-Encoding");
  11175. EXPECT_TRUE(te_it == req.headers.end());
  11176. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11177. res.set_content("ok", "text/plain");
  11178. handled = true;
  11179. });
  11180. auto port = svr.bind_to_any_port(HOST);
  11181. auto t = thread([&] { svr.listen_after_bind(); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. t.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. ASSERT_TRUE(handled);
  11187. });
  11188. svr.wait_until_ready();
  11189. UploadFormDataItems items = {
  11190. {"field1", "hello", "", "text/plain"},
  11191. {"file1", "world", "test.txt", "application/octet-stream"},
  11192. };
  11193. Client cli(HOST, port);
  11194. auto res = cli.Post("/upload", {}, items);
  11195. ASSERT_TRUE(res);
  11196. EXPECT_EQ(StatusCode::OK_200, res->status);
  11197. }
  11198. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11199. // Verify that make_multipart_content_provider coalesces many small segments
  11200. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11201. constexpr size_t kItemCount = 1000;
  11202. UploadFormDataItems items;
  11203. items.reserve(kItemCount);
  11204. for (size_t i = 0; i < kItemCount; i++) {
  11205. items.push_back(
  11206. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11207. }
  11208. const std::string boundary = "----test-boundary";
  11209. auto content_length = detail::get_multipart_content_length(items, boundary);
  11210. auto provider = detail::make_multipart_content_provider(items, boundary);
  11211. // Drive the provider the same way write_content_with_progress does
  11212. size_t write_count = 0;
  11213. size_t total_bytes = 0;
  11214. DataSink sink;
  11215. size_t offset = 0;
  11216. sink.write = [&](const char *d, size_t l) -> bool {
  11217. (void)d;
  11218. write_count++;
  11219. total_bytes += l;
  11220. offset += l;
  11221. return true;
  11222. };
  11223. sink.is_writable = []() -> bool { return true; };
  11224. while (offset < content_length) {
  11225. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11226. }
  11227. EXPECT_EQ(content_length, total_bytes);
  11228. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11229. // With buffering into 64KB blocks, write_count should be much smaller.
  11230. auto segment_count = 3 * kItemCount + 1;
  11231. EXPECT_LT(write_count, segment_count / 10);
  11232. }
  11233. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11234. // Integration test: send many UploadFormDataItems and verify the server
  11235. // receives all of them correctly (#2410).
  11236. constexpr size_t kItemCount = 500;
  11237. auto handled = false;
  11238. Server svr;
  11239. svr.Post("/upload", [&](const Request &req, Response &res) {
  11240. EXPECT_EQ(kItemCount, req.form.fields.size());
  11241. for (size_t i = 0; i < kItemCount; i++) {
  11242. auto key = "field" + std::to_string(i);
  11243. auto val = "value" + std::to_string(i);
  11244. auto it = req.form.fields.find(key);
  11245. if (it != req.form.fields.end()) {
  11246. EXPECT_EQ(val, it->second.content);
  11247. } else {
  11248. ADD_FAILURE() << "Missing field: " << key;
  11249. }
  11250. }
  11251. res.set_content("ok", "text/plain");
  11252. handled = true;
  11253. });
  11254. auto port = svr.bind_to_any_port(HOST);
  11255. auto t = thread([&] { svr.listen_after_bind(); });
  11256. auto se = detail::scope_exit([&] {
  11257. svr.stop();
  11258. t.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. ASSERT_TRUE(handled);
  11261. });
  11262. svr.wait_until_ready();
  11263. UploadFormDataItems items;
  11264. items.reserve(kItemCount);
  11265. for (size_t i = 0; i < kItemCount; i++) {
  11266. items.push_back(
  11267. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11268. }
  11269. Client cli(HOST, port);
  11270. auto res = cli.Post("/upload", items);
  11271. ASSERT_TRUE(res);
  11272. EXPECT_EQ(StatusCode::OK_200, res->status);
  11273. }
  11274. TEST(MultipartFormDataTest, MakeFileProvider) {
  11275. // Verify make_file_provider sends a file's contents correctly.
  11276. const std::string file_content(4096, 'Z');
  11277. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11278. {
  11279. std::ofstream ofs(tmp_path, std::ios::binary);
  11280. ofs.write(file_content.data(),
  11281. static_cast<std::streamsize>(file_content.size()));
  11282. }
  11283. auto handled = false;
  11284. Server svr;
  11285. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11286. const ContentReader &content_reader) {
  11287. ASSERT_TRUE(req.is_multipart_form_data());
  11288. std::vector<FormData> items;
  11289. content_reader(
  11290. [&](const FormData &file) {
  11291. items.push_back(file);
  11292. return true;
  11293. },
  11294. [&](const char *data, size_t data_length) {
  11295. items.back().content.append(data, data_length);
  11296. return true;
  11297. });
  11298. ASSERT_EQ(1u, items.size());
  11299. EXPECT_EQ("myfile", items[0].name);
  11300. EXPECT_EQ("data.bin", items[0].filename);
  11301. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11302. EXPECT_EQ(file_content, items[0].content);
  11303. handled = true;
  11304. });
  11305. auto port = svr.bind_to_any_port(HOST);
  11306. auto t = thread([&] { svr.listen_after_bind(); });
  11307. auto se = detail::scope_exit([&] {
  11308. svr.stop();
  11309. t.join();
  11310. ASSERT_FALSE(svr.is_running());
  11311. ASSERT_TRUE(handled);
  11312. std::remove(tmp_path.c_str());
  11313. });
  11314. svr.wait_until_ready();
  11315. FormDataProviderItems providers;
  11316. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11317. "application/octet-stream"));
  11318. Client cli(HOST, port);
  11319. auto res = cli.Post("/upload", {}, {}, providers);
  11320. ASSERT_TRUE(res);
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. }
  11323. TEST(MakeFileBodyTest, Basic) {
  11324. const std::string file_content(4096, 'Z');
  11325. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11326. {
  11327. std::ofstream ofs(tmp_path, std::ios::binary);
  11328. ofs.write(file_content.data(),
  11329. static_cast<std::streamsize>(file_content.size()));
  11330. }
  11331. auto handled = false;
  11332. Server svr;
  11333. svr.Post("/upload", [&](const Request &req, Response &res) {
  11334. EXPECT_EQ(file_content, req.body);
  11335. handled = true;
  11336. res.status = StatusCode::OK_200;
  11337. });
  11338. auto port = svr.bind_to_any_port(HOST);
  11339. auto t = thread([&] { svr.listen_after_bind(); });
  11340. auto se = detail::scope_exit([&] {
  11341. svr.stop();
  11342. t.join();
  11343. ASSERT_FALSE(svr.is_running());
  11344. ASSERT_TRUE(handled);
  11345. std::remove(tmp_path.c_str());
  11346. });
  11347. svr.wait_until_ready();
  11348. auto fb = make_file_body(tmp_path);
  11349. ASSERT_GT(fb.first, 0u);
  11350. Client cli(HOST, port);
  11351. auto res =
  11352. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11353. ASSERT_TRUE(res);
  11354. EXPECT_EQ(StatusCode::OK_200, res->status);
  11355. }
  11356. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11357. static constexpr unsigned int number_of_tasks{1000000};
  11358. std::atomic_uint count{0};
  11359. std::unique_ptr<TaskQueue> task_queue{
  11360. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11361. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11362. auto queued = task_queue->enqueue(
  11363. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11364. EXPECT_TRUE(queued);
  11365. }
  11366. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11367. task_queue->shutdown();
  11368. #else
  11369. EXPECT_NO_THROW(task_queue->shutdown());
  11370. #endif
  11371. EXPECT_EQ(number_of_tasks, count.load());
  11372. }
  11373. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11374. static constexpr unsigned int number_of_tasks{1000000};
  11375. static constexpr unsigned int qlimit{2};
  11376. unsigned int queued_count{0};
  11377. std::atomic_uint count{0};
  11378. std::unique_ptr<TaskQueue> task_queue{
  11379. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11380. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11381. if (task_queue->enqueue(
  11382. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11383. queued_count++;
  11384. }
  11385. }
  11386. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11387. task_queue->shutdown();
  11388. #else
  11389. EXPECT_NO_THROW(task_queue->shutdown());
  11390. #endif
  11391. EXPECT_EQ(queued_count, count.load());
  11392. EXPECT_TRUE(queued_count <= number_of_tasks);
  11393. EXPECT_TRUE(queued_count >= qlimit);
  11394. }
  11395. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11396. // Use a short idle timeout so a dynamic thread spawns, times out and
  11397. // exits during the test, and the pool keeps working afterwards.
  11398. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11399. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11400. /*idle_timeout_sec=*/1}};
  11401. std::atomic_uint count{0};
  11402. std::condition_variable cv;
  11403. std::mutex mtx;
  11404. bool release = false;
  11405. // Block the base thread so the second task spawns a dynamic thread.
  11406. EXPECT_TRUE(task_queue->enqueue([&] {
  11407. std::unique_lock<std::mutex> lock(mtx);
  11408. while (!release) {
  11409. cv.wait(lock);
  11410. }
  11411. count++;
  11412. }));
  11413. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11414. // Let the dynamic thread finish its task and exceed the idle timeout.
  11415. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11416. {
  11417. std::unique_lock<std::mutex> lock(mtx);
  11418. release = true;
  11419. }
  11420. cv.notify_all();
  11421. // The pool must still accept and run tasks after the dynamic thread exited.
  11422. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11423. task_queue->shutdown();
  11424. EXPECT_EQ(3u, count.load());
  11425. }
  11426. TEST(TaskQueueTest, MaxQueuedRequests) {
  11427. static constexpr unsigned int qlimit{3};
  11428. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11429. std::condition_variable sem_cv;
  11430. std::mutex sem_mtx;
  11431. int credits = 0;
  11432. bool queued;
  11433. /* Fill up the queue with tasks that will block until we give them credits to
  11434. * complete. */
  11435. for (unsigned int n = 0; n <= qlimit;) {
  11436. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11437. std::unique_lock<std::mutex> lock(sem_mtx);
  11438. while (credits <= 0) {
  11439. sem_cv.wait(lock);
  11440. }
  11441. /* Consume the credit and signal the test code if they are all gone. */
  11442. if (--credits == 0) { sem_cv.notify_one(); }
  11443. });
  11444. if (n < qlimit) {
  11445. /* The first qlimit enqueues must succeed. */
  11446. EXPECT_TRUE(queued);
  11447. } else {
  11448. /* The last one will succeed only when the worker thread
  11449. * starts and dequeues the first blocking task. Although
  11450. * not necessary for the correctness of this test, we sleep for
  11451. * a short while to avoid busy waiting. */
  11452. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11453. }
  11454. if (queued) { n++; }
  11455. }
  11456. /* Further enqueues must fail since the queue is full. */
  11457. for (auto i = 0; i < 4; i++) {
  11458. queued = task_queue->enqueue([] {});
  11459. EXPECT_FALSE(queued);
  11460. }
  11461. /* Give the credits to allow the previous tasks to complete. */
  11462. {
  11463. std::unique_lock<std::mutex> lock(sem_mtx);
  11464. credits += qlimit + 1;
  11465. }
  11466. sem_cv.notify_all();
  11467. /* Wait for all the credits to be consumed. */
  11468. {
  11469. std::unique_lock<std::mutex> lock(sem_mtx);
  11470. while (credits > 0) {
  11471. sem_cv.wait(lock);
  11472. }
  11473. }
  11474. /* Check that we are able again to enqueue at least qlimit tasks. */
  11475. for (unsigned int i = 0; i < qlimit; i++) {
  11476. queued = task_queue->enqueue([] {});
  11477. EXPECT_TRUE(queued);
  11478. }
  11479. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11480. task_queue->shutdown();
  11481. #else
  11482. EXPECT_NO_THROW(task_queue->shutdown());
  11483. #endif
  11484. }
  11485. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11486. Server svr;
  11487. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11488. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11489. });
  11490. svr.Get("/hello", [](const Request &req, Response &res) {
  11491. res.set_content(req.get_param_value("key"), "text/plain");
  11492. });
  11493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11494. auto se = detail::scope_exit([&] {
  11495. svr.stop();
  11496. thread.join();
  11497. ASSERT_FALSE(svr.is_running());
  11498. });
  11499. svr.wait_until_ready();
  11500. {
  11501. Client cli(HOST, PORT);
  11502. cli.set_follow_location(true);
  11503. auto res = cli.Get("/");
  11504. ASSERT_TRUE(res);
  11505. EXPECT_EQ(StatusCode::OK_200, res->status);
  11506. EXPECT_EQ("val&key2=val2", res->body);
  11507. }
  11508. }
  11509. #endif
  11510. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11511. Server svr;
  11512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11513. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11514. });
  11515. svr.Get("/hello", [](const Request &req, Response &res) {
  11516. res.set_content(req.get_param_value("key"), "text/plain");
  11517. });
  11518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11519. auto se = detail::scope_exit([&] {
  11520. svr.stop();
  11521. thread.join();
  11522. ASSERT_FALSE(svr.is_running());
  11523. });
  11524. svr.wait_until_ready();
  11525. {
  11526. Client cli(HOST, PORT);
  11527. cli.set_follow_location(true);
  11528. auto res = cli.Get("/");
  11529. ASSERT_TRUE(res);
  11530. EXPECT_EQ(StatusCode::OK_200, res->status);
  11531. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11532. }
  11533. }
  11534. TEST(RedirectTest, RedirectWithPlusInPath) {
  11535. Server svr;
  11536. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11537. res.set_redirect("/a+b");
  11538. });
  11539. // Route pattern uses regex; escape + as \\+
  11540. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11541. res.set_content(req.path, "text/plain");
  11542. });
  11543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. {
  11551. Client cli(HOST, PORT);
  11552. cli.set_follow_location(true);
  11553. auto res = cli.Get("/");
  11554. ASSERT_TRUE(res);
  11555. EXPECT_EQ(StatusCode::OK_200, res->status);
  11556. EXPECT_EQ("/a+b", res->body);
  11557. }
  11558. }
  11559. #ifdef CPPHTTPLIB_SSL_ENABLED
  11560. TEST(RedirectTest, Issue2185_Online) {
  11561. SSLClient client("github.com");
  11562. client.set_follow_location(true);
  11563. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11564. "Coollab-Windows.zip");
  11565. ASSERT_TRUE(res);
  11566. EXPECT_EQ(StatusCode::OK_200, res->status);
  11567. EXPECT_EQ(9920427U, res->body.size());
  11568. }
  11569. #endif
  11570. TEST(VulnerabilityTest, CRLFInjection) {
  11571. Server svr;
  11572. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11573. res.set_content("Hello 1", "text/plain");
  11574. });
  11575. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11576. res.set_content("Hello 2", "text/plain");
  11577. });
  11578. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11579. res.set_content("Hello 3", "text/plain");
  11580. });
  11581. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11582. res.set_content("Hello 4", "text/plain");
  11583. });
  11584. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11585. for (const auto &x : req.headers) {
  11586. auto key = x.first;
  11587. EXPECT_STRNE("evil", key.c_str());
  11588. }
  11589. });
  11590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11591. auto se = detail::scope_exit([&] {
  11592. svr.stop();
  11593. thread.join();
  11594. ASSERT_FALSE(svr.is_running());
  11595. });
  11596. svr.wait_until_ready();
  11597. {
  11598. Client cli(HOST, PORT);
  11599. cli.Post("/test1", "A=B",
  11600. "application/x-www-form-urlencoded\r\nevil: hello1");
  11601. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11602. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11603. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11604. }
  11605. }
  11606. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11607. auto server_thread = std::thread([] {
  11608. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11609. default_socket_options(srv);
  11610. sockaddr_in addr{};
  11611. addr.sin_family = AF_INET;
  11612. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11614. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11615. ::listen(srv, 1);
  11616. sockaddr_in cli_addr{};
  11617. socklen_t cli_len = sizeof(cli_addr);
  11618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11619. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11620. std::string buf_all;
  11621. char buf[2048];
  11622. ssize_t n;
  11623. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11624. buf_all.append(buf, static_cast<size_t>(n));
  11625. size_t pos;
  11626. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11627. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11628. auto e = request_block.find("\r\n");
  11629. if (e != std::string::npos) {
  11630. auto request_line = request_block.substr(0, e);
  11631. std::string msg =
  11632. "CRLF injection detected in request line: '" + request_line + "'";
  11633. EXPECT_FALSE(true) << msg;
  11634. }
  11635. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11636. ::send(cli,
  11637. #ifdef _WIN32
  11638. static_cast<const char *>(resp.c_str()),
  11639. static_cast<int>(resp.size()),
  11640. #else
  11641. resp.c_str(), resp.size(),
  11642. #endif
  11643. 0);
  11644. buf_all.erase(0, pos + 4);
  11645. }
  11646. }
  11647. detail::close_socket(cli);
  11648. detail::close_socket(srv);
  11649. });
  11650. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11651. auto cli = Client("127.0.0.1", PORT + 1);
  11652. auto headers = Headers{
  11653. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11654. {"Connection", "keep-alive"}};
  11655. auto res = cli.Get("/hi", headers);
  11656. EXPECT_FALSE(res);
  11657. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11658. server_thread.join();
  11659. }
  11660. TEST(PathParamsTest, StaticMatch) {
  11661. const auto pattern = "/users/all";
  11662. detail::PathParamsMatcher matcher(pattern);
  11663. Request request;
  11664. request.path = "/users/all";
  11665. ASSERT_TRUE(matcher.match(request));
  11666. std::unordered_map<std::string, std::string> expected_params = {};
  11667. EXPECT_EQ(request.path_params, expected_params);
  11668. }
  11669. TEST(PathParamsTest, StaticMismatch) {
  11670. const auto pattern = "/users/all";
  11671. detail::PathParamsMatcher matcher(pattern);
  11672. Request request;
  11673. request.path = "/users/1";
  11674. ASSERT_FALSE(matcher.match(request));
  11675. }
  11676. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11677. const auto pattern = "/users/:id/subscriptions";
  11678. detail::PathParamsMatcher matcher(pattern);
  11679. Request request;
  11680. request.path = "/users/42/subscriptions";
  11681. ASSERT_TRUE(matcher.match(request));
  11682. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11683. EXPECT_EQ(request.path_params, expected_params);
  11684. }
  11685. TEST(PathParamsTest, SingleParamInTheEnd) {
  11686. const auto pattern = "/users/:id";
  11687. detail::PathParamsMatcher matcher(pattern);
  11688. Request request;
  11689. request.path = "/users/24";
  11690. ASSERT_TRUE(matcher.match(request));
  11691. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11692. EXPECT_EQ(request.path_params, expected_params);
  11693. }
  11694. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11695. const auto pattern = "/users/:id/";
  11696. detail::PathParamsMatcher matcher(pattern);
  11697. Request request;
  11698. request.path = "/users/42/";
  11699. ASSERT_TRUE(matcher.match(request));
  11700. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11701. EXPECT_EQ(request.path_params, expected_params);
  11702. }
  11703. TEST(PathParamsTest, EmptyParam) {
  11704. const auto pattern = "/users/:id/";
  11705. detail::PathParamsMatcher matcher(pattern);
  11706. Request request;
  11707. request.path = "/users//";
  11708. ASSERT_TRUE(matcher.match(request));
  11709. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11710. EXPECT_EQ(request.path_params, expected_params);
  11711. }
  11712. TEST(PathParamsTest, FragmentMismatch) {
  11713. const auto pattern = "/users/:id/";
  11714. detail::PathParamsMatcher matcher(pattern);
  11715. Request request;
  11716. request.path = "/admins/24/";
  11717. ASSERT_FALSE(matcher.match(request));
  11718. }
  11719. TEST(PathParamsTest, ExtraFragments) {
  11720. const auto pattern = "/users/:id";
  11721. detail::PathParamsMatcher matcher(pattern);
  11722. Request request;
  11723. request.path = "/users/42/subscriptions";
  11724. ASSERT_FALSE(matcher.match(request));
  11725. }
  11726. TEST(PathParamsTest, MissingTrailingParam) {
  11727. const auto pattern = "/users/:id";
  11728. detail::PathParamsMatcher matcher(pattern);
  11729. Request request;
  11730. request.path = "/users";
  11731. ASSERT_FALSE(matcher.match(request));
  11732. }
  11733. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11734. const auto pattern = "/users/:id/subscriptions";
  11735. detail::PathParamsMatcher matcher(pattern);
  11736. Request request;
  11737. request.path = "/users/subscriptions";
  11738. ASSERT_FALSE(matcher.match(request));
  11739. }
  11740. TEST(PathParamsTest, MultipleParams) {
  11741. const auto pattern = "/users/:userid/subscriptions/:subid";
  11742. detail::PathParamsMatcher matcher(pattern);
  11743. Request request;
  11744. request.path = "/users/42/subscriptions/2";
  11745. ASSERT_TRUE(matcher.match(request));
  11746. std::unordered_map<std::string, std::string> expected_params = {
  11747. {"userid", "42"}, {"subid", "2"}};
  11748. EXPECT_EQ(request.path_params, expected_params);
  11749. }
  11750. TEST(PathParamsTest, SequenceOfParams) {
  11751. const auto pattern = "/values/:x/:y/:z";
  11752. detail::PathParamsMatcher matcher(pattern);
  11753. Request request;
  11754. request.path = "/values/1/2/3";
  11755. ASSERT_TRUE(matcher.match(request));
  11756. std::unordered_map<std::string, std::string> expected_params = {
  11757. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11758. EXPECT_EQ(request.path_params, expected_params);
  11759. }
  11760. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11761. const auto pattern = "/prefix:suffix";
  11762. detail::PathParamsMatcher matcher(pattern);
  11763. Request request;
  11764. request.path = "/prefix:suffix";
  11765. ASSERT_TRUE(matcher.match(request));
  11766. const std::unordered_map<std::string, std::string> expected_params = {};
  11767. EXPECT_EQ(request.path_params, expected_params);
  11768. }
  11769. TEST(ParseUrlTest, VariousPatterns) {
  11770. {
  11771. detail::UrlComponents uc;
  11772. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11773. EXPECT_EQ("http", uc.scheme);
  11774. EXPECT_EQ("example.com", uc.host);
  11775. EXPECT_EQ("8080", uc.port);
  11776. EXPECT_EQ("/path", uc.path);
  11777. EXPECT_EQ("?q=1", uc.query);
  11778. }
  11779. {
  11780. detail::UrlComponents uc;
  11781. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11782. EXPECT_EQ("https", uc.scheme);
  11783. EXPECT_EQ("example.com", uc.host);
  11784. EXPECT_TRUE(uc.port.empty());
  11785. EXPECT_EQ("/path", uc.path);
  11786. }
  11787. {
  11788. detail::UrlComponents uc;
  11789. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11790. EXPECT_EQ("::1", uc.host);
  11791. EXPECT_EQ("8080", uc.port);
  11792. EXPECT_EQ("/path", uc.path);
  11793. }
  11794. {
  11795. detail::UrlComponents uc;
  11796. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11797. }
  11798. {
  11799. detail::UrlComponents uc;
  11800. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11801. EXPECT_TRUE(uc.scheme.empty());
  11802. EXPECT_EQ("example.com", uc.host);
  11803. EXPECT_EQ("/path", uc.path);
  11804. EXPECT_EQ("?q=1", uc.query);
  11805. }
  11806. {
  11807. detail::UrlComponents uc;
  11808. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11809. EXPECT_TRUE(uc.host.empty());
  11810. EXPECT_EQ("/path", uc.path);
  11811. EXPECT_EQ("?q=1", uc.query);
  11812. }
  11813. {
  11814. detail::UrlComponents uc;
  11815. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11816. EXPECT_EQ("example.com", uc.host);
  11817. EXPECT_EQ("8080", uc.port);
  11818. }
  11819. {
  11820. // Unix socket path — must not be parsed as host
  11821. detail::UrlComponents uc;
  11822. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11823. EXPECT_TRUE(uc.host.empty());
  11824. }
  11825. {
  11826. detail::UrlComponents uc;
  11827. ASSERT_TRUE(detail::parse_url("", uc));
  11828. EXPECT_TRUE(uc.host.empty());
  11829. EXPECT_TRUE(uc.path.empty());
  11830. }
  11831. {
  11832. detail::UrlComponents uc;
  11833. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11834. }
  11835. {
  11836. detail::UrlComponents uc;
  11837. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11838. }
  11839. {
  11840. // Accepted by parse_url; callers restrict to http/https
  11841. detail::UrlComponents uc;
  11842. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11843. EXPECT_EQ("ftp", uc.scheme);
  11844. }
  11845. {
  11846. detail::UrlComponents uc;
  11847. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11848. }
  11849. {
  11850. detail::UrlComponents uc;
  11851. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11852. }
  11853. }
  11854. TEST(ParseUrlTest, FragmentHandling) {
  11855. {
  11856. detail::UrlComponents uc;
  11857. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11858. EXPECT_EQ("/path", uc.path);
  11859. EXPECT_TRUE(uc.query.empty());
  11860. }
  11861. {
  11862. detail::UrlComponents uc;
  11863. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11864. EXPECT_TRUE(uc.path.empty());
  11865. EXPECT_TRUE(uc.query.empty());
  11866. }
  11867. }
  11868. TEST(ParseUrlTest, UserinfoHandling) {
  11869. // Userinfo with @ but no colon — host includes @
  11870. detail::UrlComponents uc;
  11871. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11872. EXPECT_EQ("user@host.com", uc.host);
  11873. EXPECT_EQ("/path", uc.path);
  11874. }
  11875. TEST(ParseUrlTest, IPv6EdgeCases) {
  11876. {
  11877. detail::UrlComponents uc;
  11878. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11879. EXPECT_TRUE(uc.scheme.empty());
  11880. EXPECT_EQ("::1", uc.host);
  11881. EXPECT_EQ("8080", uc.port);
  11882. }
  11883. {
  11884. // Zone ID '%25' is not in [a-fA-F0-9:]
  11885. detail::UrlComponents uc;
  11886. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11887. }
  11888. }
  11889. TEST(ParseUrlTest, SchemeEdgeCases) {
  11890. {
  11891. detail::UrlComponents uc;
  11892. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11893. }
  11894. {
  11895. detail::UrlComponents uc;
  11896. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11897. }
  11898. {
  11899. detail::UrlComponents uc;
  11900. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11901. }
  11902. }
  11903. TEST(ParseUrlTest, PortEdgeCases) {
  11904. {
  11905. detail::UrlComponents uc;
  11906. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11907. EXPECT_TRUE(uc.port.empty());
  11908. EXPECT_EQ("/path", uc.path);
  11909. }
  11910. {
  11911. // parse_url accepts any port string; validation is done by parse_port
  11912. detail::UrlComponents uc;
  11913. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11914. EXPECT_EQ("abc", uc.port);
  11915. }
  11916. }
  11917. TEST(ParseUrlTest, WebSocketPatterns) {
  11918. {
  11919. detail::UrlComponents uc;
  11920. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11921. EXPECT_EQ("ws", uc.scheme);
  11922. EXPECT_EQ("echo.example.com", uc.host);
  11923. EXPECT_EQ("8080", uc.port);
  11924. EXPECT_EQ("/ws", uc.path);
  11925. }
  11926. {
  11927. detail::UrlComponents uc;
  11928. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11929. EXPECT_EQ("wss", uc.scheme);
  11930. EXPECT_EQ("echo.example.com", uc.host);
  11931. EXPECT_TRUE(uc.port.empty());
  11932. EXPECT_EQ("/ws", uc.path);
  11933. }
  11934. }
  11935. TEST(ParseUrlTest, QueryOnly) {
  11936. detail::UrlComponents uc;
  11937. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11938. EXPECT_TRUE(uc.host.empty());
  11939. EXPECT_TRUE(uc.path.empty());
  11940. EXPECT_EQ("?q=1&r=2", uc.query);
  11941. }
  11942. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11943. detail::UrlComponents uc;
  11944. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11945. EXPECT_TRUE(uc.scheme.empty());
  11946. EXPECT_EQ("example.com", uc.host);
  11947. EXPECT_EQ("443", uc.port);
  11948. EXPECT_EQ("/path", uc.path);
  11949. }
  11950. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11951. // If ipv6 regex working, regex match codepath is taken.
  11952. // else port will default to 80 in Client impl
  11953. int clientImplMagicPort = 80;
  11954. int port = 4321;
  11955. // above ports must be different to avoid false negative
  11956. EXPECT_NE(clientImplMagicPort, port);
  11957. std::string ipV6TestURL = "http://[ff06::c3]";
  11958. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11959. CLIENT_PRIVATE_KEY_FILE);
  11960. EXPECT_EQ(cli.port(), port);
  11961. }
  11962. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11963. auto file_path = "./www/dir/index.html";
  11964. auto dir_path = "./www/dir";
  11965. detail::FileStat stat_file(file_path);
  11966. EXPECT_TRUE(stat_file.is_file());
  11967. EXPECT_FALSE(stat_file.is_dir());
  11968. detail::FileStat stat_dir(dir_path);
  11969. EXPECT_FALSE(stat_dir.is_file());
  11970. EXPECT_TRUE(stat_dir.is_dir());
  11971. }
  11972. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11973. // IPv4 with default HTTP port (80)
  11974. EXPECT_EQ("example.com",
  11975. detail::make_host_and_port_string("example.com", 80, false));
  11976. // IPv4 with default HTTPS port (443)
  11977. EXPECT_EQ("example.com",
  11978. detail::make_host_and_port_string("example.com", 443, true));
  11979. // IPv4 with non-default HTTP port
  11980. EXPECT_EQ("example.com:8080",
  11981. detail::make_host_and_port_string("example.com", 8080, false));
  11982. // IPv4 with non-default HTTPS port
  11983. EXPECT_EQ("example.com:8443",
  11984. detail::make_host_and_port_string("example.com", 8443, true));
  11985. // IPv6 with default HTTP port (80)
  11986. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11987. // IPv6 with default HTTPS port (443)
  11988. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11989. // IPv6 with non-default HTTP port
  11990. EXPECT_EQ("[::1]:8080",
  11991. detail::make_host_and_port_string("::1", 8080, false));
  11992. // IPv6 with non-default HTTPS port
  11993. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11994. // IPv6 full address with default port
  11995. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11996. detail::make_host_and_port_string(
  11997. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11998. // IPv6 full address with non-default port
  11999. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12000. detail::make_host_and_port_string(
  12001. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12002. // IPv6 localhost with non-default port
  12003. EXPECT_EQ("[::1]:3000",
  12004. detail::make_host_and_port_string("::1", 3000, false));
  12005. // IPv6 with zone ID (link-local address) with default port
  12006. EXPECT_EQ("[fe80::1%eth0]",
  12007. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12008. // IPv6 with zone ID (link-local address) with non-default port
  12009. EXPECT_EQ("[fe80::1%eth0]:8080",
  12010. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12011. // Edge case: Port 443 with is_ssl=false (should add port)
  12012. EXPECT_EQ("example.com:443",
  12013. detail::make_host_and_port_string("example.com", 443, false));
  12014. // Edge case: Port 80 with is_ssl=true (should add port)
  12015. EXPECT_EQ("example.com:80",
  12016. detail::make_host_and_port_string("example.com", 80, true));
  12017. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12018. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12019. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12020. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12021. // Security fix: Already bracketed IPv6 should not get double brackets
  12022. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12023. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12024. EXPECT_EQ("[::1]:8080",
  12025. detail::make_host_and_port_string("[::1]", 8080, false));
  12026. EXPECT_EQ("[2001:db8::1]:8080",
  12027. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12028. EXPECT_EQ("[fe80::1%eth0]",
  12029. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12030. EXPECT_EQ("[fe80::1%eth0]:8080",
  12031. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12032. // Edge case: Empty host (should return as-is)
  12033. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12034. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12035. // This is a known limitation but shouldn't crash
  12036. EXPECT_EQ("[host:name]",
  12037. detail::make_host_and_port_string("host:name", 80, false));
  12038. // Port number edge cases (no validation, but should not crash)
  12039. EXPECT_EQ("example.com:0",
  12040. detail::make_host_and_port_string("example.com", 0, false));
  12041. EXPECT_EQ("example.com:-1",
  12042. detail::make_host_and_port_string("example.com", -1, false));
  12043. EXPECT_EQ("example.com:65535",
  12044. detail::make_host_and_port_string("example.com", 65535, false));
  12045. EXPECT_EQ("example.com:65536",
  12046. detail::make_host_and_port_string("example.com", 65536, false));
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12050. httplib::SSLClient cli("roblox.com", 443);
  12051. cli.set_follow_location(true);
  12052. auto res = cli.Get("/");
  12053. ASSERT_TRUE(res);
  12054. EXPECT_EQ(StatusCode::OK_200, res->status);
  12055. }
  12056. #endif
  12057. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12058. Server svr;
  12059. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12060. EXPECT_EQ(res.status, 400);
  12061. });
  12062. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12063. auto se = detail::scope_exit([&] {
  12064. svr.stop();
  12065. thread.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. });
  12068. svr.wait_until_ready();
  12069. Client cli(HOST, PORT);
  12070. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12071. }
  12072. TEST(InvalidHeaderCharsTest, is_field_name) {
  12073. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12074. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12075. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12076. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12077. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12078. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12079. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12080. EXPECT_FALSE(detail::fields::is_field_name(""));
  12081. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12082. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12083. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12084. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12085. }
  12086. TEST(InvalidHeaderCharsTest, is_field_value) {
  12087. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12088. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12089. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12090. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12091. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12092. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12093. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12094. EXPECT_TRUE(detail::fields::is_field_value(""));
  12095. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12096. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12097. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12098. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12099. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12100. }
  12101. TEST(InvalidHeaderCharsTest, OnServer) {
  12102. Server svr;
  12103. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12104. std::string header = "Not Set";
  12105. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12106. res.set_header(header, "value");
  12107. res.set_content("Page Content Page Content", "text/plain");
  12108. });
  12109. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12110. std::string header = "Not Set";
  12111. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12112. res.set_header("X-Test", header);
  12113. res.set_content("Page Content Page Content", "text/plain");
  12114. });
  12115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. thread.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. Client cli(HOST, PORT);
  12123. {
  12124. auto res = cli.Get(
  12125. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12126. ASSERT_TRUE(res);
  12127. EXPECT_EQ("Page Content Page Content", res->body);
  12128. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12129. }
  12130. {
  12131. auto res = cli.Get(
  12132. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12133. ASSERT_TRUE(res);
  12134. EXPECT_EQ("Page Content Page Content", res->body);
  12135. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12136. }
  12137. }
  12138. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12139. auto handled = false;
  12140. Server svr;
  12141. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12142. thread t = thread([&] { svr.listen(HOST, PORT); });
  12143. auto se = detail::scope_exit([&] {
  12144. svr.stop();
  12145. t.join();
  12146. ASSERT_FALSE(svr.is_running());
  12147. ASSERT_FALSE(handled);
  12148. });
  12149. svr.wait_until_ready();
  12150. auto req = "POST /test HTTP/1.1\r\n"
  12151. "Content-Length: x\r\n"
  12152. "\r\n";
  12153. std::string response;
  12154. ASSERT_TRUE(send_request(1, req, &response));
  12155. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12156. response.substr(0, response.find("\r\n")));
  12157. }
  12158. #ifndef _WIN32
  12159. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12160. static constexpr char reject[] = "Unauthorized";
  12161. static constexpr char accept[] = "Upload accepted";
  12162. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12163. Server svr;
  12164. svr.set_expect_100_continue_handler(
  12165. [](const Request & /*req*/, Response &res) {
  12166. res.status = StatusCode::Unauthorized_401;
  12167. res.set_content(reject, "text/plain");
  12168. return res.status;
  12169. });
  12170. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12171. res.set_content(accept, "text/plain");
  12172. });
  12173. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12174. auto se = detail::scope_exit([&] {
  12175. svr.stop();
  12176. thread.join();
  12177. ASSERT_FALSE(svr.is_running());
  12178. });
  12179. svr.wait_until_ready();
  12180. {
  12181. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12182. curl_easy_init(), &curl_easy_cleanup};
  12183. ASSERT_NE(curl, nullptr);
  12184. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12185. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12186. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12187. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12188. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12189. &curl_slist_free_all};
  12190. ASSERT_NE(list, nullptr);
  12191. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12192. struct read_data {
  12193. size_t read_size;
  12194. size_t total_size;
  12195. } data = {0, total_size};
  12196. using read_callback_t =
  12197. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12198. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12199. void *userdata) -> size_t {
  12200. read_data *d = (read_data *)userdata;
  12201. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12202. std::fill_n(ptr, size * nmemb, 'A');
  12203. d->read_size += size * nmemb;
  12204. return size * nmemb;
  12205. };
  12206. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12207. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12208. std::vector<char> buffer;
  12209. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12210. using write_callback_t =
  12211. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12212. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12213. void *userdata) -> size_t {
  12214. std::vector<char> *buf = (std::vector<char> *)userdata;
  12215. buf->reserve(buf->size() + size * nmemb + 1);
  12216. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12217. return size * nmemb;
  12218. };
  12219. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12220. {
  12221. const auto res = curl_easy_perform(curl.get());
  12222. ASSERT_EQ(res, CURLE_OK);
  12223. }
  12224. {
  12225. auto response_code = long{};
  12226. const auto res =
  12227. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12228. ASSERT_EQ(res, CURLE_OK);
  12229. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12230. }
  12231. {
  12232. auto dl = curl_off_t{};
  12233. const auto res =
  12234. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12235. ASSERT_EQ(res, CURLE_OK);
  12236. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12237. }
  12238. {
  12239. buffer.push_back('\0');
  12240. ASSERT_STRCASEEQ(buffer.data(), reject);
  12241. }
  12242. }
  12243. }
  12244. #endif
  12245. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12246. // Regression test for #2458.
  12247. //
  12248. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12249. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12250. // ticket can make the client socket spuriously readable during the
  12251. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12252. // the client withholds the body and then blocks reading a response that never
  12253. // comes, failing with `Failed to read connection`.
  12254. //
  12255. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12256. // within the timeout. This raw OpenSSL server deliberately never sends
  12257. // `100 Continue`; the client must still deliver the body and receive 200.
  12258. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12259. signal(SIGPIPE, SIG_IGN);
  12260. const auto port = PORT + 4;
  12261. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12262. ASSERT_NE(srv, INVALID_SOCKET);
  12263. int opt = 1;
  12264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12265. sockaddr_in addr{};
  12266. addr.sin_family = AF_INET;
  12267. addr.sin_port = htons(static_cast<uint16_t>(port));
  12268. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12269. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12270. ASSERT_EQ(0, ::listen(srv, 1));
  12271. std::atomic<size_t> server_body_bytes{0};
  12272. auto server_thread = std::thread([&] {
  12273. sockaddr_in cli_addr{};
  12274. socklen_t cli_len = sizeof(cli_addr);
  12275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12276. if (cli == INVALID_SOCKET) { return; }
  12277. // Bound the lifetime of the server side so a buggy client (which never
  12278. // sends the body) cannot make this thread block forever on join.
  12279. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12280. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12281. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12282. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12283. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12284. SSL *ssl = SSL_new(ctx);
  12285. SSL_set_fd(ssl, static_cast<int>(cli));
  12286. if (SSL_accept(ssl) > 0) {
  12287. // Read the request headers. Reading here also flushes the TLS 1.3
  12288. // session tickets to the client. Deliberately do NOT send
  12289. // `100 Continue`.
  12290. std::string buf;
  12291. char tmp[1024];
  12292. while (buf.find("\r\n\r\n") == std::string::npos) {
  12293. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12294. if (n <= 0) { break; }
  12295. buf.append(tmp, static_cast<size_t>(n));
  12296. }
  12297. // A correct client sends the body now; count what arrives.
  12298. auto pos = buf.find("\r\n\r\n");
  12299. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12300. while (body < 4096) {
  12301. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12302. if (n <= 0) { break; }
  12303. body += static_cast<size_t>(n);
  12304. }
  12305. server_body_bytes = body;
  12306. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12307. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12308. SSL_shutdown(ssl);
  12309. }
  12310. SSL_free(ssl);
  12311. detail::close_socket(cli);
  12312. SSL_CTX_free(ctx);
  12313. });
  12314. auto se = detail::scope_exit([&] {
  12315. server_thread.join();
  12316. detail::close_socket(srv);
  12317. });
  12318. SSLClient cli("127.0.0.1", port);
  12319. cli.enable_server_certificate_verification(false);
  12320. cli.set_connection_timeout(5, 0);
  12321. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12322. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12323. std::string body(4096, 'A');
  12324. auto res = cli.Put("/api/test", body, "application/json");
  12325. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12326. EXPECT_EQ(StatusCode::OK_200, res->status);
  12327. EXPECT_EQ(body.size(), server_body_bytes.load());
  12328. }
  12329. #endif
  12330. template <typename S, typename C>
  12331. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12332. svr.Get("/stream", [&](const Request &, Response &res) {
  12333. auto data = new std::string("01234567890123456789");
  12334. res.set_content_provider(
  12335. data->size(), "text/plain",
  12336. [&, data](size_t offset, size_t length, DataSink &sink) {
  12337. const size_t DATA_CHUNK_SIZE = 4;
  12338. const auto &d = *data;
  12339. std::this_thread::sleep_for(std::chrono::seconds(1));
  12340. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12341. return true;
  12342. },
  12343. [data](bool success) {
  12344. EXPECT_FALSE(success);
  12345. delete data;
  12346. });
  12347. });
  12348. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12349. auto i = new size_t(0);
  12350. res.set_content_provider(
  12351. "text/plain",
  12352. [i](size_t, DataSink &sink) {
  12353. if (*i < 5) {
  12354. std::this_thread::sleep_for(std::chrono::seconds(1));
  12355. sink.write("abcd", 4);
  12356. (*i)++;
  12357. } else {
  12358. sink.done();
  12359. }
  12360. return true;
  12361. },
  12362. [i](bool success) {
  12363. EXPECT_FALSE(success);
  12364. delete i;
  12365. });
  12366. });
  12367. svr.Get("/chunked", [&](const Request &, Response &res) {
  12368. auto i = new size_t(0);
  12369. res.set_chunked_content_provider(
  12370. "text/plain",
  12371. [i](size_t, DataSink &sink) {
  12372. if (*i < 5) {
  12373. std::this_thread::sleep_for(std::chrono::seconds(1));
  12374. sink.os << "abcd";
  12375. (*i)++;
  12376. } else {
  12377. sink.done();
  12378. }
  12379. return true;
  12380. },
  12381. [i](bool success) {
  12382. EXPECT_FALSE(success);
  12383. delete i;
  12384. });
  12385. });
  12386. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. listen_thread.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12394. {
  12395. auto start = std::chrono::steady_clock::now();
  12396. auto res = cli.Get("/stream");
  12397. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12398. std::chrono::steady_clock::now() - start)
  12399. .count();
  12400. ASSERT_FALSE(res);
  12401. EXPECT_EQ(Error::Read, res.error());
  12402. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12403. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12404. }
  12405. {
  12406. auto start = std::chrono::steady_clock::now();
  12407. auto res = cli.Get("/stream_without_length");
  12408. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12409. std::chrono::steady_clock::now() - start)
  12410. .count();
  12411. ASSERT_FALSE(res);
  12412. EXPECT_EQ(Error::Read, res.error());
  12413. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12414. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12415. }
  12416. {
  12417. auto start = std::chrono::steady_clock::now();
  12418. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12419. EXPECT_EQ("abcd", string(data, data_length));
  12420. return true;
  12421. });
  12422. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12423. std::chrono::steady_clock::now() - start)
  12424. .count();
  12425. ASSERT_FALSE(res);
  12426. EXPECT_EQ(Error::Read, res.error());
  12427. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12428. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12429. }
  12430. }
  12431. TEST(MaxTimeoutTest, ContentStream) {
  12432. time_t timeout = 2000;
  12433. time_t threshold = 200;
  12434. Server svr;
  12435. Client cli("localhost", PORT);
  12436. max_timeout_test(svr, cli, timeout, threshold);
  12437. }
  12438. #ifdef CPPHTTPLIB_SSL_ENABLED
  12439. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12440. time_t timeout = 2000;
  12441. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12443. SSLClient cli("localhost", PORT);
  12444. cli.enable_server_certificate_verification(false);
  12445. max_timeout_test(svr, cli, timeout, threshold);
  12446. }
  12447. #endif
  12448. class EventDispatcher {
  12449. public:
  12450. EventDispatcher() {}
  12451. bool wait_event(DataSink *sink) {
  12452. unique_lock<mutex> lk(m_);
  12453. int id = id_;
  12454. // Wait with timeout to prevent hanging if client disconnects
  12455. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12456. [&] { return cid_ == id; })) {
  12457. return false; // Timeout occurred
  12458. }
  12459. sink->write(message_.data(), message_.size());
  12460. return true;
  12461. }
  12462. void send_event(const string &message) {
  12463. lock_guard<mutex> lk(m_);
  12464. cid_ = id_++;
  12465. message_ = message;
  12466. cv_.notify_all();
  12467. }
  12468. private:
  12469. mutex m_;
  12470. condition_variable cv_;
  12471. atomic_int id_{0};
  12472. atomic_int cid_{-1};
  12473. string message_;
  12474. };
  12475. TEST(ClientInThreadTest, Issue2068) {
  12476. EventDispatcher ed;
  12477. Server svr;
  12478. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12479. res.set_chunked_content_provider("text/event-stream",
  12480. [&](size_t /*offset*/, DataSink &sink) {
  12481. return ed.wait_event(&sink);
  12482. });
  12483. });
  12484. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12485. svr.wait_until_ready();
  12486. thread event_thread([&] {
  12487. int id = 0;
  12488. while (svr.is_running()) {
  12489. this_thread::sleep_for(chrono::milliseconds(500));
  12490. std::stringstream ss;
  12491. ss << "data: " << id << "\n\n";
  12492. ed.send_event(ss.str());
  12493. id++;
  12494. }
  12495. });
  12496. auto se = detail::scope_exit([&] {
  12497. svr.stop();
  12498. listen_thread.join();
  12499. event_thread.join();
  12500. ASSERT_FALSE(svr.is_running());
  12501. });
  12502. {
  12503. auto client = detail::make_unique<Client>(HOST, PORT);
  12504. client->set_read_timeout(std::chrono::minutes(10));
  12505. std::atomic<bool> stop{false};
  12506. std::thread t([&] {
  12507. client->Get("/event1",
  12508. [&](const char *, size_t) -> bool { return !stop; });
  12509. });
  12510. std::this_thread::sleep_for(std::chrono::seconds(2));
  12511. stop = true;
  12512. client->stop();
  12513. t.join();
  12514. // Reset client after thread has finished
  12515. client.reset();
  12516. }
  12517. }
  12518. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12519. auto handled = false;
  12520. Server svr;
  12521. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12523. auto se = detail::scope_exit([&] {
  12524. svr.stop();
  12525. t.join();
  12526. ASSERT_FALSE(svr.is_running());
  12527. ASSERT_FALSE(handled);
  12528. });
  12529. svr.wait_until_ready();
  12530. // Two Content-Length headers with different values — must be rejected
  12531. auto req = "POST /test HTTP/1.1\r\n"
  12532. "Content-Length: 5\r\n"
  12533. "Content-Length: 10\r\n"
  12534. "\r\n"
  12535. "hello";
  12536. std::string response;
  12537. ASSERT_TRUE(send_request(1, req, &response));
  12538. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12539. response.substr(0, response.find("\r\n")));
  12540. }
  12541. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12542. auto handled = false;
  12543. Server svr;
  12544. svr.Post("/test", [&](const Request &, Response &res) {
  12545. handled = true;
  12546. res.set_content("ok", "text/plain");
  12547. });
  12548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12549. auto se = detail::scope_exit([&] {
  12550. svr.stop();
  12551. t.join();
  12552. ASSERT_FALSE(svr.is_running());
  12553. ASSERT_TRUE(handled);
  12554. });
  12555. svr.wait_until_ready();
  12556. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12557. auto req = "POST /test HTTP/1.1\r\n"
  12558. "Content-Length: 5\r\n"
  12559. "Content-Length: 5\r\n"
  12560. "\r\n"
  12561. "hello";
  12562. std::string response;
  12563. ASSERT_TRUE(send_request(1, req, &response));
  12564. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12565. }
  12566. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12567. Server svr;
  12568. svr.Get("/", [](const Request &req, Response &res) {
  12569. EXPECT_EQ(2U, req.trailers.size());
  12570. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12571. // Denied
  12572. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12573. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12574. // Accepted
  12575. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12576. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12577. EXPECT_TRUE(req.has_trailer("X-World"));
  12578. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12579. res.set_content("ok", "text/plain");
  12580. });
  12581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12582. auto se = detail::scope_exit([&] {
  12583. svr.stop();
  12584. t.join();
  12585. ASSERT_FALSE(svr.is_running());
  12586. });
  12587. svr.wait_until_ready();
  12588. const std::string req = "GET / HTTP/1.1\r\n"
  12589. "Transfer-Encoding: chunked\r\n"
  12590. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12591. "\r\n"
  12592. "0\r\n"
  12593. "Content-Length: 10\r\n"
  12594. "Host: internal.local\r\n"
  12595. "Content-Type: malicious/content\r\n"
  12596. "Cookie: any\r\n"
  12597. "Set-Cookie: any\r\n"
  12598. "X-Forwarded-For: attacker.com\r\n"
  12599. "X-Real-Ip: 1.1.1.1\r\n"
  12600. "X-Hello: hello\r\n"
  12601. "X-World: world\r\n"
  12602. "\r\n";
  12603. std::string res;
  12604. ASSERT_TRUE(send_request(1, req, &res));
  12605. }
  12606. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12607. Server svr;
  12608. std::string observed_remote_addr;
  12609. std::string observed_xff;
  12610. svr.Get("/ip", [&](const Request &req, Response &res) {
  12611. observed_remote_addr = req.remote_addr;
  12612. observed_xff = req.get_header_value("X-Forwarded-For");
  12613. res.set_content("ok", "text/plain");
  12614. });
  12615. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12616. auto se = detail::scope_exit([&] {
  12617. svr.stop();
  12618. t.join();
  12619. ASSERT_FALSE(svr.is_running());
  12620. });
  12621. svr.wait_until_ready();
  12622. Client cli(HOST, PORT);
  12623. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12624. ASSERT_TRUE(res);
  12625. EXPECT_EQ(StatusCode::OK_200, res->status);
  12626. EXPECT_EQ(observed_xff, "203.0.113.66");
  12627. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12628. observed_remote_addr == "127.0.0.1");
  12629. }
  12630. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12631. Server svr;
  12632. svr.set_trusted_proxies({"203.0.113.66"});
  12633. std::string observed_remote_addr;
  12634. std::string observed_xff;
  12635. svr.Get("/ip", [&](const Request &req, Response &res) {
  12636. observed_remote_addr = req.remote_addr;
  12637. observed_xff = req.get_header_value("X-Forwarded-For");
  12638. res.set_content("ok", "text/plain");
  12639. });
  12640. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12641. auto se = detail::scope_exit([&] {
  12642. svr.stop();
  12643. t.join();
  12644. ASSERT_FALSE(svr.is_running());
  12645. });
  12646. svr.wait_until_ready();
  12647. Client cli(HOST, PORT);
  12648. auto res = cli.Get("/ip");
  12649. ASSERT_TRUE(res);
  12650. EXPECT_EQ(StatusCode::OK_200, res->status);
  12651. EXPECT_EQ(observed_xff, "");
  12652. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12653. observed_remote_addr == "127.0.0.1");
  12654. }
  12655. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12656. Server svr;
  12657. svr.set_trusted_proxies({"203.0.113.66"});
  12658. std::string observed_remote_addr;
  12659. std::string observed_xff;
  12660. svr.Get("/ip", [&](const Request &req, Response &res) {
  12661. observed_remote_addr = req.remote_addr;
  12662. observed_xff = req.get_header_value("X-Forwarded-For");
  12663. res.set_content("ok", "text/plain");
  12664. });
  12665. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12666. auto se = detail::scope_exit([&] {
  12667. svr.stop();
  12668. t.join();
  12669. ASSERT_FALSE(svr.is_running());
  12670. });
  12671. svr.wait_until_ready();
  12672. Client cli(HOST, PORT);
  12673. auto res = cli.Get(
  12674. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12675. ASSERT_TRUE(res);
  12676. EXPECT_EQ(StatusCode::OK_200, res->status);
  12677. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12678. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12679. }
  12680. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12681. Server svr;
  12682. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12683. std::string observed_remote_addr;
  12684. std::string observed_xff;
  12685. svr.Get("/ip", [&](const Request &req, Response &res) {
  12686. observed_remote_addr = req.remote_addr;
  12687. observed_xff = req.get_header_value("X-Forwarded-For");
  12688. res.set_content("ok", "text/plain");
  12689. });
  12690. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12691. auto se = detail::scope_exit([&] {
  12692. svr.stop();
  12693. t.join();
  12694. ASSERT_FALSE(svr.is_running());
  12695. });
  12696. svr.wait_until_ready();
  12697. Client cli(HOST, PORT);
  12698. auto res = cli.Get(
  12699. "/ip",
  12700. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12701. ASSERT_TRUE(res);
  12702. EXPECT_EQ(StatusCode::OK_200, res->status);
  12703. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12704. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12705. }
  12706. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12707. Server svr;
  12708. svr.set_trusted_proxies({"192.0.2.45"});
  12709. std::string observed_remote_addr;
  12710. std::string observed_xff;
  12711. svr.Get("/ip", [&](const Request &req, Response &res) {
  12712. observed_remote_addr = req.remote_addr;
  12713. observed_xff = req.get_header_value("X-Forwarded-For");
  12714. res.set_content("ok", "text/plain");
  12715. });
  12716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. t.join();
  12720. ASSERT_FALSE(svr.is_running());
  12721. });
  12722. svr.wait_until_ready();
  12723. Client cli(HOST, PORT);
  12724. auto res = cli.Get(
  12725. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12726. ASSERT_TRUE(res);
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12729. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12730. }
  12731. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12732. Server svr;
  12733. svr.set_trusted_proxies({"192.0.2.45"});
  12734. std::string observed_remote_addr;
  12735. std::string observed_xff;
  12736. svr.Get("/ip", [&](const Request &req, Response &res) {
  12737. observed_remote_addr = req.remote_addr;
  12738. observed_xff = req.get_header_value("X-Forwarded-For");
  12739. res.set_content("ok", "text/plain");
  12740. });
  12741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12742. auto se = detail::scope_exit([&] {
  12743. svr.stop();
  12744. t.join();
  12745. ASSERT_FALSE(svr.is_running());
  12746. });
  12747. svr.wait_until_ready();
  12748. Client cli(HOST, PORT);
  12749. auto res = cli.Get(
  12750. "/ip",
  12751. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12752. ASSERT_TRUE(res);
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12755. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12756. }
  12757. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12758. Server svr;
  12759. svr.set_trusted_proxies({"192.0.2.45"});
  12760. std::string observed_remote_addr;
  12761. std::string observed_xff;
  12762. svr.Get("/ip", [&](const Request &req, Response &res) {
  12763. observed_remote_addr = req.remote_addr;
  12764. observed_xff = req.get_header_value("X-Forwarded-For");
  12765. res.set_content("ok", "text/plain");
  12766. });
  12767. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. std::string raw_req =
  12775. "GET /ip HTTP/1.1\r\n"
  12776. "Host: localhost\r\n"
  12777. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12778. "Connection: close\r\n"
  12779. "\r\n";
  12780. std::string out;
  12781. ASSERT_TRUE(send_request(5, raw_req, &out));
  12782. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12783. // Header parser trims surrounding whitespace of the header value
  12784. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12785. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12786. }
  12787. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12788. // crash the server (it used to call front() on an empty vector inside
  12789. // get_client_ip). The connection-level remote address must be retained instead.
  12790. static void run_malformed_xff_test(const std::string &xff_value) {
  12791. Server svr;
  12792. svr.set_trusted_proxies({"192.0.2.45"});
  12793. std::string observed_remote_addr;
  12794. svr.Get("/ip", [&](const Request &req, Response &res) {
  12795. observed_remote_addr = req.remote_addr;
  12796. res.set_content("ok", "text/plain");
  12797. });
  12798. int port = 0;
  12799. thread t = thread([&]() {
  12800. port = svr.bind_to_any_port(HOST);
  12801. svr.listen_after_bind();
  12802. });
  12803. auto se = detail::scope_exit([&] {
  12804. svr.stop();
  12805. t.join();
  12806. ASSERT_FALSE(svr.is_running());
  12807. });
  12808. svr.wait_until_ready();
  12809. Client cli(HOST, port);
  12810. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  12811. ASSERT_TRUE(res);
  12812. EXPECT_EQ(StatusCode::OK_200, res->status);
  12813. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12814. observed_remote_addr == "127.0.0.1");
  12815. }
  12816. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12817. run_malformed_xff_test("");
  12818. }
  12819. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12820. run_malformed_xff_test(",");
  12821. }
  12822. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12823. run_malformed_xff_test(", , ,");
  12824. }
  12825. #ifndef _WIN32
  12826. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12827. Server svr;
  12828. svr.Post("/post", [&](const Request &req, Response &res) {
  12829. res.set_content(req.body, "text/plain");
  12830. });
  12831. svr.Put("/put", [&](const Request &req, Response &res) {
  12832. res.set_content(req.body, "text/plain");
  12833. });
  12834. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12835. res.set_content(req.body, "text/plain");
  12836. });
  12837. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12838. res.set_content(req.body, "text/plain");
  12839. });
  12840. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12841. auto se = detail::scope_exit([&] {
  12842. svr.stop();
  12843. t.join();
  12844. ASSERT_FALSE(svr.is_running());
  12845. });
  12846. svr.wait_until_ready();
  12847. std::string resp;
  12848. // POST without Content-Length
  12849. ASSERT_TRUE(send_request(5,
  12850. "POST /post HTTP/1.1\r\n"
  12851. "Host: localhost\r\n"
  12852. "Connection: close\r\n"
  12853. "\r\n",
  12854. &resp));
  12855. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12856. // PUT without Content-Length
  12857. resp.clear();
  12858. ASSERT_TRUE(send_request(5,
  12859. "PUT /put HTTP/1.1\r\n"
  12860. "Host: localhost\r\n"
  12861. "Connection: close\r\n"
  12862. "\r\n",
  12863. &resp));
  12864. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12865. // PATCH without Content-Length
  12866. resp.clear();
  12867. ASSERT_TRUE(send_request(5,
  12868. "PATCH /patch HTTP/1.1\r\n"
  12869. "Host: localhost\r\n"
  12870. "Connection: close\r\n"
  12871. "\r\n",
  12872. &resp));
  12873. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12874. // DELETE without Content-Length
  12875. resp.clear();
  12876. ASSERT_TRUE(send_request(5,
  12877. "DELETE /delete HTTP/1.1\r\n"
  12878. "Host: localhost\r\n"
  12879. "Connection: close\r\n"
  12880. "\r\n",
  12881. &resp));
  12882. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12883. }
  12884. #endif
  12885. //==============================================================================
  12886. // open_stream() Tests
  12887. //==============================================================================
  12888. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12889. std::string result;
  12890. char buf[8192];
  12891. ssize_t n;
  12892. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12893. result.append(buf, static_cast<size_t>(n));
  12894. }
  12895. return result;
  12896. }
  12897. // Mock stream for unit tests
  12898. class MockStream : public Stream {
  12899. public:
  12900. std::string data;
  12901. size_t pos = 0;
  12902. ssize_t error_after = -1; // -1 = no error
  12903. explicit MockStream(const std::string &d, ssize_t err = -1)
  12904. : data(d), error_after(err) {}
  12905. bool is_readable() const override { return true; }
  12906. bool wait_readable() const override { return true; }
  12907. bool wait_writable() const override { return true; }
  12908. ssize_t read(char *ptr, size_t size) override {
  12909. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12910. if (pos >= data.size()) return 0;
  12911. size_t limit =
  12912. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12913. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12914. std::memcpy(ptr, data.data() + pos, to_read);
  12915. pos += to_read;
  12916. return static_cast<ssize_t>(to_read);
  12917. }
  12918. ssize_t write(const char *, size_t) override { return -1; }
  12919. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12920. ip = "127.0.0.1";
  12921. port = 0;
  12922. }
  12923. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12924. ip = "127.0.0.1";
  12925. port = 0;
  12926. }
  12927. socket_t socket() const override { return INVALID_SOCKET; }
  12928. time_t duration() const override { return 0; }
  12929. };
  12930. TEST(StreamHandleTest, Basic) {
  12931. ClientImpl::StreamHandle handle;
  12932. EXPECT_FALSE(handle.is_valid());
  12933. handle.response = detail::make_unique<Response>();
  12934. handle.error = Error::Connection;
  12935. EXPECT_FALSE(handle.is_valid());
  12936. handle.error = Error::Success;
  12937. EXPECT_TRUE(handle.is_valid());
  12938. }
  12939. TEST(BodyReaderTest, Basic) {
  12940. MockStream stream("Hello, World!");
  12941. detail::BodyReader reader;
  12942. reader.stream = &stream;
  12943. reader.content_length = 13;
  12944. char buf[32];
  12945. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12946. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12947. EXPECT_TRUE(reader.eof);
  12948. }
  12949. TEST(BodyReaderTest, NoStream) {
  12950. detail::BodyReader reader;
  12951. char buf[32];
  12952. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12953. EXPECT_EQ(Error::Connection, reader.last_error);
  12954. }
  12955. TEST(BodyReaderTest, Error) {
  12956. MockStream stream("Hello, World!", 5);
  12957. detail::BodyReader reader;
  12958. reader.stream = &stream;
  12959. reader.content_length = 13;
  12960. char buf[32];
  12961. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12962. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12963. EXPECT_EQ(Error::Read, reader.last_error);
  12964. }
  12965. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12966. // Mock-based StreamHandle tests relying on private internals are removed.
  12967. class OpenStreamTest : public ::testing::Test {
  12968. protected:
  12969. void SetUp() override {
  12970. svr_.Get("/hello", [](const Request &, Response &res) {
  12971. res.set_content("Hello World!", "text/plain");
  12972. });
  12973. svr_.Get("/large", [](const Request &, Response &res) {
  12974. res.set_content(std::string(10000, 'X'), "text/plain");
  12975. });
  12976. svr_.Get("/chunked", [](const Request &, Response &res) {
  12977. res.set_chunked_content_provider("text/plain",
  12978. [](size_t offset, DataSink &sink) {
  12979. if (offset < 15) {
  12980. sink.write("chunk", 5);
  12981. return true;
  12982. }
  12983. sink.done();
  12984. return true;
  12985. });
  12986. });
  12987. svr_.Get("/compressible", [](const Request &, Response &res) {
  12988. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12989. DataSink &sink) {
  12990. if (offset < 100 * 1024) {
  12991. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12992. sink.write(chunk.data(), chunk.size());
  12993. return true;
  12994. }
  12995. sink.done();
  12996. return true;
  12997. });
  12998. });
  12999. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13000. [](const Request & /*req*/, Response &res) {
  13001. auto i = new int(0);
  13002. res.set_header("Trailer", "Content-Length, X-Allowed");
  13003. res.set_chunked_content_provider(
  13004. "text/plain",
  13005. [i](size_t /*offset*/, DataSink &sink) {
  13006. switch (*i) {
  13007. case 0: sink.os << "123"; break;
  13008. case 1: sink.os << "456"; break;
  13009. case 2: sink.os << "789"; break;
  13010. case 3: {
  13011. sink.done_with_trailer(
  13012. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13013. } break;
  13014. }
  13015. (*i)++;
  13016. return true;
  13017. },
  13018. [i](bool success) {
  13019. EXPECT_TRUE(success);
  13020. delete i;
  13021. });
  13022. });
  13023. // Echo headers endpoint for header-related tests
  13024. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13025. std::string body;
  13026. for (const auto &h : req.headers) {
  13027. body.append(h.first);
  13028. body.push_back(':');
  13029. body.append(h.second);
  13030. body.push_back('\n');
  13031. }
  13032. res.set_content(body, "text/plain");
  13033. });
  13034. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13035. std::string body;
  13036. for (const auto &h : req.headers) {
  13037. body.append(h.first);
  13038. body.push_back(':');
  13039. body.append(h.second);
  13040. body.push_back('\n');
  13041. }
  13042. res.set_content(body, "text/plain");
  13043. });
  13044. port_ = svr_.bind_to_any_port("127.0.0.1");
  13045. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13046. svr_.wait_until_ready();
  13047. }
  13048. void TearDown() override {
  13049. svr_.stop();
  13050. if (thread_.joinable()) thread_.join();
  13051. }
  13052. Server svr_;
  13053. std::thread thread_;
  13054. int port_ = 0;
  13055. };
  13056. TEST_F(OpenStreamTest, Basic) {
  13057. Client cli("127.0.0.1", port_);
  13058. auto handle = cli.open_stream("GET", "/hello");
  13059. EXPECT_TRUE(handle.is_valid());
  13060. EXPECT_EQ("Hello World!", read_all(handle));
  13061. }
  13062. TEST_F(OpenStreamTest, SmallBuffer) {
  13063. Client cli("127.0.0.1", port_);
  13064. auto handle = cli.open_stream("GET", "/hello");
  13065. std::string result;
  13066. char buf[4];
  13067. ssize_t n;
  13068. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13069. result.append(buf, static_cast<size_t>(n));
  13070. EXPECT_EQ("Hello World!", result);
  13071. }
  13072. TEST_F(OpenStreamTest, DefaultHeaders) {
  13073. Client cli("127.0.0.1", port_);
  13074. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13075. {
  13076. auto handle = cli.open_stream("GET", "/echo-headers");
  13077. ASSERT_TRUE(handle.is_valid());
  13078. auto body = read_all(handle);
  13079. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13080. std::string::npos);
  13081. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13082. std::string::npos);
  13083. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13084. }
  13085. // open_stream POST with body and no explicit content_type should NOT add
  13086. // text/plain Content-Type (behavior differs from non-streaming path), but
  13087. // should include Content-Length
  13088. {
  13089. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13090. ASSERT_TRUE(handle.is_valid());
  13091. auto body = read_all(handle);
  13092. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13093. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13094. }
  13095. // open_stream POST with explicit Content-Type should preserve it
  13096. {
  13097. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13098. {{"Content-Type", "application/custom"}},
  13099. "{}", "application/custom");
  13100. ASSERT_TRUE(handle.is_valid());
  13101. auto body = read_all(handle);
  13102. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13103. }
  13104. // User-specified User-Agent must not be overwritten for stream API
  13105. {
  13106. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13107. {{"User-Agent", "MyAgent/1.2"}});
  13108. ASSERT_TRUE(handle.is_valid());
  13109. auto body = read_all(handle);
  13110. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13111. }
  13112. }
  13113. TEST_F(OpenStreamTest, Large) {
  13114. Client cli("127.0.0.1", port_);
  13115. auto handle = cli.open_stream("GET", "/large");
  13116. EXPECT_EQ(10000u, read_all(handle).size());
  13117. }
  13118. TEST_F(OpenStreamTest, ConnectionError) {
  13119. Client cli("127.0.0.1", 9999);
  13120. auto handle = cli.open_stream("GET", "/hello");
  13121. EXPECT_FALSE(handle.is_valid());
  13122. }
  13123. TEST_F(OpenStreamTest, Chunked) {
  13124. Client cli("127.0.0.1", port_);
  13125. auto handle = cli.open_stream("GET", "/chunked");
  13126. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13127. "Transfer-Encoding") == "chunked");
  13128. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13129. }
  13130. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13131. Client cli("127.0.0.1", port_);
  13132. auto handle =
  13133. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13134. ASSERT_TRUE(handle.is_valid());
  13135. // Consume body to allow trailers to be received/parsed
  13136. auto body = read_all(handle);
  13137. // Explicitly parse trailers (ensure trailers are available for assertion)
  13138. handle.parse_trailers_if_needed();
  13139. EXPECT_EQ(std::string("123456789"), body);
  13140. // The response should include a Trailer header declaring both names
  13141. ASSERT_TRUE(handle.response);
  13142. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13143. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13144. handle.response->get_header_value("Trailer"));
  13145. // Prohibited trailer must not be present
  13146. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13147. // Allowed trailer should be present
  13148. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13149. EXPECT_EQ(std::string("yes"),
  13150. handle.response->get_trailer_value("X-Allowed"));
  13151. // Verify trailers are NOT present as regular headers
  13152. EXPECT_EQ(std::string(""),
  13153. handle.response->get_header_value("Content-Length"));
  13154. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13155. }
  13156. static std::thread serve_single_response(std::promise<int> &port_promise,
  13157. const std::string &response) {
  13158. return std::thread([&port_promise, response] {
  13159. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13160. default_socket_options(srv);
  13161. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13162. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13163. sockaddr_in addr{};
  13164. addr.sin_family = AF_INET;
  13165. addr.sin_port = htons(0); // Let OS assign a free port
  13166. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13167. int opt = 1;
  13168. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13169. #ifdef _WIN32
  13170. reinterpret_cast<const char *>(&opt),
  13171. #else
  13172. &opt,
  13173. #endif
  13174. sizeof(opt));
  13175. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13176. ::listen(srv, 1) != 0) {
  13177. port_promise.set_value(-1);
  13178. detail::close_socket(srv);
  13179. return;
  13180. }
  13181. socklen_t addr_len = sizeof(addr);
  13182. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13183. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13184. sockaddr_in cli_addr{};
  13185. socklen_t cli_len = sizeof(cli_addr);
  13186. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13187. if (cli != INVALID_SOCKET) {
  13188. // Read the complete HTTP request (until the blank line that terminates
  13189. // headers) before sending the response. If the server closes the socket
  13190. // while the client's request data is still unread in the kernel receive
  13191. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13192. // connection on both sides: it discards the client's receive buffer
  13193. // (which already holds our response) and causes any in-progress write on
  13194. // the client to fail with ECONNRESET. Reading all request data first
  13195. // ensures close() emits a graceful FIN.
  13196. {
  13197. char rbuf[256];
  13198. std::string req;
  13199. while (req.find("\r\n\r\n") == std::string::npos) {
  13200. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13201. if (n <= 0) { break; }
  13202. req.append(rbuf, static_cast<size_t>(n));
  13203. }
  13204. }
  13205. ::send(cli,
  13206. #ifdef _WIN32
  13207. static_cast<const char *>(response.c_str()),
  13208. static_cast<int>(response.size()),
  13209. #else
  13210. response.c_str(), response.size(),
  13211. #endif
  13212. 0);
  13213. detail::close_socket(cli);
  13214. }
  13215. detail::close_socket(srv);
  13216. });
  13217. }
  13218. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13219. #ifndef _WIN32
  13220. signal(SIGPIPE, SIG_IGN);
  13221. #endif
  13222. std::promise<int> port_promise;
  13223. auto port_future = port_promise.get_future();
  13224. auto server_thread =
  13225. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13226. "Content-Type: text/plain\r\n"
  13227. "Content-Length: not-a-number\r\n"
  13228. "Connection: close\r\n"
  13229. "\r\n"
  13230. "hello");
  13231. auto port = port_future.get();
  13232. ASSERT_GT(port, 0);
  13233. Client cli("127.0.0.1", port);
  13234. auto handle = cli.open_stream("GET", "/");
  13235. EXPECT_FALSE(handle.is_valid());
  13236. server_thread.join();
  13237. }
  13238. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13239. #ifndef _WIN32
  13240. signal(SIGPIPE, SIG_IGN);
  13241. #endif
  13242. std::promise<int> port_promise;
  13243. auto port_future = port_promise.get_future();
  13244. auto server_thread = serve_single_response(
  13245. port_promise, "HTTP/1.1 200 OK\r\n"
  13246. "Content-Type: text/plain\r\n"
  13247. "Content-Length: 99999999999999999999999999\r\n"
  13248. "Connection: close\r\n"
  13249. "\r\n"
  13250. "hello");
  13251. auto port = port_future.get();
  13252. ASSERT_GT(port, 0);
  13253. // Before the fix, std::stoull would throw std::out_of_range here and
  13254. // crash the process. After the fix, strtoull silently clamps to
  13255. // ULLONG_MAX so the stream opens without crashing. The important thing
  13256. // is that the process does NOT terminate.
  13257. Client cli("127.0.0.1", port);
  13258. auto handle = cli.open_stream("GET", "/");
  13259. EXPECT_TRUE(handle.is_valid());
  13260. server_thread.join();
  13261. }
  13262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13263. TEST_F(OpenStreamTest, Gzip) {
  13264. Client cli("127.0.0.1", port_);
  13265. auto handle = cli.open_stream("GET", "/compressible", {},
  13266. {{"Accept-Encoding", "gzip"}});
  13267. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13268. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13269. }
  13270. #endif
  13271. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13272. TEST_F(OpenStreamTest, Brotli) {
  13273. Client cli("127.0.0.1", port_);
  13274. auto handle =
  13275. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13276. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13277. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13278. }
  13279. #endif
  13280. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13281. TEST_F(OpenStreamTest, Zstd) {
  13282. Client cli("127.0.0.1", port_);
  13283. auto handle = cli.open_stream("GET", "/compressible", {},
  13284. {{"Accept-Encoding", "zstd"}});
  13285. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13286. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13287. }
  13288. #endif
  13289. #ifdef CPPHTTPLIB_SSL_ENABLED
  13290. class SSLOpenStreamTest : public ::testing::Test {
  13291. protected:
  13292. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13293. void SetUp() override {
  13294. svr_.Get("/hello", [](const Request &, Response &res) {
  13295. res.set_content("Hello SSL World!", "text/plain");
  13296. });
  13297. svr_.Get("/chunked", [](const Request &, Response &res) {
  13298. res.set_chunked_content_provider("text/plain",
  13299. [](size_t offset, DataSink &sink) {
  13300. if (offset < 15) {
  13301. sink.write("chunk", 5);
  13302. return true;
  13303. }
  13304. sink.done();
  13305. return true;
  13306. });
  13307. });
  13308. svr_.Post("/echo", [](const Request &req, Response &res) {
  13309. res.set_content(req.body, req.get_header_value("Content-Type"));
  13310. });
  13311. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13312. std::string body = req.body;
  13313. res.set_chunked_content_provider(
  13314. "text/plain", [body](size_t offset, DataSink &sink) {
  13315. if (offset < body.size()) {
  13316. sink.write(body.data() + offset, body.size() - offset);
  13317. }
  13318. sink.done();
  13319. return true;
  13320. });
  13321. });
  13322. port_ = svr_.bind_to_any_port("127.0.0.1");
  13323. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13324. svr_.wait_until_ready();
  13325. }
  13326. void TearDown() override {
  13327. svr_.stop();
  13328. if (thread_.joinable()) thread_.join();
  13329. }
  13330. SSLServer svr_;
  13331. std::thread thread_;
  13332. int port_ = 0;
  13333. };
  13334. TEST_F(SSLOpenStreamTest, Basic) {
  13335. SSLClient cli("127.0.0.1", port_);
  13336. cli.enable_server_certificate_verification(false);
  13337. auto handle = cli.open_stream("GET", "/hello");
  13338. ASSERT_TRUE(handle.is_valid());
  13339. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13340. }
  13341. TEST_F(SSLOpenStreamTest, Chunked) {
  13342. SSLClient cli("127.0.0.1", port_);
  13343. cli.enable_server_certificate_verification(false);
  13344. auto handle = cli.open_stream("GET", "/chunked");
  13345. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13346. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13347. "Transfer-Encoding") == "chunked");
  13348. auto body = read_all(handle);
  13349. EXPECT_EQ("chunkchunkchunk", body);
  13350. }
  13351. TEST_F(SSLOpenStreamTest, Post) {
  13352. SSLClient cli("127.0.0.1", port_);
  13353. cli.enable_server_certificate_verification(false);
  13354. auto handle =
  13355. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13356. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13357. EXPECT_EQ(200, handle.response->status);
  13358. auto body = read_all(handle);
  13359. EXPECT_EQ("Hello SSL POST", body);
  13360. }
  13361. TEST_F(SSLOpenStreamTest, PostChunked) {
  13362. SSLClient cli("127.0.0.1", port_);
  13363. cli.enable_server_certificate_verification(false);
  13364. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13365. "Chunked SSL Data", "text/plain");
  13366. ASSERT_TRUE(handle.is_valid());
  13367. EXPECT_EQ(200, handle.response->status);
  13368. auto body = read_all(handle);
  13369. EXPECT_EQ("Chunked SSL Data", body);
  13370. }
  13371. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13372. // Content-Length is terminated by the server closing the connection. When the
  13373. // SSL peer sends a close_notify after the body, the client must treat it as a
  13374. // clean EOF and return a successful response rather than an error.
  13375. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(svr.is_valid());
  13378. svr.set_keep_alive_max_count(1);
  13379. const std::string expected_body = "Hello from connection-close response!";
  13380. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13381. res.set_content_provider("text/plain",
  13382. [&](size_t offset, DataSink &sink) -> bool {
  13383. if (offset < expected_body.size()) {
  13384. sink.write(expected_body.data() + offset,
  13385. expected_body.size() - offset);
  13386. }
  13387. sink.done();
  13388. return true;
  13389. });
  13390. });
  13391. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13392. auto se = detail::scope_exit([&] {
  13393. svr.stop();
  13394. listen_thread.join();
  13395. ASSERT_FALSE(svr.is_running());
  13396. });
  13397. svr.wait_until_ready();
  13398. SSLClient cli(HOST, PORT);
  13399. cli.enable_server_certificate_verification(false);
  13400. auto res = cli.Get("/no-content-length");
  13401. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13402. EXPECT_EQ(StatusCode::OK_200, res->status);
  13403. EXPECT_EQ(expected_body, res->body);
  13404. }
  13405. #endif // CPPHTTPLIB_SSL_ENABLED
  13406. //==============================================================================
  13407. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13408. // results for various scenarios.
  13409. //==============================================================================
  13410. TEST(ParityTest, GetVsOpenStream) {
  13411. Server svr;
  13412. const std::string path = "/parity";
  13413. const std::string content = "Parity test content: hello world";
  13414. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13415. res.set_content(content, "text/plain");
  13416. });
  13417. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13418. auto se = detail::scope_exit([&] {
  13419. svr.stop();
  13420. t.join();
  13421. ASSERT_FALSE(svr.is_running());
  13422. });
  13423. svr.wait_until_ready();
  13424. Client cli(HOST, PORT);
  13425. // Non-stream path
  13426. auto r1 = cli.Get(path);
  13427. ASSERT_TRUE(r1);
  13428. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13429. // Stream path
  13430. auto h = cli.open_stream("GET", path);
  13431. ASSERT_TRUE(h.is_valid());
  13432. EXPECT_EQ(r1->body, read_all(h));
  13433. }
  13434. // Helper to compress data with provided compressor type T
  13435. template <typename Compressor>
  13436. static std::string compress_payload_for_parity(const std::string &in) {
  13437. std::string out;
  13438. Compressor compressor;
  13439. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13440. [&](const char *data, size_t n) {
  13441. out.append(data, n);
  13442. return true;
  13443. });
  13444. EXPECT_TRUE(ok);
  13445. return out;
  13446. }
  13447. // Helper function for compression parity tests
  13448. template <typename Compressor>
  13449. static void test_compression_parity(const std::string &original,
  13450. const std::string &path,
  13451. const std::string &encoding) {
  13452. const std::string compressed =
  13453. compress_payload_for_parity<Compressor>(original);
  13454. Server svr;
  13455. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13456. res.set_content(compressed, "application/octet-stream");
  13457. res.set_header("Content-Encoding", encoding);
  13458. });
  13459. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13460. auto se = detail::scope_exit([&] {
  13461. svr.stop();
  13462. t.join();
  13463. ASSERT_FALSE(svr.is_running());
  13464. });
  13465. svr.wait_until_ready();
  13466. Client cli(HOST, PORT);
  13467. // Non-streaming
  13468. {
  13469. auto res = cli.Get(path);
  13470. ASSERT_TRUE(res);
  13471. EXPECT_EQ(StatusCode::OK_200, res->status);
  13472. EXPECT_EQ(original, res->body);
  13473. }
  13474. // Streaming
  13475. {
  13476. auto h = cli.open_stream("GET", path);
  13477. ASSERT_TRUE(h.is_valid());
  13478. EXPECT_EQ(original, read_all(h));
  13479. }
  13480. }
  13481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13482. TEST(ParityTest, Gzip) {
  13483. test_compression_parity<detail::gzip_compressor>(
  13484. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13485. }
  13486. #endif
  13487. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13488. TEST(ParityTest, Brotli) {
  13489. test_compression_parity<detail::brotli_compressor>(
  13490. "Hello, brotli parity test payload", "/parity-br", "br");
  13491. }
  13492. #endif
  13493. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13494. TEST(ParityTest, Zstd) {
  13495. test_compression_parity<detail::zstd_compressor>(
  13496. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13497. }
  13498. #endif
  13499. //==============================================================================
  13500. // New Stream API Tests
  13501. //==============================================================================
  13502. inline std::string read_body(httplib::stream::Result &result) {
  13503. std::string body;
  13504. while (result.next()) {
  13505. body.append(result.data(), result.size());
  13506. }
  13507. return body;
  13508. }
  13509. TEST(ClientConnectionTest, Basic) {
  13510. httplib::ClientConnection conn;
  13511. EXPECT_FALSE(conn.is_open());
  13512. conn.sock = 1;
  13513. EXPECT_TRUE(conn.is_open());
  13514. httplib::ClientConnection conn2(std::move(conn));
  13515. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13516. conn2.sock = INVALID_SOCKET;
  13517. }
  13518. // Unified test server for all stream::* tests
  13519. class StreamApiTest : public ::testing::Test {
  13520. protected:
  13521. void SetUp() override {
  13522. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13523. res.set_content("Hello World!", "text/plain");
  13524. });
  13525. svr_.Get("/echo-params",
  13526. [](const httplib::Request &req, httplib::Response &res) {
  13527. std::string r;
  13528. for (const auto &p : req.params) {
  13529. if (!r.empty()) r += "&";
  13530. r += p.first + "=" + p.second;
  13531. }
  13532. res.set_content(r, "text/plain");
  13533. });
  13534. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13535. res.set_content(req.body, req.get_header_value("Content-Type"));
  13536. });
  13537. svr_.Post("/echo-headers",
  13538. [](const httplib::Request &req, httplib::Response &res) {
  13539. std::string r;
  13540. for (const auto &h : req.headers)
  13541. r += h.first + ": " + h.second + "\n";
  13542. res.set_content(r, "text/plain");
  13543. });
  13544. svr_.Post("/echo-params",
  13545. [](const httplib::Request &req, httplib::Response &res) {
  13546. std::string r = "params:";
  13547. for (const auto &p : req.params)
  13548. r += p.first + "=" + p.second + ";";
  13549. res.set_content(r + " body:" + req.body, "text/plain");
  13550. });
  13551. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13552. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13553. });
  13554. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13555. res.set_content("PUT:" + req.body, "text/plain");
  13556. });
  13557. svr_.Patch("/echo",
  13558. [](const httplib::Request &req, httplib::Response &res) {
  13559. res.set_content("PATCH:" + req.body, "text/plain");
  13560. });
  13561. svr_.Delete(
  13562. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13563. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13564. "text/plain");
  13565. });
  13566. svr_.Get("/head-test",
  13567. [](const httplib::Request &, httplib::Response &res) {
  13568. res.set_content("body for HEAD", "text/plain");
  13569. });
  13570. svr_.Options("/options",
  13571. [](const httplib::Request &, httplib::Response &res) {
  13572. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13573. });
  13574. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13575. svr_.wait_until_ready();
  13576. }
  13577. void TearDown() override {
  13578. svr_.stop();
  13579. if (thread_.joinable()) thread_.join();
  13580. }
  13581. httplib::Server svr_;
  13582. std::thread thread_;
  13583. };
  13584. // stream::Get tests
  13585. TEST_F(StreamApiTest, GetBasic) {
  13586. httplib::Client cli(HOST, PORT);
  13587. auto result = httplib::stream::Get(cli, "/hello");
  13588. ASSERT_TRUE(result.is_valid());
  13589. EXPECT_EQ(200, result.status());
  13590. EXPECT_EQ("Hello World!", read_body(result));
  13591. }
  13592. TEST_F(StreamApiTest, GetWithParams) {
  13593. httplib::Client cli(HOST, PORT);
  13594. httplib::Params params{{"foo", "bar"}};
  13595. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13596. ASSERT_TRUE(result.is_valid());
  13597. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13598. }
  13599. TEST_F(StreamApiTest, GetConnectionError) {
  13600. httplib::Client cli(HOST, 9999);
  13601. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13602. }
  13603. TEST_F(StreamApiTest, Get404) {
  13604. httplib::Client cli(HOST, PORT);
  13605. auto result = httplib::stream::Get(cli, "/nonexistent");
  13606. EXPECT_TRUE(result.is_valid());
  13607. EXPECT_EQ(404, result.status());
  13608. }
  13609. // stream::Post tests
  13610. TEST_F(StreamApiTest, PostBasic) {
  13611. httplib::Client cli(HOST, PORT);
  13612. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13613. "application/json");
  13614. ASSERT_TRUE(result.is_valid());
  13615. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13616. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13617. }
  13618. TEST_F(StreamApiTest, PostWithHeaders) {
  13619. httplib::Client cli(HOST, PORT);
  13620. httplib::Headers headers{{"X-Custom", "value"}};
  13621. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13622. "text/plain");
  13623. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13624. }
  13625. TEST_F(StreamApiTest, PostWithParams) {
  13626. httplib::Client cli(HOST, PORT);
  13627. httplib::Params params{{"k", "v"}};
  13628. auto result =
  13629. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13630. auto body = read_body(result);
  13631. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13632. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13633. }
  13634. TEST_F(StreamApiTest, PostLarge) {
  13635. httplib::Client cli(HOST, PORT);
  13636. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13637. size_t total = 0;
  13638. while (result.next()) {
  13639. total += result.size();
  13640. }
  13641. EXPECT_EQ(100u * 1024u, total);
  13642. }
  13643. // stream::Put/Patch tests
  13644. TEST_F(StreamApiTest, PutAndPatch) {
  13645. httplib::Client cli(HOST, PORT);
  13646. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13647. EXPECT_EQ("PUT:test", read_body(put));
  13648. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13649. EXPECT_EQ("PATCH:test", read_body(patch));
  13650. }
  13651. // stream::Delete tests
  13652. TEST_F(StreamApiTest, Delete) {
  13653. httplib::Client cli(HOST, PORT);
  13654. auto del1 = httplib::stream::Delete(cli, "/resource");
  13655. EXPECT_EQ("Deleted", read_body(del1));
  13656. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13657. EXPECT_EQ("Deleted:data", read_body(del2));
  13658. }
  13659. // stream::Head/Options tests
  13660. TEST_F(StreamApiTest, HeadAndOptions) {
  13661. httplib::Client cli(HOST, PORT);
  13662. auto head = httplib::stream::Head(cli, "/head-test");
  13663. EXPECT_TRUE(head.is_valid());
  13664. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13665. auto opts = httplib::stream::Options(cli, "/options");
  13666. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13667. }
  13668. // SSL stream::* tests
  13669. #ifdef CPPHTTPLIB_SSL_ENABLED
  13670. class SSLStreamApiTest : public ::testing::Test {
  13671. protected:
  13672. void SetUp() override {
  13673. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13674. res.set_content("Hello SSL!", "text/plain");
  13675. });
  13676. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13677. res.set_content(req.body, "text/plain");
  13678. });
  13679. port_ = svr_.bind_to_any_port("127.0.0.1");
  13680. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13681. svr_.wait_until_ready();
  13682. }
  13683. void TearDown() override {
  13684. svr_.stop();
  13685. if (thread_.joinable()) thread_.join();
  13686. }
  13687. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13688. std::thread thread_;
  13689. int port_ = 0;
  13690. };
  13691. TEST_F(SSLStreamApiTest, GetAndPost) {
  13692. httplib::SSLClient cli("127.0.0.1", port_);
  13693. cli.enable_server_certificate_verification(false);
  13694. auto get = httplib::stream::Get(cli, "/hello");
  13695. EXPECT_EQ("Hello SSL!", read_body(get));
  13696. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13697. EXPECT_EQ("test", read_body(post));
  13698. }
  13699. #endif
  13700. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13701. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13702. // BodyReader
  13703. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13704. // Test that read timeout during streaming is detected
  13705. // Use a large content-length response where server delays mid-stream
  13706. Server svr;
  13707. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13708. // Send a large response with delay in the middle
  13709. res.set_content_provider(
  13710. 1000, // content_length
  13711. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13712. if (offset < 100) {
  13713. // Send first 100 bytes immediately
  13714. std::string data(100, 'A');
  13715. sink.write(data.c_str(), data.size());
  13716. return true;
  13717. }
  13718. // Then delay longer than client timeout
  13719. std::this_thread::sleep_for(std::chrono::seconds(3));
  13720. std::string data(900, 'B');
  13721. sink.write(data.c_str(), data.size());
  13722. return true;
  13723. });
  13724. });
  13725. auto port = 8091;
  13726. std::thread t([&]() { svr.listen("localhost", port); });
  13727. svr.wait_until_ready();
  13728. Client cli("localhost", port);
  13729. cli.set_read_timeout(1, 0); // 1 second timeout
  13730. auto handle = cli.open_stream("GET", "/slow-stream");
  13731. ASSERT_TRUE(handle.is_valid());
  13732. char buf[256];
  13733. ssize_t total = 0;
  13734. ssize_t n;
  13735. bool got_error = false;
  13736. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13737. total += n;
  13738. }
  13739. if (n < 0) {
  13740. got_error = true;
  13741. // Should be timeout or read error
  13742. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13743. handle.get_read_error() == Error::Read)
  13744. << "Actual error: " << to_string(handle.get_read_error());
  13745. }
  13746. // Either we got an error, or we got less data than expected
  13747. EXPECT_TRUE(got_error || total < 1000)
  13748. << "Expected timeout but got all " << total << " bytes";
  13749. svr.stop();
  13750. t.join();
  13751. }
  13752. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13753. // Test connection closed detection via BodyReader
  13754. Server svr;
  13755. std::atomic<bool> close_now{false};
  13756. svr.Get("/will-close", [&](const Request &, Response &res) {
  13757. res.set_content_provider(
  13758. 10000, // Large content_length that we won't fully send
  13759. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13760. if (offset < 100) {
  13761. std::string data(100, 'X');
  13762. sink.write(data.c_str(), data.size());
  13763. return true;
  13764. }
  13765. // Wait for signal then abort
  13766. while (!close_now) {
  13767. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13768. }
  13769. return false; // Abort - server will close connection
  13770. });
  13771. });
  13772. auto port = 8092;
  13773. std::thread t([&]() { svr.listen("localhost", port); });
  13774. svr.wait_until_ready();
  13775. Client cli("localhost", port);
  13776. auto handle = cli.open_stream("GET", "/will-close");
  13777. ASSERT_TRUE(handle.is_valid());
  13778. char buf[256];
  13779. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13780. EXPECT_GT(n, 0) << "First read should succeed";
  13781. // Signal server to close
  13782. close_now = true;
  13783. // Keep reading until error or EOF
  13784. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13785. // Keep reading
  13786. }
  13787. // Should get an error since content_length wasn't satisfied
  13788. if (n < 0) {
  13789. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13790. handle.get_read_error() == Error::Read)
  13791. << "Actual error: " << to_string(handle.get_read_error());
  13792. }
  13793. svr.stop();
  13794. t.join();
  13795. }
  13796. #ifdef CPPHTTPLIB_SSL_ENABLED
  13797. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13798. // Test that read timeout during SSL streaming is detected
  13799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13800. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13801. res.set_content_provider(
  13802. 1000, "text/plain",
  13803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13804. if (offset < 100) {
  13805. std::string data(100, 'A');
  13806. sink.write(data.c_str(), data.size());
  13807. return true;
  13808. }
  13809. std::this_thread::sleep_for(std::chrono::seconds(3));
  13810. std::string data(900, 'B');
  13811. sink.write(data.c_str(), data.size());
  13812. return true;
  13813. });
  13814. });
  13815. auto port = 8093;
  13816. std::thread t([&]() { svr.listen("localhost", port); });
  13817. svr.wait_until_ready();
  13818. SSLClient cli("localhost", port);
  13819. cli.enable_server_certificate_verification(false);
  13820. cli.set_read_timeout(1, 0); // 1 second timeout
  13821. auto handle = cli.open_stream("GET", "/slow-stream");
  13822. ASSERT_TRUE(handle.is_valid());
  13823. char buf[256];
  13824. ssize_t total = 0;
  13825. ssize_t n;
  13826. bool got_error = false;
  13827. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13828. total += n;
  13829. }
  13830. if (n < 0) {
  13831. got_error = true;
  13832. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13833. handle.get_read_error() == Error::Read)
  13834. << "Actual error: " << to_string(handle.get_read_error());
  13835. }
  13836. EXPECT_TRUE(got_error || total < 1000)
  13837. << "Expected timeout but got all " << total << " bytes";
  13838. svr.stop();
  13839. t.join();
  13840. }
  13841. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13842. // Test SSL connection closed detection
  13843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. std::atomic<bool> close_now{false};
  13845. svr.Get("/will-close", [&](const Request &, Response &res) {
  13846. res.set_content_provider(
  13847. 10000, "text/plain",
  13848. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13849. if (offset < 100) {
  13850. std::string data(100, 'X');
  13851. sink.write(data.c_str(), data.size());
  13852. return true;
  13853. }
  13854. while (!close_now) {
  13855. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13856. }
  13857. return false;
  13858. });
  13859. });
  13860. auto port = 8094;
  13861. std::thread t([&]() { svr.listen("localhost", port); });
  13862. svr.wait_until_ready();
  13863. SSLClient cli("localhost", port);
  13864. cli.enable_server_certificate_verification(false);
  13865. auto handle = cli.open_stream("GET", "/will-close");
  13866. ASSERT_TRUE(handle.is_valid());
  13867. char buf[256];
  13868. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13869. EXPECT_GT(n, 0);
  13870. // Signal server to close
  13871. close_now = true;
  13872. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13873. // Keep reading
  13874. }
  13875. if (n < 0) {
  13876. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13877. handle.get_read_error() == Error::Read)
  13878. << "Actual error: " << to_string(handle.get_read_error());
  13879. }
  13880. svr.stop();
  13881. t.join();
  13882. }
  13883. #endif
  13884. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13885. using namespace httplib;
  13886. // Create a test file
  13887. const char *fname = "etag_testfile.txt";
  13888. const char *content = "etag-content";
  13889. {
  13890. std::ofstream ofs(fname);
  13891. ofs << content;
  13892. ASSERT_TRUE(ofs.good());
  13893. }
  13894. Server svr;
  13895. svr.set_mount_point("/static", ".");
  13896. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13897. svr.wait_until_ready();
  13898. Client cli(HOST, PORT);
  13899. // First request: should get 200 with ETag header
  13900. auto res1 = cli.Get("/static/etag_testfile.txt");
  13901. ASSERT_TRUE(res1);
  13902. ASSERT_EQ(200, res1->status);
  13903. ASSERT_TRUE(res1->has_header("ETag"));
  13904. std::string etag = res1->get_header_value("ETag");
  13905. EXPECT_FALSE(etag.empty());
  13906. // Verify ETag format: W/"hex-hex"
  13907. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13908. EXPECT_EQ('W', etag[0]);
  13909. EXPECT_EQ('/', etag[1]);
  13910. EXPECT_EQ('"', etag[2]);
  13911. EXPECT_EQ('"', etag.back());
  13912. // Exact match: expect 304 Not Modified
  13913. Headers h2 = {{"If-None-Match", etag}};
  13914. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13915. ASSERT_TRUE(res2);
  13916. EXPECT_EQ(304, res2->status);
  13917. // Wildcard match: expect 304 Not Modified
  13918. Headers h3 = {{"If-None-Match", "*"}};
  13919. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13920. ASSERT_TRUE(res3);
  13921. EXPECT_EQ(304, res3->status);
  13922. // Non-matching ETag: expect 200
  13923. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13924. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13925. ASSERT_TRUE(res4);
  13926. EXPECT_EQ(200, res4->status);
  13927. // Multiple ETags with one matching: expect 304
  13928. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13929. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13930. ASSERT_TRUE(res5);
  13931. EXPECT_EQ(304, res5->status);
  13932. svr.stop();
  13933. t.join();
  13934. std::remove(fname);
  13935. }
  13936. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13937. using namespace httplib;
  13938. Server svr;
  13939. svr.set_mount_point("/static", ".");
  13940. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13941. svr.wait_until_ready();
  13942. Client cli(HOST, PORT);
  13943. // Send If-None-Match: * to a non-existent file
  13944. Headers h = {{"If-None-Match", "*"}};
  13945. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13946. ASSERT_TRUE(res);
  13947. EXPECT_EQ(404, res->status);
  13948. svr.stop();
  13949. t.join();
  13950. }
  13951. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13952. using namespace httplib;
  13953. // Create a test file
  13954. const char *fname = "etag_boundary_testfile.txt";
  13955. const char *content = "boundary-test";
  13956. {
  13957. std::ofstream ofs(fname);
  13958. ofs << content;
  13959. ASSERT_TRUE(ofs.good());
  13960. }
  13961. Server svr;
  13962. svr.set_mount_point("/static", ".");
  13963. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13964. svr.wait_until_ready();
  13965. Client cli(HOST, PORT);
  13966. // Get the actual ETag
  13967. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13968. ASSERT_TRUE(res1);
  13969. ASSERT_EQ(200, res1->status);
  13970. ASSERT_TRUE(res1->has_header("ETag"));
  13971. std::string etag = res1->get_header_value("ETag");
  13972. // Test 1: Very long ETag value (longer than actual ETag)
  13973. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13974. Headers h1 = {{"If-None-Match", "W/"
  13975. "\"very-long-etag-value-that-is-much-longer-"
  13976. "than-the-actual-etag-value\""}};
  13977. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13978. ASSERT_TRUE(res2);
  13979. EXPECT_EQ(200, res2->status); // Should not match
  13980. // Test 2: Long string followed by wildcard
  13981. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13982. // string)
  13983. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13984. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13985. ASSERT_TRUE(res3);
  13986. EXPECT_EQ(304, res3->status); // Should match on "*"
  13987. // Test 3: Wildcard followed by long string
  13988. // Should match on "*" immediately and return 304
  13989. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13990. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13991. ASSERT_TRUE(res4);
  13992. EXPECT_EQ(304, res4->status); // Should match on "*"
  13993. // Test 4: Multiple long non-matching values
  13994. // Should NOT match and return 200 (test that all comparisons are safe)
  13995. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13996. "W/\"second-long-non-matching-value\", "
  13997. "W/\"third-long-non-matching-value\""}};
  13998. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13999. ASSERT_TRUE(res5);
  14000. EXPECT_EQ(200, res5->status); // Should not match
  14001. // Test 5: Single character that is not "*" (edge case)
  14002. Headers h5 = {{"If-None-Match", "X"}};
  14003. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14004. ASSERT_TRUE(res6);
  14005. EXPECT_EQ(200, res6->status); // Should not match
  14006. svr.stop();
  14007. t.join();
  14008. std::remove(fname);
  14009. }
  14010. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14011. using namespace httplib;
  14012. // Create a test file
  14013. const char *fname = "ims_testfile.txt";
  14014. const char *content = "if-modified-since-test";
  14015. {
  14016. std::ofstream ofs(fname);
  14017. ofs << content;
  14018. ASSERT_TRUE(ofs.good());
  14019. }
  14020. Server svr;
  14021. svr.set_mount_point("/static", ".");
  14022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14023. svr.wait_until_ready();
  14024. Client cli(HOST, PORT);
  14025. // First request: should get 200 with Last-Modified header
  14026. auto res1 = cli.Get("/static/ims_testfile.txt");
  14027. ASSERT_TRUE(res1);
  14028. ASSERT_EQ(200, res1->status);
  14029. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14030. std::string last_modified = res1->get_header_value("Last-Modified");
  14031. EXPECT_FALSE(last_modified.empty());
  14032. // If-Modified-Since with same time: expect 304
  14033. Headers h2 = {{"If-Modified-Since", last_modified}};
  14034. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14035. ASSERT_TRUE(res2);
  14036. EXPECT_EQ(304, res2->status);
  14037. // If-Modified-Since with future time: expect 304
  14038. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14039. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14040. ASSERT_TRUE(res3);
  14041. EXPECT_EQ(304, res3->status);
  14042. // If-Modified-Since with past time: expect 200
  14043. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14044. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14045. ASSERT_TRUE(res4);
  14046. EXPECT_EQ(200, res4->status);
  14047. // If-None-Match takes precedence over If-Modified-Since
  14048. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14049. ASSERT_TRUE(res1->has_header("ETag"));
  14050. std::string etag = res1->get_header_value("ETag");
  14051. Headers h5 = {{"If-None-Match", etag},
  14052. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14053. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14054. ASSERT_TRUE(res5);
  14055. EXPECT_EQ(304, res5->status);
  14056. svr.stop();
  14057. t.join();
  14058. std::remove(fname);
  14059. }
  14060. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14061. using namespace httplib;
  14062. Server svr;
  14063. // Endpoint that returns compressible content
  14064. svr.Get("/compressible", [](const Request &, Response &res) {
  14065. // Return a large enough body to trigger compression
  14066. std::string body(1000, 'a');
  14067. res.set_content(body, "text/plain");
  14068. });
  14069. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14070. svr.wait_until_ready();
  14071. Client cli(HOST, PORT);
  14072. // Request with gzip support: should get Vary header when compressed
  14073. cli.set_compress(true);
  14074. auto res1 = cli.Get("/compressible");
  14075. ASSERT_TRUE(res1);
  14076. EXPECT_EQ(200, res1->status);
  14077. // If Content-Encoding is set, Vary should also be set
  14078. if (res1->has_header("Content-Encoding")) {
  14079. EXPECT_TRUE(res1->has_header("Vary"));
  14080. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14081. }
  14082. // Request without Accept-Encoding header: should not have compression
  14083. Headers h_no_compress;
  14084. auto res2 = cli.Get("/compressible", h_no_compress);
  14085. ASSERT_TRUE(res2);
  14086. EXPECT_EQ(200, res2->status);
  14087. // Verify Vary header is present when compression is applied
  14088. // (the exact behavior depends on server configuration)
  14089. svr.stop();
  14090. t.join();
  14091. }
  14092. TEST(ETagTest, IfRangeWithETag) {
  14093. using namespace httplib;
  14094. // Create a test file with known content
  14095. const char *fname = "if_range_testfile.txt";
  14096. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14097. {
  14098. std::ofstream ofs(fname);
  14099. ofs << content;
  14100. ASSERT_TRUE(ofs.good());
  14101. }
  14102. Server svr;
  14103. svr.set_mount_point("/static", ".");
  14104. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14105. svr.wait_until_ready();
  14106. Client cli(HOST, PORT);
  14107. // First request: get ETag
  14108. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14109. ASSERT_TRUE(res1);
  14110. ASSERT_EQ(200, res1->status);
  14111. ASSERT_TRUE(res1->has_header("ETag"));
  14112. std::string etag = res1->get_header_value("ETag");
  14113. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14114. // Since our server generates weak ETags (W/"..."), If-Range with our
  14115. // ETag should NOT result in partial content - it should return full content.
  14116. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14117. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14118. ASSERT_TRUE(res2);
  14119. // Weak ETag in If-Range -> full content (200), not partial (206)
  14120. EXPECT_EQ(200, res2->status);
  14121. EXPECT_EQ(content, res2->body);
  14122. EXPECT_FALSE(res2->has_header("Content-Range"));
  14123. // Range request with non-matching If-Range (ETag): should get 200 (full
  14124. // content)
  14125. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14126. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14127. ASSERT_TRUE(res3);
  14128. EXPECT_EQ(200, res3->status);
  14129. EXPECT_EQ(content, res3->body);
  14130. EXPECT_FALSE(res3->has_header("Content-Range"));
  14131. // Range request with strong ETag (hypothetical - our server doesn't generate
  14132. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14133. // should return full content)
  14134. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14135. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14136. ASSERT_TRUE(res4);
  14137. EXPECT_EQ(200, res4->status);
  14138. EXPECT_EQ(content, res4->body);
  14139. EXPECT_FALSE(res4->has_header("Content-Range"));
  14140. svr.stop();
  14141. t.join();
  14142. std::remove(fname);
  14143. }
  14144. TEST(ETagTest, IfRangeWithDate) {
  14145. using namespace httplib;
  14146. // Create a test file
  14147. const char *fname = "if_range_date_testfile.txt";
  14148. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14149. {
  14150. std::ofstream ofs(fname);
  14151. ofs << content;
  14152. ASSERT_TRUE(ofs.good());
  14153. }
  14154. Server svr;
  14155. svr.set_mount_point("/static", ".");
  14156. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14157. svr.wait_until_ready();
  14158. Client cli(HOST, PORT);
  14159. // First request: get Last-Modified
  14160. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14161. ASSERT_TRUE(res1);
  14162. ASSERT_EQ(200, res1->status);
  14163. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14164. std::string last_modified = res1->get_header_value("Last-Modified");
  14165. // Range request with matching If-Range (date): should get 206
  14166. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14167. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14168. ASSERT_TRUE(res2);
  14169. EXPECT_EQ(206, res2->status);
  14170. EXPECT_EQ("FGHIJ", res2->body);
  14171. // Range request with old If-Range date: should get 200 (full content)
  14172. Headers h3 = {{"Range", "bytes=5-9"},
  14173. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14174. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14175. ASSERT_TRUE(res3);
  14176. EXPECT_EQ(200, res3->status);
  14177. EXPECT_EQ(content, res3->body);
  14178. // Range request with future If-Range date: should get 206
  14179. Headers h4 = {{"Range", "bytes=0-4"},
  14180. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14181. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14182. ASSERT_TRUE(res4);
  14183. EXPECT_EQ(206, res4->status);
  14184. EXPECT_EQ("ABCDE", res4->body);
  14185. svr.stop();
  14186. t.join();
  14187. std::remove(fname);
  14188. }
  14189. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14190. using namespace httplib;
  14191. const char *fname = "etag_malformed.txt";
  14192. const char *content = "malformed-etag";
  14193. {
  14194. std::ofstream ofs(fname);
  14195. ofs << content;
  14196. ASSERT_TRUE(ofs.good());
  14197. }
  14198. Server svr;
  14199. svr.set_mount_point("/static", ".");
  14200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14201. svr.wait_until_ready();
  14202. Client cli(HOST, PORT);
  14203. // baseline: should get 200 and an ETag
  14204. auto res1 = cli.Get("/static/etag_malformed.txt");
  14205. ASSERT_TRUE(res1);
  14206. ASSERT_EQ(200, res1->status);
  14207. ASSERT_TRUE(res1->has_header("ETag"));
  14208. // Malformed ETag value (missing quotes) should be treated as non-matching
  14209. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14210. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14211. ASSERT_TRUE(res_bad);
  14212. EXPECT_EQ(200, res_bad->status);
  14213. // Whitespace-only header value should be considered invalid / non-matching
  14214. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14215. "Host: localhost\r\n"
  14216. "If-None-Match: \r\n"
  14217. "Connection: close\r\n"
  14218. "\r\n";
  14219. std::string out;
  14220. ASSERT_TRUE(send_request(5, raw_req, &out));
  14221. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14222. svr.stop();
  14223. t.join();
  14224. std::remove(fname);
  14225. }
  14226. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14227. using namespace httplib;
  14228. const char *fname = "ims_invalid_format.txt";
  14229. const char *content = "ims-bad-format";
  14230. {
  14231. std::ofstream ofs(fname);
  14232. ofs << content;
  14233. ASSERT_TRUE(ofs.good());
  14234. }
  14235. Server svr;
  14236. svr.set_mount_point("/static", ".");
  14237. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14238. svr.wait_until_ready();
  14239. Client cli(HOST, PORT);
  14240. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14241. ASSERT_TRUE(res1);
  14242. ASSERT_EQ(200, res1->status);
  14243. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14244. // If-Modified-Since with invalid format should not result in 304
  14245. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14246. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14247. ASSERT_TRUE(res_bad);
  14248. EXPECT_EQ(200, res_bad->status);
  14249. // If-Range with invalid date format should be treated as mismatch -> full
  14250. // content (200)
  14251. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14252. {"If-Range", "invalid-date"}};
  14253. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14254. ASSERT_TRUE(res_ifrange);
  14255. EXPECT_EQ(200, res_ifrange->status);
  14256. svr.stop();
  14257. t.join();
  14258. std::remove(fname);
  14259. }
  14260. TEST(ETagTest, IfRangeWithMalformedETag) {
  14261. using namespace httplib;
  14262. const char *fname = "ifrange_malformed.txt";
  14263. const std::string content = "0123456789";
  14264. {
  14265. std::ofstream ofs(fname);
  14266. ofs << content;
  14267. ASSERT_TRUE(ofs.good());
  14268. }
  14269. Server svr;
  14270. svr.set_mount_point("/static", ".");
  14271. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14272. svr.wait_until_ready();
  14273. Client cli(HOST, PORT);
  14274. // First request: get ETag
  14275. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14276. ASSERT_TRUE(res1);
  14277. ASSERT_EQ(200, res1->status);
  14278. ASSERT_TRUE(res1->has_header("ETag"));
  14279. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14280. // full content (200)
  14281. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14282. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14283. ASSERT_TRUE(res2);
  14284. EXPECT_EQ(200, res2->status);
  14285. EXPECT_EQ(content, res2->body);
  14286. svr.stop();
  14287. t.join();
  14288. std::remove(fname);
  14289. }
  14290. TEST(ETagTest, ExtremeLargeDateValues) {
  14291. using namespace httplib;
  14292. const char *fname = "ims_extreme_date.txt";
  14293. const char *content = "ims-extreme-date";
  14294. {
  14295. std::ofstream ofs(fname);
  14296. ofs << content;
  14297. ASSERT_TRUE(ofs.good());
  14298. }
  14299. Server svr;
  14300. svr.set_mount_point("/static", ".");
  14301. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14302. svr.wait_until_ready();
  14303. Client cli(HOST, PORT);
  14304. auto res1 = cli.Get(std::string("/static/") + fname);
  14305. ASSERT_TRUE(res1);
  14306. ASSERT_EQ(200, res1->status);
  14307. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14308. // Extremely large year that may overflow date parsing routines.
  14309. Headers h_large_date = {
  14310. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14311. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14312. ASSERT_TRUE(res_bad);
  14313. // Expect server to treat this as invalid/mismatch and return full content
  14314. EXPECT_EQ(200, res_bad->status);
  14315. // If-Range with extremely large date should be treated as mismatch -> full
  14316. // content (200)
  14317. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14318. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14319. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14320. ASSERT_TRUE(res_ifrange);
  14321. EXPECT_EQ(200, res_ifrange->status);
  14322. svr.stop();
  14323. t.join();
  14324. std::remove(fname);
  14325. }
  14326. TEST(ETagTest, NegativeFileModificationTime) {
  14327. using namespace httplib;
  14328. const char *fname = "ims_negative_mtime.txt";
  14329. const std::string content = "negative-mtime";
  14330. {
  14331. std::ofstream ofs(fname);
  14332. ofs << content;
  14333. ASSERT_TRUE(ofs.good());
  14334. }
  14335. // Try to set file mtime to a negative value. This may fail on some
  14336. // platforms/filesystems; if it fails, the test will still verify server
  14337. // behaves safely by performing a regular conditional request.
  14338. #if defined(__APPLE__) || defined(__linux__)
  14339. bool set_negative = false;
  14340. do {
  14341. struct timeval times[2];
  14342. // access time: now
  14343. times[0].tv_sec = time(nullptr);
  14344. times[0].tv_usec = 0;
  14345. // modification time: negative (e.g., -1)
  14346. times[1].tv_sec = -1;
  14347. times[1].tv_usec = 0;
  14348. if (utimes(fname, times) == 0) { set_negative = true; }
  14349. } while (0);
  14350. #else
  14351. bool set_negative = false;
  14352. #endif
  14353. Server svr;
  14354. svr.set_mount_point("/static", ".");
  14355. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14356. svr.wait_until_ready();
  14357. Client cli(HOST, PORT);
  14358. auto res1 = cli.Get(std::string("/static/") + fname);
  14359. ASSERT_TRUE(res1);
  14360. ASSERT_EQ(200, res1->status);
  14361. bool has_last_modified = res1->has_header("Last-Modified");
  14362. std::string last_modified;
  14363. if (has_last_modified) {
  14364. last_modified = res1->get_header_value("Last-Modified");
  14365. }
  14366. if (set_negative) {
  14367. // If we successfully set a negative mtime, ensure server returns a
  14368. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14369. // with an old date and ensure server handles it without crash.
  14370. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14371. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14372. ASSERT_TRUE(res2);
  14373. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14374. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14375. } else {
  14376. // Could not set negative mtime on this platform; fall back to verifying
  14377. // that normal invalid/malformed dates are treated safely (non-304).
  14378. Headers h_bad_date = {
  14379. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14380. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14381. ASSERT_TRUE(res_bad);
  14382. EXPECT_EQ(200, res_bad->status);
  14383. }
  14384. svr.stop();
  14385. t.join();
  14386. std::remove(fname);
  14387. }
  14388. //==============================================================================
  14389. // SSE Parsing Tests
  14390. //==============================================================================
  14391. class SSEParsingTest : public ::testing::Test {
  14392. protected:
  14393. // Test helper that mimics SSE parsing behavior
  14394. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14395. int &retry_ms) {
  14396. // Blank line signals end of event
  14397. if (line.empty() || line == "\r") { return true; }
  14398. // Lines starting with ':' are comments (ignored)
  14399. if (!line.empty() && line[0] == ':') { return false; }
  14400. // Find the colon separator
  14401. auto colon_pos = line.find(':');
  14402. if (colon_pos == std::string::npos) {
  14403. // Line with no colon is treated as field name with empty value
  14404. return false;
  14405. }
  14406. std::string field = line.substr(0, colon_pos);
  14407. std::string value;
  14408. // Value starts after colon, skip optional single space
  14409. if (colon_pos + 1 < line.size()) {
  14410. size_t value_start = colon_pos + 1;
  14411. if (line[value_start] == ' ') { value_start++; }
  14412. value = line.substr(value_start);
  14413. // Remove trailing \r if present
  14414. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14415. }
  14416. // Handle known fields
  14417. if (field == "event") {
  14418. msg.event = value;
  14419. } else if (field == "data") {
  14420. // Multiple data lines are concatenated with newlines
  14421. if (!msg.data.empty()) { msg.data += "\n"; }
  14422. msg.data += value;
  14423. } else if (field == "id") {
  14424. // Empty id is valid (clears the last event ID)
  14425. msg.id = value;
  14426. } else if (field == "retry") {
  14427. // Parse retry interval in milliseconds
  14428. {
  14429. int v = 0;
  14430. auto res =
  14431. detail::from_chars(value.data(), value.data() + value.size(), v);
  14432. if (res.ec == std::errc{}) { retry_ms = v; }
  14433. }
  14434. }
  14435. // Unknown fields are ignored per SSE spec
  14436. return false;
  14437. }
  14438. };
  14439. // Test: Single-line data
  14440. TEST_F(SSEParsingTest, SingleLineData) {
  14441. sse::SSEMessage msg;
  14442. int retry_ms = 3000;
  14443. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14444. EXPECT_EQ(msg.data, "hello");
  14445. EXPECT_EQ(msg.event, "message");
  14446. // Blank line ends event
  14447. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14448. }
  14449. // Test: Multi-line data
  14450. TEST_F(SSEParsingTest, MultiLineData) {
  14451. sse::SSEMessage msg;
  14452. int retry_ms = 3000;
  14453. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14454. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14455. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14456. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14457. }
  14458. // Test: Custom event types
  14459. TEST_F(SSEParsingTest, CustomEventType) {
  14460. sse::SSEMessage msg;
  14461. int retry_ms = 3000;
  14462. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14463. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14464. EXPECT_EQ(msg.event, "update");
  14465. EXPECT_EQ(msg.data, "payload");
  14466. }
  14467. // Test: Event ID handling
  14468. TEST_F(SSEParsingTest, EventIdHandling) {
  14469. sse::SSEMessage msg;
  14470. int retry_ms = 3000;
  14471. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14472. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14473. EXPECT_EQ(msg.id, "12345");
  14474. }
  14475. // Test: Empty event ID (clears last event ID)
  14476. TEST_F(SSEParsingTest, EmptyEventId) {
  14477. sse::SSEMessage msg;
  14478. msg.id = "previous";
  14479. int retry_ms = 3000;
  14480. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14481. EXPECT_EQ(msg.id, "");
  14482. }
  14483. // Test: Retry field parsing
  14484. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14485. sse::SSEMessage msg;
  14486. int retry_ms = 3000;
  14487. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14488. EXPECT_EQ(retry_ms, 5000);
  14489. }
  14490. // Test: Invalid retry value
  14491. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14492. sse::SSEMessage msg;
  14493. int retry_ms = 3000;
  14494. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14495. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14496. }
  14497. // Test: Comments (lines starting with :)
  14498. TEST_F(SSEParsingTest, CommentsIgnored) {
  14499. sse::SSEMessage msg;
  14500. int retry_ms = 3000;
  14501. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14502. EXPECT_EQ(msg.data, "");
  14503. EXPECT_EQ(msg.event, "message");
  14504. }
  14505. // Test: Colon in value
  14506. TEST_F(SSEParsingTest, ColonInValue) {
  14507. sse::SSEMessage msg;
  14508. int retry_ms = 3000;
  14509. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14510. EXPECT_EQ(msg.data, "hello:world:test");
  14511. }
  14512. // Test: Line with no colon (field name only)
  14513. TEST_F(SSEParsingTest, FieldNameOnly) {
  14514. sse::SSEMessage msg;
  14515. int retry_ms = 3000;
  14516. // According to SSE spec, this is treated as field name with empty value
  14517. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14518. // Since we don't recognize "data" without colon, data should be empty
  14519. EXPECT_EQ(msg.data, "");
  14520. }
  14521. // Test: Trailing \r handling
  14522. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14523. sse::SSEMessage msg;
  14524. int retry_ms = 3000;
  14525. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14526. EXPECT_EQ(msg.data, "hello");
  14527. }
  14528. // Test: Unknown fields ignored
  14529. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14530. sse::SSEMessage msg;
  14531. int retry_ms = 3000;
  14532. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14533. EXPECT_EQ(msg.data, "");
  14534. EXPECT_EQ(msg.event, "message");
  14535. }
  14536. // Test: Space after colon is optional
  14537. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14538. sse::SSEMessage msg1, msg2;
  14539. int retry_ms = 3000;
  14540. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14541. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14542. EXPECT_EQ(msg1.data, "hello");
  14543. EXPECT_EQ(msg2.data, "hello");
  14544. }
  14545. // Test: SSEMessage clear
  14546. TEST_F(SSEParsingTest, MessageClear) {
  14547. sse::SSEMessage msg;
  14548. msg.event = "custom";
  14549. msg.data = "some data";
  14550. msg.id = "123";
  14551. msg.clear();
  14552. EXPECT_EQ(msg.event, "message");
  14553. EXPECT_EQ(msg.data, "");
  14554. EXPECT_EQ(msg.id, "");
  14555. }
  14556. // Test: Complete event parsing
  14557. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14558. sse::SSEMessage msg;
  14559. int retry_ms = 3000;
  14560. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14561. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14562. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14563. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14564. // Blank line ends event
  14565. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14566. EXPECT_EQ(msg.event, "notification");
  14567. EXPECT_EQ(msg.id, "evt-42");
  14568. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14569. EXPECT_EQ(retry_ms, 1000);
  14570. }
  14571. //==============================================================================
  14572. // Integration Tests with Server
  14573. //==============================================================================
  14574. class SSEIntegrationTest : public ::testing::Test {
  14575. protected:
  14576. void SetUp() override {
  14577. stop_server_.store(false);
  14578. events_.clear();
  14579. server_ = httplib::detail::make_unique<Server>();
  14580. setup_server();
  14581. start_server();
  14582. }
  14583. void TearDown() override {
  14584. stop_server_.store(true);
  14585. event_cv_.notify_all();
  14586. server_->stop();
  14587. if (server_thread_.joinable()) { server_thread_.join(); }
  14588. }
  14589. void setup_server() {
  14590. // Simple SSE endpoint
  14591. server_->Get("/events", [this](const Request &req, Response &res) {
  14592. auto last_id = req.get_header_value("Last-Event-ID");
  14593. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14594. res.set_chunked_content_provider(
  14595. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14596. std::unique_lock<std::mutex> lock(event_mutex_);
  14597. if (event_cv_.wait_for(
  14598. lock, std::chrono::milliseconds(200), [this] {
  14599. return !events_.empty() || stop_server_.load();
  14600. })) {
  14601. if (stop_server_.load()) { return false; }
  14602. if (!events_.empty()) {
  14603. std::string event = events_.front();
  14604. events_.erase(events_.begin());
  14605. sink.write(event.data(), event.size());
  14606. return true;
  14607. }
  14608. }
  14609. return !stop_server_.load();
  14610. });
  14611. });
  14612. // Endpoint that returns error
  14613. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14614. res.status = 500;
  14615. res.set_content("Internal Server Error", "text/plain");
  14616. });
  14617. // Endpoint for custom event types
  14618. server_->Get("/custom-events", [](const Request &, Response &res) {
  14619. res.set_chunked_content_provider(
  14620. "text/event-stream", [](size_t offset, DataSink &sink) {
  14621. if (offset == 0) {
  14622. std::string event = "event: update\ndata: updated\n\n"
  14623. "event: delete\ndata: deleted\n\n";
  14624. sink.write(event.data(), event.size());
  14625. }
  14626. return false; // End stream after sending
  14627. });
  14628. });
  14629. }
  14630. void start_server() {
  14631. port_ = server_->bind_to_any_port(HOST);
  14632. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14633. // Wait for server to start
  14634. while (!server_->is_running()) {
  14635. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14636. }
  14637. }
  14638. int get_port() const { return port_; }
  14639. void send_event(const std::string &event) {
  14640. std::lock_guard<std::mutex> lock(event_mutex_);
  14641. events_.push_back(event);
  14642. event_cv_.notify_all();
  14643. }
  14644. std::unique_ptr<Server> server_;
  14645. std::thread server_thread_;
  14646. std::mutex event_mutex_;
  14647. std::condition_variable event_cv_;
  14648. std::vector<std::string> events_;
  14649. std::atomic<bool> stop_server_{false};
  14650. std::string last_received_event_id_;
  14651. int port_ = 0;
  14652. };
  14653. // Test: Successful connection and on_open callback
  14654. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14655. // Add a simple endpoint that sends one event and closes
  14656. server_->Get("/simple-event", [](const Request &, Response &res) {
  14657. res.set_chunked_content_provider(
  14658. "text/event-stream", [](size_t offset, DataSink &sink) {
  14659. if (offset == 0) {
  14660. std::string event = "data: hello\n\n";
  14661. sink.write(event.data(), event.size());
  14662. }
  14663. return false; // Close stream after sending
  14664. });
  14665. });
  14666. Client client("localhost", get_port());
  14667. sse::SSEClient sse(client, "/simple-event");
  14668. std::atomic<bool> open_called{false};
  14669. std::atomic<bool> message_received{false};
  14670. sse.on_open([&open_called]() { open_called.store(true); });
  14671. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14672. if (msg.data == "hello") { message_received.store(true); }
  14673. });
  14674. sse.set_reconnect_interval(100);
  14675. sse.set_max_reconnect_attempts(1);
  14676. // Start async
  14677. sse.start_async();
  14678. // Wait for message to be processed
  14679. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14680. sse.stop();
  14681. EXPECT_TRUE(open_called.load());
  14682. EXPECT_TRUE(message_received.load());
  14683. }
  14684. // Test: on_message callback
  14685. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14686. // Endpoint that sends multiple events then closes
  14687. server_->Get("/multi-event", [](const Request &, Response &res) {
  14688. res.set_chunked_content_provider(
  14689. "text/event-stream", [](size_t offset, DataSink &sink) {
  14690. if (offset == 0) {
  14691. std::string events = "data: message1\n\ndata: message2\n\n";
  14692. sink.write(events.data(), events.size());
  14693. }
  14694. return false;
  14695. });
  14696. });
  14697. Client client("localhost", get_port());
  14698. sse::SSEClient sse(client, "/multi-event");
  14699. std::vector<std::string> received_messages;
  14700. std::mutex messages_mutex;
  14701. sse.on_message([&](const sse::SSEMessage &msg) {
  14702. std::lock_guard<std::mutex> lock(messages_mutex);
  14703. received_messages.push_back(msg.data);
  14704. });
  14705. sse.set_reconnect_interval(100);
  14706. sse.set_max_reconnect_attempts(1);
  14707. sse.start_async();
  14708. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14709. sse.stop();
  14710. std::lock_guard<std::mutex> lock(messages_mutex);
  14711. EXPECT_GE(received_messages.size(), 2u);
  14712. if (received_messages.size() >= 2) {
  14713. EXPECT_EQ(received_messages[0], "message1");
  14714. EXPECT_EQ(received_messages[1], "message2");
  14715. }
  14716. }
  14717. // Test: on_event for specific types
  14718. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14719. Client client("localhost", get_port());
  14720. sse::SSEClient sse(client, "/custom-events");
  14721. std::atomic<bool> update_received{false};
  14722. std::atomic<bool> delete_received{false};
  14723. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14724. if (msg.data == "updated") { update_received.store(true); }
  14725. });
  14726. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14727. if (msg.data == "deleted") { delete_received.store(true); }
  14728. });
  14729. sse.set_max_reconnect_attempts(1);
  14730. sse.start_async();
  14731. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14732. sse.stop();
  14733. EXPECT_TRUE(update_received.load());
  14734. EXPECT_TRUE(delete_received.load());
  14735. }
  14736. // Test: on_error callback on connection failure
  14737. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14738. // Connect to a non-existent port
  14739. Client client("localhost", 59999);
  14740. sse::SSEClient sse(client, "/events");
  14741. std::atomic<bool> error_called{false};
  14742. Error received_error = Error::Success;
  14743. sse.on_error([&](Error err) {
  14744. error_called.store(true);
  14745. received_error = err;
  14746. });
  14747. sse.set_reconnect_interval(50);
  14748. sse.set_max_reconnect_attempts(1);
  14749. sse.start_async();
  14750. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14751. sse.stop();
  14752. EXPECT_TRUE(error_called.load());
  14753. EXPECT_NE(received_error, Error::Success);
  14754. }
  14755. // Test: Last-Event-ID header sent on reconnect
  14756. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14757. // Endpoint that sends event with ID
  14758. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14759. res.set_chunked_content_provider(
  14760. "text/event-stream", [](size_t offset, DataSink &sink) {
  14761. if (offset == 0) {
  14762. std::string event = "id: evt-123\ndata: test\n\n";
  14763. sink.write(event.data(), event.size());
  14764. }
  14765. return false;
  14766. });
  14767. });
  14768. Client client("localhost", get_port());
  14769. sse::SSEClient sse(client, "/event-with-id");
  14770. std::atomic<bool> id_received{false};
  14771. sse.on_message([&](const sse::SSEMessage &msg) {
  14772. if (!msg.id.empty()) { id_received.store(true); }
  14773. });
  14774. sse.set_reconnect_interval(100);
  14775. sse.set_max_reconnect_attempts(1);
  14776. sse.start_async();
  14777. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14778. sse.stop();
  14779. EXPECT_TRUE(id_received.load());
  14780. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14781. }
  14782. // Test: Manual stop
  14783. TEST_F(SSEIntegrationTest, ManualStop) {
  14784. // Endpoint that sends one event and stays open briefly
  14785. std::atomic<bool> handler_running{true};
  14786. server_->Get("/stay-open", [&handler_running](const Request &,
  14787. Response &res) {
  14788. res.set_chunked_content_provider(
  14789. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14790. if (offset == 0) {
  14791. std::string event = "data: connected\n\n";
  14792. sink.write(event.data(), event.size());
  14793. }
  14794. // Keep connection open while handler_running is true
  14795. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14796. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14797. }
  14798. return false;
  14799. });
  14800. });
  14801. Client client("localhost", get_port());
  14802. sse::SSEClient sse(client, "/stay-open");
  14803. std::atomic<bool> connected{false};
  14804. sse.on_open([&connected]() { connected.store(true); });
  14805. sse.set_reconnect_interval(100);
  14806. sse.set_max_reconnect_attempts(1);
  14807. sse.start_async();
  14808. // Wait for connection to establish
  14809. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14810. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14811. }
  14812. EXPECT_TRUE(connected.load());
  14813. EXPECT_TRUE(sse.is_connected());
  14814. // Signal handler to stop
  14815. handler_running.store(false);
  14816. // Stop SSE client
  14817. sse.stop();
  14818. EXPECT_FALSE(sse.is_connected());
  14819. }
  14820. // Test: SSEClient with custom headers
  14821. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14822. // Setup a server endpoint that checks for custom header
  14823. std::atomic<bool> header_received{false};
  14824. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14825. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14826. header_received.store(true);
  14827. }
  14828. res.set_chunked_content_provider("text/event-stream",
  14829. [](size_t, DataSink &) { return false; });
  14830. });
  14831. Client client("localhost", get_port());
  14832. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14833. sse::SSEClient sse(client, "/header-check", headers);
  14834. sse.set_max_reconnect_attempts(1);
  14835. sse.start_async();
  14836. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14837. sse.stop();
  14838. EXPECT_TRUE(header_received.load());
  14839. }
  14840. // Test: Reconnect interval configuration
  14841. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14842. Client client("localhost", get_port());
  14843. sse::SSEClient sse(client, "/events");
  14844. auto &result = sse.set_reconnect_interval(500);
  14845. // Builder pattern should return reference to self
  14846. EXPECT_EQ(&result, &sse);
  14847. }
  14848. // Test: Max reconnect attempts
  14849. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14850. // Connect to non-existent port to force reconnects
  14851. Client client("localhost", 59998);
  14852. sse::SSEClient sse(client, "/events");
  14853. std::atomic<int> error_count{0};
  14854. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14855. sse.set_reconnect_interval(50);
  14856. sse.set_max_reconnect_attempts(2);
  14857. auto start = std::chrono::steady_clock::now();
  14858. sse.start(); // Blocking call
  14859. auto end = std::chrono::steady_clock::now();
  14860. // Should have stopped after 2 failed attempts
  14861. EXPECT_GE(error_count.load(), 2);
  14862. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14863. auto duration =
  14864. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14865. #ifdef _WIN32
  14866. // Windows is much slower for socket connection failures
  14867. EXPECT_LT(duration.count(), 7000);
  14868. #else
  14869. EXPECT_LT(duration.count(), 1000);
  14870. #endif
  14871. }
  14872. // Test: Multi-line data in integration
  14873. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14874. // Endpoint with multi-line data
  14875. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14876. res.set_chunked_content_provider(
  14877. "text/event-stream", [](size_t offset, DataSink &sink) {
  14878. if (offset == 0) {
  14879. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14880. sink.write(event.data(), event.size());
  14881. }
  14882. return false;
  14883. });
  14884. });
  14885. Client client("localhost", get_port());
  14886. sse::SSEClient sse(client, "/multiline-data");
  14887. std::string received_data;
  14888. std::mutex data_mutex;
  14889. sse.on_message([&](const sse::SSEMessage &msg) {
  14890. std::lock_guard<std::mutex> lock(data_mutex);
  14891. received_data = msg.data;
  14892. });
  14893. sse.set_reconnect_interval(100);
  14894. sse.set_max_reconnect_attempts(1);
  14895. sse.start_async();
  14896. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14897. sse.stop();
  14898. std::lock_guard<std::mutex> lock(data_mutex);
  14899. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14900. }
  14901. // Test: Auto-reconnect after server disconnection
  14902. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14903. std::atomic<int> connection_count{0};
  14904. std::atomic<int> message_count{0};
  14905. // Endpoint that sends one event and closes, forcing reconnect
  14906. server_->Get("/reconnect-test",
  14907. [&connection_count](const Request &, Response &res) {
  14908. connection_count.fetch_add(1);
  14909. res.set_chunked_content_provider(
  14910. "text/event-stream", [](size_t offset, DataSink &sink) {
  14911. if (offset == 0) {
  14912. std::string event = "data: hello\n\n";
  14913. sink.write(event.data(), event.size());
  14914. }
  14915. return false; // Close connection after sending
  14916. });
  14917. });
  14918. Client client("localhost", get_port());
  14919. sse::SSEClient sse(client, "/reconnect-test");
  14920. sse.on_message([&message_count](const sse::SSEMessage &) {
  14921. message_count.fetch_add(1);
  14922. });
  14923. sse.set_reconnect_interval(100);
  14924. sse.set_max_reconnect_attempts(3);
  14925. sse.start_async();
  14926. // Wait long enough for multiple reconnects
  14927. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14928. sse.stop();
  14929. // Should have connected multiple times (initial + reconnects)
  14930. EXPECT_GE(connection_count.load(), 2);
  14931. // Should have received messages from multiple connections
  14932. EXPECT_GE(message_count.load(), 2);
  14933. }
  14934. // Test: Last-Event-ID sent on reconnect
  14935. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14936. std::atomic<int> connection_count{0};
  14937. std::vector<std::string> received_last_event_ids;
  14938. std::mutex id_mutex;
  14939. // Endpoint that checks Last-Event-ID header and sends event with ID
  14940. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14941. int conn = connection_count.fetch_add(1);
  14942. // Capture the Last-Event-ID header from each connection
  14943. {
  14944. std::lock_guard<std::mutex> lock(id_mutex);
  14945. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14946. }
  14947. res.set_chunked_content_provider(
  14948. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14949. if (offset == 0) {
  14950. std::string event =
  14951. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14952. sink.write(event.data(), event.size());
  14953. }
  14954. return false;
  14955. });
  14956. });
  14957. Client client("localhost", get_port());
  14958. sse::SSEClient sse(client, "/reconnect-with-id");
  14959. sse.set_reconnect_interval(100);
  14960. sse.set_max_reconnect_attempts(3);
  14961. sse.start_async();
  14962. // Wait for at least 2 connections
  14963. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14964. sse.stop();
  14965. // Verify behavior
  14966. std::lock_guard<std::mutex> lock(id_mutex);
  14967. EXPECT_GE(received_last_event_ids.size(), 2u);
  14968. // First connection should have no Last-Event-ID
  14969. if (!received_last_event_ids.empty()) {
  14970. EXPECT_EQ(received_last_event_ids[0], "");
  14971. }
  14972. // Second connection should have Last-Event-ID from first connection
  14973. if (received_last_event_ids.size() >= 2) {
  14974. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14975. }
  14976. }
  14977. // Test: set_headers updates headers used on reconnect
  14978. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14979. std::vector<std::string> received_tokens;
  14980. std::mutex token_mutex;
  14981. // Endpoint that captures Authorization header
  14982. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14983. {
  14984. std::lock_guard<std::mutex> lock(token_mutex);
  14985. received_tokens.push_back(req.get_header_value("Authorization"));
  14986. }
  14987. res.set_chunked_content_provider(
  14988. "text/event-stream", [](size_t offset, DataSink &sink) {
  14989. if (offset == 0) {
  14990. std::string event = "data: hello\n\n";
  14991. sink.write(event.data(), event.size());
  14992. }
  14993. return false; // Close connection to trigger reconnect
  14994. });
  14995. });
  14996. Client client("localhost", get_port());
  14997. Headers headers = {{"Authorization", "Bearer old-token"}};
  14998. sse::SSEClient sse(client, "/auth-check", headers);
  14999. // Update headers on each successful connection
  15000. sse.on_open(
  15001. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15002. sse.set_reconnect_interval(100);
  15003. sse.set_max_reconnect_attempts(3);
  15004. sse.start_async();
  15005. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15006. sse.stop();
  15007. std::lock_guard<std::mutex> lock(token_mutex);
  15008. ASSERT_GE(received_tokens.size(), 2u);
  15009. // First connection uses original header
  15010. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15011. // Second connection uses updated header from set_headers
  15012. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15013. }
  15014. // Test: 401 allows reconnection (so on_error can refresh headers)
  15015. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15016. std::atomic<int> connection_count{0};
  15017. // Endpoint: returns 401 on first attempt, 200 on second
  15018. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15019. int conn = connection_count.fetch_add(1);
  15020. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15021. res.status = StatusCode::Unauthorized_401;
  15022. res.set_content("Unauthorized", "text/plain");
  15023. return;
  15024. }
  15025. res.set_chunked_content_provider(
  15026. "text/event-stream", [](size_t offset, DataSink &sink) {
  15027. if (offset == 0) {
  15028. std::string event = "data: authenticated\n\n";
  15029. sink.write(event.data(), event.size());
  15030. }
  15031. return false;
  15032. });
  15033. });
  15034. Client client("localhost", get_port());
  15035. Headers headers = {{"Authorization", "Bearer expired"}};
  15036. sse::SSEClient sse(client, "/auth-retry", headers);
  15037. std::atomic<bool> message_received{false};
  15038. // Refresh token on error
  15039. sse.on_error(
  15040. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15041. sse.on_message([&](const sse::SSEMessage &msg) {
  15042. if (msg.data == "authenticated") { message_received.store(true); }
  15043. });
  15044. sse.set_reconnect_interval(100);
  15045. sse.set_max_reconnect_attempts(3);
  15046. sse.start_async();
  15047. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15048. sse.stop();
  15049. // Should have reconnected after 401 and succeeded with new token
  15050. EXPECT_GE(connection_count.load(), 2);
  15051. EXPECT_TRUE(message_received.load());
  15052. }
  15053. TEST(Issue2318Test, EmptyHostString) {
  15054. {
  15055. httplib::Client cli_empty("", PORT);
  15056. auto res = cli_empty.Get("/");
  15057. ASSERT_FALSE(res);
  15058. EXPECT_EQ(httplib::Error::Connection, res.error());
  15059. }
  15060. {
  15061. httplib::Client cli(" ", PORT);
  15062. auto res = cli.Get("/");
  15063. ASSERT_FALSE(res);
  15064. EXPECT_EQ(httplib::Error::Connection, res.error());
  15065. }
  15066. }
  15067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15068. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15069. Server svr;
  15070. // Set a small payload limit (1KB)
  15071. svr.set_payload_max_length(1024);
  15072. svr.Post("/test", [&](const Request &req, Response &res) {
  15073. res.set_content("Body size: " + std::to_string(req.body.size()),
  15074. "text/plain");
  15075. });
  15076. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. listen_thread.join();
  15080. });
  15081. svr.wait_until_ready();
  15082. // Create data that compresses well but exceeds limit when decompressed
  15083. // 8KB of repeated null bytes compresses to a very small size
  15084. std::string original_data(8 * 1024, '\0');
  15085. // Compress the data using gzip
  15086. std::string compressed_data;
  15087. detail::gzip_compressor compressor;
  15088. compressor.compress(original_data.data(), original_data.size(), true,
  15089. [&](const char *data, size_t size) {
  15090. compressed_data.append(data, size);
  15091. return true;
  15092. });
  15093. // Verify compression worked (compressed should be much smaller)
  15094. ASSERT_LT(compressed_data.size(), original_data.size());
  15095. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15096. // Send compressed data with Content-Encoding: gzip
  15097. Client cli(HOST, PORT);
  15098. Headers headers = {{"Content-Encoding", "gzip"}};
  15099. auto res =
  15100. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15101. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15102. ASSERT_TRUE(res);
  15103. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15104. }
  15105. #endif
  15106. // ============================================================================
  15107. // OpenSSL-Specific Tests
  15108. // ============================================================================
  15109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15110. X509 *readCertificate(const std::string &strFileName) {
  15111. std::ifstream inStream(strFileName);
  15112. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15113. std::istreambuf_iterator<char>());
  15114. if (strCertPEM.empty()) return (nullptr);
  15115. BIO *pbCert = BIO_new(BIO_s_mem());
  15116. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15117. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15118. BIO_free(pbCert);
  15119. return (pCert);
  15120. }
  15121. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15122. std::ifstream inStream(strFileName);
  15123. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15124. std::istreambuf_iterator<char>());
  15125. if (strPrivateKeyPEM.empty()) return (nullptr);
  15126. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15127. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15128. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15129. BIO_free(pbPrivKey);
  15130. return (pPrivateKey);
  15131. }
  15132. TEST(BindServerTest, UpdateCerts) {
  15133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15134. int port = svr.bind_to_any_port("0.0.0.0");
  15135. ASSERT_TRUE(svr.is_valid());
  15136. ASSERT_TRUE(port > 0);
  15137. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15138. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15139. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15140. ASSERT_TRUE(cert != nullptr);
  15141. ASSERT_TRUE(ca_cert != nullptr);
  15142. ASSERT_TRUE(key != nullptr);
  15143. X509_STORE *cert_store = X509_STORE_new();
  15144. X509_STORE_add_cert(cert_store, ca_cert);
  15145. // svr.update_certs(cert, key, cert_store); // deprecated
  15146. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15147. CLIENT_CA_CERT_FILE);
  15148. ASSERT_TRUE(svr.is_valid());
  15149. svr.stop();
  15150. X509_STORE_free(cert_store);
  15151. X509_free(cert);
  15152. X509_free(ca_cert);
  15153. EVP_PKEY_free(key);
  15154. }
  15155. // Test that update_certs() updates client CA list correctly
  15156. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15157. // Start with file-based constructor
  15158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15159. ASSERT_TRUE(svr.is_valid());
  15160. // Initially no client CA list should be set
  15161. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15162. ASSERT_TRUE(ssl_ctx != nullptr);
  15163. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15164. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15165. EXPECT_EQ(0, count_before);
  15166. // Now update with client CA (PEM string)
  15167. std::string cert_pem, key_pem, ca_pem;
  15168. read_file(SERVER_CERT_FILE, cert_pem);
  15169. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15170. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15171. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15172. ASSERT_TRUE(svr.is_valid());
  15173. // Now client CA list should be set
  15174. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15175. ASSERT_TRUE(ca_list_after != nullptr);
  15176. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15177. }
  15178. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15179. // Test that the file-path SSLServer constructor properly sets the client CA
  15180. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15182. ASSERT_TRUE(svr.is_valid());
  15183. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15184. ASSERT_TRUE(ssl_ctx != nullptr);
  15185. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15186. ASSERT_TRUE(ca_list != nullptr);
  15187. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15188. }
  15189. #endif
  15190. // ============================================================================
  15191. // MbedTLS-Specific Tests
  15192. // ============================================================================
  15193. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15194. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15195. using namespace httplib::tls;
  15196. // Track if callback was invoked
  15197. bool callback_invoked = false;
  15198. // The callback receives void* ctx which is actually MbedTlsContext*
  15199. // We can access the mbedtls_ssl_config via the context
  15200. auto setup_callback = [&callback_invoked](void *ctx) {
  15201. callback_invoked = true;
  15202. // Cast to MbedTlsContext* to access the ssl config
  15203. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15204. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15205. // Use static variables to hold certificate data (simplified for test)
  15206. static mbedtls_x509_crt own_cert;
  15207. static mbedtls_pk_context own_key;
  15208. static mbedtls_x509_crt ca_chain;
  15209. static bool initialized = false;
  15210. if (!initialized) {
  15211. mbedtls_x509_crt_init(&own_cert);
  15212. mbedtls_pk_init(&own_key);
  15213. mbedtls_x509_crt_init(&ca_chain);
  15214. // Load server certificate
  15215. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15216. return false;
  15217. }
  15218. // Load server private key
  15219. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15220. #if MBEDTLS_VERSION_MAJOR >= 3
  15221. ,
  15222. mbedtls_ctr_drbg_random, nullptr
  15223. #endif
  15224. ) != 0) {
  15225. return false;
  15226. }
  15227. // Load CA chain for client verification
  15228. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15229. return false;
  15230. }
  15231. initialized = true;
  15232. }
  15233. // Configure the SSL config
  15234. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15235. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15236. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15237. // Set minimum TLS version using mbedTLS native API
  15238. #if MBEDTLS_VERSION_MAJOR >= 3
  15239. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15240. #else
  15241. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15242. MBEDTLS_SSL_MINOR_VERSION_3);
  15243. #endif
  15244. return true;
  15245. };
  15246. SSLServer svr(setup_callback);
  15247. ASSERT_TRUE(svr.is_valid());
  15248. ASSERT_TRUE(callback_invoked);
  15249. svr.Get("/test", [&](const Request &req, Response &res) {
  15250. res.set_content("test", "text/plain");
  15251. auto cert = req.peer_cert();
  15252. ASSERT_TRUE(static_cast<bool>(cert));
  15253. auto common_name = cert.subject_cn();
  15254. EXPECT_EQ("Common Name", common_name);
  15255. });
  15256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15257. auto se = detail::scope_exit([&] {
  15258. svr.stop();
  15259. t.join();
  15260. ASSERT_FALSE(svr.is_running());
  15261. });
  15262. svr.wait_until_ready();
  15263. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15264. cli.enable_server_certificate_verification(false);
  15265. cli.set_connection_timeout(30);
  15266. auto res = cli.Get("/test");
  15267. ASSERT_TRUE(res);
  15268. ASSERT_EQ(StatusCode::OK_200, res->status);
  15269. }
  15270. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15271. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15272. // keep-alive SSL session, which reads through that config in
  15273. // mbedtls_ssl_close_notify.
  15274. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15276. ASSERT_TRUE(svr.is_valid());
  15277. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15278. res.set_content("test", "text/plain");
  15279. });
  15280. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15281. auto se = detail::scope_exit([&] {
  15282. svr.stop();
  15283. t.join();
  15284. ASSERT_FALSE(svr.is_running());
  15285. });
  15286. svr.wait_until_ready();
  15287. {
  15288. SSLClient cli(HOST, PORT);
  15289. cli.enable_server_certificate_verification(false);
  15290. cli.set_keep_alive(true);
  15291. auto res = cli.Get("/test");
  15292. ASSERT_TRUE(res);
  15293. ASSERT_EQ(StatusCode::OK_200, res->status);
  15294. // cli is destructed here with the keep-alive SSL session still open.
  15295. }
  15296. }
  15297. #endif
  15298. // WebSocket Tests
  15299. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15300. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15301. // defining the meaning of these bits has been negotiated.
  15302. auto make_frame = [](uint8_t first_byte) {
  15303. std::string frame;
  15304. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15305. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15306. frame += "Hello";
  15307. return frame;
  15308. };
  15309. // RSV1 set (0x40)
  15310. {
  15311. detail::BufferStream strm;
  15312. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15313. ws::Opcode opcode;
  15314. std::string payload;
  15315. bool fin;
  15316. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15317. false, 1024));
  15318. }
  15319. // RSV2 set (0x20)
  15320. {
  15321. detail::BufferStream strm;
  15322. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15323. ws::Opcode opcode;
  15324. std::string payload;
  15325. bool fin;
  15326. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15327. false, 1024));
  15328. }
  15329. // RSV3 set (0x10)
  15330. {
  15331. detail::BufferStream strm;
  15332. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15333. ws::Opcode opcode;
  15334. std::string payload;
  15335. bool fin;
  15336. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15337. false, 1024));
  15338. }
  15339. // No RSV bits set - should succeed
  15340. {
  15341. detail::BufferStream strm;
  15342. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15343. ws::Opcode opcode;
  15344. std::string payload;
  15345. bool fin;
  15346. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15347. false, 1024));
  15348. EXPECT_EQ(ws::Opcode::Text, opcode);
  15349. EXPECT_EQ("Hello", payload);
  15350. EXPECT_TRUE(fin);
  15351. }
  15352. }
  15353. TEST(WebSocketTest, ControlFrameValidation) {
  15354. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15355. // payload length <= 125.
  15356. // Ping with FIN=0 - must be rejected
  15357. {
  15358. detail::BufferStream strm;
  15359. std::string frame;
  15360. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15361. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15362. strm.write(frame.data(), frame.size());
  15363. ws::Opcode opcode;
  15364. std::string payload;
  15365. bool fin;
  15366. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15367. false, 1024));
  15368. }
  15369. // Close with FIN=0 - must be rejected
  15370. {
  15371. detail::BufferStream strm;
  15372. std::string frame;
  15373. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15374. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15375. strm.write(frame.data(), frame.size());
  15376. ws::Opcode opcode;
  15377. std::string payload;
  15378. bool fin;
  15379. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15380. false, 1024));
  15381. }
  15382. // Ping with payload_len=126 (extended length) - must be rejected
  15383. {
  15384. detail::BufferStream strm;
  15385. std::string frame;
  15386. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15387. frame += static_cast<char>(126); // payload_len=126 (>125)
  15388. frame += static_cast<char>(0x00); // extended length high byte
  15389. frame += static_cast<char>(126); // extended length low byte
  15390. frame += std::string(126, 'x');
  15391. strm.write(frame.data(), frame.size());
  15392. ws::Opcode opcode;
  15393. std::string payload;
  15394. bool fin;
  15395. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15396. false, 1024));
  15397. }
  15398. // Ping with FIN=1 and payload_len=125 - should succeed
  15399. {
  15400. detail::BufferStream strm;
  15401. std::string frame;
  15402. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15403. frame += static_cast<char>(125); // payload_len=125
  15404. frame += std::string(125, 'x');
  15405. strm.write(frame.data(), frame.size());
  15406. ws::Opcode opcode;
  15407. std::string payload;
  15408. bool fin;
  15409. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15410. false, 1024));
  15411. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15412. EXPECT_EQ(125u, payload.size());
  15413. EXPECT_TRUE(fin);
  15414. }
  15415. }
  15416. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15417. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15418. // length MUST be 0.
  15419. // MSB set - must be rejected
  15420. {
  15421. detail::BufferStream strm;
  15422. std::string frame;
  15423. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15424. frame += static_cast<char>(127); // 64-bit extended length
  15425. frame += static_cast<char>(0x80); // MSB set (invalid)
  15426. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15427. strm.write(frame.data(), frame.size());
  15428. ws::Opcode opcode;
  15429. std::string payload;
  15430. bool fin;
  15431. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15432. false, 1024));
  15433. }
  15434. // MSB clear - should pass length parsing (will be rejected by max_len,
  15435. // but that's a different check; use a small length to verify)
  15436. {
  15437. detail::BufferStream strm;
  15438. std::string frame;
  15439. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15440. frame += static_cast<char>(127); // 64-bit extended length
  15441. frame += std::string(7, '\0'); // high bytes = 0
  15442. frame += static_cast<char>(0x03); // length = 3
  15443. frame += "abc";
  15444. strm.write(frame.data(), frame.size());
  15445. ws::Opcode opcode;
  15446. std::string payload;
  15447. bool fin;
  15448. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15449. false, 1024));
  15450. EXPECT_EQ(ws::Opcode::Text, opcode);
  15451. EXPECT_EQ("abc", payload);
  15452. }
  15453. }
  15454. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15455. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15456. // Valid UTF-8
  15457. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15458. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15459. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15460. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15461. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15462. // Invalid UTF-8
  15463. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15464. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15465. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15466. EXPECT_FALSE(
  15467. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15468. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15469. }
  15470. TEST(WebSocketTest, ConnectAndDisconnect) {
  15471. Server svr;
  15472. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15473. std::string msg;
  15474. while (ws.read(msg)) {}
  15475. });
  15476. auto port = svr.bind_to_any_port(HOST);
  15477. std::thread t([&]() { svr.listen_after_bind(); });
  15478. svr.wait_until_ready();
  15479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15480. ASSERT_TRUE(client.connect());
  15481. EXPECT_TRUE(client.is_open());
  15482. client.close();
  15483. EXPECT_FALSE(client.is_open());
  15484. svr.stop();
  15485. t.join();
  15486. }
  15487. TEST(WebSocketTest, ValidURL) {
  15488. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15489. EXPECT_TRUE(ws1.is_valid());
  15490. ws::WebSocketClient ws2("ws://example.com/path");
  15491. EXPECT_TRUE(ws2.is_valid());
  15492. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15493. EXPECT_TRUE(ws3.is_valid());
  15494. #ifdef CPPHTTPLIB_SSL_ENABLED
  15495. ws::WebSocketClient wss1("wss://example.com/path");
  15496. EXPECT_TRUE(wss1.is_valid());
  15497. ws::WebSocketClient wss2("wss://example.com:443/path");
  15498. EXPECT_TRUE(wss2.is_valid());
  15499. #endif
  15500. }
  15501. TEST(WebSocketTest, InvalidURL) {
  15502. // No scheme
  15503. ws::WebSocketClient ws1("localhost:8080/path");
  15504. EXPECT_FALSE(ws1.is_valid());
  15505. // No path
  15506. ws::WebSocketClient ws2("ws://localhost:8080");
  15507. EXPECT_FALSE(ws2.is_valid());
  15508. // Empty string
  15509. ws::WebSocketClient ws3("");
  15510. EXPECT_FALSE(ws3.is_valid());
  15511. // Missing host
  15512. ws::WebSocketClient ws4("ws://:8080/path");
  15513. EXPECT_FALSE(ws4.is_valid());
  15514. // Port number overflow — should not crash
  15515. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15516. EXPECT_FALSE(ws5.is_valid());
  15517. // Port out of range
  15518. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15519. EXPECT_FALSE(ws6.is_valid());
  15520. }
  15521. TEST(WebSocketTest, UnsupportedScheme) {
  15522. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15523. ws::WebSocketClient ws1("http://localhost:8080/path");
  15524. EXPECT_FALSE(ws1.is_valid());
  15525. ws::WebSocketClient ws2("https://localhost:8080/path");
  15526. EXPECT_FALSE(ws2.is_valid());
  15527. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15528. EXPECT_FALSE(ws3.is_valid());
  15529. #else
  15530. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15531. std::invalid_argument);
  15532. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15533. std::invalid_argument);
  15534. #endif
  15535. }
  15536. TEST(WebSocketTest, ConnectWhenInvalid) {
  15537. ws::WebSocketClient ws("not a valid url");
  15538. EXPECT_FALSE(ws.is_valid());
  15539. EXPECT_FALSE(ws.connect());
  15540. }
  15541. TEST(WebSocketTest, DefaultPort) {
  15542. ws::WebSocketClient ws1("ws://example.com/path");
  15543. EXPECT_TRUE(ws1.is_valid());
  15544. // ws:// defaults to port 80 (verified by successful parse)
  15545. #ifdef CPPHTTPLIB_SSL_ENABLED
  15546. ws::WebSocketClient ws2("wss://example.com/path");
  15547. EXPECT_TRUE(ws2.is_valid());
  15548. // wss:// defaults to port 443 (verified by successful parse)
  15549. #endif
  15550. }
  15551. TEST(WebSocketTest, IPv6LiteralAddress) {
  15552. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15553. EXPECT_TRUE(ws1.is_valid());
  15554. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15555. EXPECT_TRUE(ws2.is_valid());
  15556. }
  15557. TEST(WebSocketTest, ComplexPath) {
  15558. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15559. EXPECT_TRUE(ws1.is_valid());
  15560. ws::WebSocketClient ws2("ws://localhost:8080/");
  15561. EXPECT_TRUE(ws2.is_valid());
  15562. }
  15563. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15564. Server svr;
  15565. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15566. std::string msg;
  15567. while (ws.read(msg)) {}
  15568. });
  15569. auto port = svr.bind_to_any_port(HOST);
  15570. std::thread t([&]() { svr.listen_after_bind(); });
  15571. svr.wait_until_ready();
  15572. auto another_host = "example.com";
  15573. auto wrong_ip = "192.0.2.1";
  15574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15575. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15576. ASSERT_TRUE(client.connect());
  15577. EXPECT_TRUE(client.is_open());
  15578. client.close();
  15579. svr.stop();
  15580. t.join();
  15581. }
  15582. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15583. Server svr;
  15584. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15585. std::string msg;
  15586. while (ws.read(msg)) {}
  15587. });
  15588. auto port = svr.bind_to_any_port(HOST);
  15589. std::thread t([&]() { svr.listen_after_bind(); });
  15590. svr.wait_until_ready();
  15591. auto wrong_ip = "192.0.2.1";
  15592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15593. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15594. client.set_connection_timeout(1);
  15595. client.set_read_timeout(1);
  15596. client.set_write_timeout(1);
  15597. EXPECT_FALSE(client.connect());
  15598. EXPECT_FALSE(client.is_open());
  15599. svr.stop();
  15600. t.join();
  15601. }
  15602. class WebSocketIntegrationTest : public ::testing::Test {
  15603. protected:
  15604. void SetUp() override {
  15605. server_ = httplib::detail::make_unique<Server>();
  15606. setup_server();
  15607. start_server();
  15608. }
  15609. void TearDown() override {
  15610. server_->stop();
  15611. if (server_thread_.joinable()) { server_thread_.join(); }
  15612. }
  15613. void setup_server() {
  15614. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15615. std::string msg;
  15616. ws::ReadResult ret;
  15617. while ((ret = ws.read(msg))) {
  15618. if (ret == ws::Binary) {
  15619. ws.send(msg.data(), msg.size());
  15620. } else {
  15621. ws.send(msg);
  15622. }
  15623. }
  15624. });
  15625. server_->WebSocket("/ws-echo-string",
  15626. [](const Request &, ws::WebSocket &ws) {
  15627. std::string msg;
  15628. while (ws.read(msg)) {
  15629. ws.send("echo: " + msg);
  15630. }
  15631. });
  15632. server_->WebSocket(
  15633. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15634. // Echo back request metadata
  15635. ws.send("path:" + req.path);
  15636. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15637. std::string msg;
  15638. while (ws.read(msg)) {}
  15639. });
  15640. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15641. std::string msg;
  15642. ws.read(msg); // wait for a message
  15643. ws.close();
  15644. });
  15645. server_->WebSocket("/ws-close-status",
  15646. [](const Request &, ws::WebSocket &ws) {
  15647. std::string msg;
  15648. ws.read(msg); // wait for a message
  15649. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15650. });
  15651. server_->WebSocket(
  15652. "/ws-subprotocol",
  15653. [](const Request &, ws::WebSocket &ws) {
  15654. std::string msg;
  15655. while (ws.read(msg)) {
  15656. ws.send(msg);
  15657. }
  15658. },
  15659. [](const std::vector<std::string> &protocols) -> std::string {
  15660. for (const auto &p : protocols) {
  15661. if (p == "graphql-ws") { return p; }
  15662. }
  15663. return "";
  15664. });
  15665. }
  15666. void start_server() {
  15667. port_ = server_->bind_to_any_port(HOST);
  15668. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15669. server_->wait_until_ready();
  15670. }
  15671. std::unique_ptr<Server> server_;
  15672. std::thread server_thread_;
  15673. int port_ = 0;
  15674. };
  15675. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15677. "/ws-echo");
  15678. ASSERT_TRUE(client.connect());
  15679. ASSERT_TRUE(client.is_open());
  15680. ASSERT_TRUE(client.send("Hello WebSocket"));
  15681. std::string msg;
  15682. EXPECT_EQ(ws::Text, client.read(msg));
  15683. EXPECT_EQ("Hello WebSocket", msg);
  15684. client.close();
  15685. }
  15686. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15688. "/ws-echo");
  15689. ASSERT_TRUE(client.connect());
  15690. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15691. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15692. std::string msg;
  15693. EXPECT_EQ(ws::Binary, client.read(msg));
  15694. EXPECT_EQ(binary_data, msg);
  15695. client.close();
  15696. }
  15697. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15699. "/ws-echo");
  15700. ASSERT_TRUE(client.connect());
  15701. for (int i = 0; i < 10; i++) {
  15702. auto text = "message " + std::to_string(i);
  15703. ASSERT_TRUE(client.send(text));
  15704. std::string msg;
  15705. ASSERT_TRUE(client.read(msg));
  15706. EXPECT_EQ(text, msg);
  15707. }
  15708. client.close();
  15709. }
  15710. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15712. "/ws-close");
  15713. ASSERT_TRUE(client.connect());
  15714. // Send a message to trigger the server to close
  15715. ASSERT_TRUE(client.send("trigger close"));
  15716. // The server will close, so read should return false
  15717. std::string msg;
  15718. EXPECT_FALSE(client.read(msg));
  15719. EXPECT_FALSE(client.is_open());
  15720. }
  15721. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15723. "/ws-echo");
  15724. ASSERT_TRUE(client.connect());
  15725. // 128KB message
  15726. std::string large_data(128 * 1024, 'X');
  15727. ASSERT_TRUE(client.send(large_data));
  15728. std::string msg;
  15729. ASSERT_TRUE(client.read(msg));
  15730. EXPECT_EQ(large_data, msg);
  15731. client.close();
  15732. }
  15733. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15735. "/ws-echo");
  15736. ASSERT_TRUE(client.connect());
  15737. const int num_threads = 4;
  15738. std::vector<std::thread> threads;
  15739. std::atomic<int> send_count{0};
  15740. for (int t = 0; t < num_threads; t++) {
  15741. threads.emplace_back([&client, &send_count, t]() {
  15742. for (int i = 0; i < 5; i++) {
  15743. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15744. if (client.send(text)) { send_count++; }
  15745. }
  15746. });
  15747. }
  15748. for (auto &th : threads) {
  15749. th.join();
  15750. }
  15751. int received = 0;
  15752. std::string msg;
  15753. while (received < send_count.load()) {
  15754. if (!client.read(msg)) { break; }
  15755. received++;
  15756. }
  15757. EXPECT_EQ(send_count.load(), received);
  15758. client.close();
  15759. }
  15760. TEST_F(WebSocketIntegrationTest, ReadString) {
  15761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15762. "/ws-echo-string");
  15763. ASSERT_TRUE(client.connect());
  15764. ASSERT_TRUE(client.send("hello"));
  15765. std::string msg;
  15766. ASSERT_TRUE(client.read(msg));
  15767. EXPECT_EQ("echo: hello", msg);
  15768. ASSERT_TRUE(client.send("world"));
  15769. ASSERT_TRUE(client.read(msg));
  15770. EXPECT_EQ("echo: world", msg);
  15771. client.close();
  15772. }
  15773. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15774. Headers headers = {{"X-Test-Header", "test-value"}};
  15775. ws::WebSocketClient client(
  15776. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15777. ASSERT_TRUE(client.connect());
  15778. std::string msg;
  15779. ASSERT_TRUE(client.read(msg));
  15780. EXPECT_EQ("path:/ws-request-info", msg);
  15781. ASSERT_TRUE(client.read(msg));
  15782. EXPECT_EQ("header:test-value", msg);
  15783. client.close();
  15784. }
  15785. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15787. "/ws-echo");
  15788. client.set_read_timeout(1, 0); // 1 second
  15789. ASSERT_TRUE(client.connect());
  15790. // Don't send anything — server echo handler waits for a message,
  15791. // so read() should time out and return false.
  15792. std::string msg;
  15793. EXPECT_FALSE(client.read(msg));
  15794. }
  15795. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15797. "/ws-echo");
  15798. client.set_read_timeout(5, 0);
  15799. ASSERT_TRUE(client.connect());
  15800. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15801. // The server should reject it and close the connection.
  15802. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15803. client.send(oversized);
  15804. // The server's read() should have failed due to payload limit,
  15805. // so our read() should return false (connection closed).
  15806. std::string msg;
  15807. EXPECT_FALSE(client.read(msg));
  15808. }
  15809. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15810. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15811. "/ws-echo");
  15812. client.set_read_timeout(10, 0);
  15813. ASSERT_TRUE(client.connect());
  15814. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15815. // This should succeed.
  15816. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15817. ASSERT_TRUE(client.send(at_limit));
  15818. std::string msg;
  15819. ASSERT_TRUE(client.read(msg));
  15820. EXPECT_EQ(at_limit.size(), msg.size());
  15821. client.close();
  15822. }
  15823. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15825. "/nonexistent");
  15826. EXPECT_FALSE(client.connect());
  15827. EXPECT_FALSE(client.is_open());
  15828. }
  15829. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15831. "/ws-echo");
  15832. ASSERT_TRUE(client.connect());
  15833. ASSERT_TRUE(client.send(""));
  15834. std::string msg;
  15835. EXPECT_EQ(ws::Text, client.read(msg));
  15836. EXPECT_EQ("", msg);
  15837. client.close();
  15838. }
  15839. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15841. "/ws-echo");
  15842. // First connection
  15843. ASSERT_TRUE(client.connect());
  15844. ASSERT_TRUE(client.send("first"));
  15845. std::string msg;
  15846. ASSERT_TRUE(client.read(msg));
  15847. EXPECT_EQ("first", msg);
  15848. client.close();
  15849. EXPECT_FALSE(client.is_open());
  15850. // Reconnect using the same client object
  15851. ASSERT_TRUE(client.connect());
  15852. ASSERT_TRUE(client.is_open());
  15853. ASSERT_TRUE(client.send("second"));
  15854. ASSERT_TRUE(client.read(msg));
  15855. EXPECT_EQ("second", msg);
  15856. client.close();
  15857. }
  15858. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15859. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15860. "/ws-close-status");
  15861. ASSERT_TRUE(client.connect());
  15862. // Trigger the server to close with GoingAway status
  15863. ASSERT_TRUE(client.send("trigger"));
  15864. // read() should return false after receiving the close frame
  15865. std::string msg;
  15866. EXPECT_FALSE(client.read(msg));
  15867. EXPECT_FALSE(client.is_open());
  15868. }
  15869. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15871. "/ws-echo");
  15872. ASSERT_TRUE(client.connect());
  15873. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15874. EXPECT_FALSE(client.is_open());
  15875. }
  15876. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15877. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15878. ws::WebSocketClient client(
  15879. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15880. ASSERT_TRUE(client.connect());
  15881. // Server should have selected graphql-ws
  15882. EXPECT_EQ("graphql-ws", client.subprotocol());
  15883. client.close();
  15884. }
  15885. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15886. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15887. ws::WebSocketClient client(
  15888. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15889. ASSERT_TRUE(client.connect());
  15890. // Server should not have selected any subprotocol
  15891. EXPECT_TRUE(client.subprotocol().empty());
  15892. client.close();
  15893. }
  15894. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15895. // Connect without requesting any subprotocol
  15896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15897. "/ws-subprotocol");
  15898. ASSERT_TRUE(client.connect());
  15899. EXPECT_TRUE(client.subprotocol().empty());
  15900. client.close();
  15901. }
  15902. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15904. "/ws-echo");
  15905. client.set_tcp_nodelay(true);
  15906. client.set_connection_timeout(3, 0);
  15907. bool socket_options_called = false;
  15908. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15909. ASSERT_TRUE(client.connect());
  15910. ASSERT_TRUE(client.is_open());
  15911. EXPECT_TRUE(socket_options_called);
  15912. ASSERT_TRUE(client.send("hello"));
  15913. std::string msg;
  15914. auto result = client.read(msg);
  15915. EXPECT_EQ(result, ws::ReadResult::Text);
  15916. EXPECT_EQ(msg, "hello");
  15917. client.close();
  15918. }
  15919. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15920. Server svr;
  15921. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15922. if (!req.has_header("Authorization")) {
  15923. res.status = StatusCode::Unauthorized_401;
  15924. res.set_content("Unauthorized", "text/plain");
  15925. return Server::HandlerResponse::Handled;
  15926. }
  15927. return Server::HandlerResponse::Unhandled;
  15928. });
  15929. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15930. std::string msg;
  15931. while (ws.read(msg)) {
  15932. ws.send(msg);
  15933. }
  15934. });
  15935. auto port = svr.bind_to_any_port("localhost");
  15936. std::thread t([&]() { svr.listen_after_bind(); });
  15937. svr.wait_until_ready();
  15938. // Without Authorization header - should be rejected before upgrade
  15939. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15940. EXPECT_FALSE(client1.connect());
  15941. // With Authorization header - should succeed
  15942. Headers headers = {{"Authorization", "Bearer token123"}};
  15943. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15944. headers);
  15945. ASSERT_TRUE(client2.connect());
  15946. ASSERT_TRUE(client2.send("hello"));
  15947. std::string msg;
  15948. ASSERT_TRUE(client2.read(msg));
  15949. EXPECT_EQ("hello", msg);
  15950. client2.close();
  15951. svr.stop();
  15952. t.join();
  15953. }
  15954. TEST(WebSocketTest, QueryStringInHandshake) {
  15955. Server svr;
  15956. std::mutex mtx;
  15957. std::string received_target;
  15958. std::string received_token;
  15959. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15960. {
  15961. std::lock_guard<std::mutex> lock(mtx);
  15962. received_target = req.target;
  15963. if (req.has_param("token")) {
  15964. received_token = req.get_param_value("token");
  15965. }
  15966. }
  15967. std::string msg;
  15968. while (ws.read(msg)) {
  15969. ws.send(msg);
  15970. }
  15971. });
  15972. auto port = svr.bind_to_any_port("localhost");
  15973. std::thread t([&]() { svr.listen_after_bind(); });
  15974. svr.wait_until_ready();
  15975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15976. "/ws?token=ABC&session=123");
  15977. ASSERT_TRUE(client.connect());
  15978. // Round-trip ensures the handler has run and captured the request.
  15979. ASSERT_TRUE(client.send("hello"));
  15980. std::string msg;
  15981. ASSERT_TRUE(client.read(msg));
  15982. EXPECT_EQ("hello", msg);
  15983. client.close();
  15984. {
  15985. std::lock_guard<std::mutex> lock(mtx);
  15986. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15987. EXPECT_EQ("ABC", received_token);
  15988. }
  15989. svr.stop();
  15990. t.join();
  15991. }
  15992. TEST(WebSocketTest, HostHeaderInHandshake) {
  15993. Server svr;
  15994. std::mutex mtx;
  15995. std::string received_host;
  15996. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15997. {
  15998. std::lock_guard<std::mutex> lock(mtx);
  15999. received_host = req.get_header_value("Host");
  16000. }
  16001. std::string msg;
  16002. while (ws.read(msg)) {
  16003. ws.send(msg);
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("localhost");
  16007. std::thread t([&]() { svr.listen_after_bind(); });
  16008. svr.wait_until_ready();
  16009. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16010. ASSERT_TRUE(client.connect());
  16011. // Round-trip ensures the handler has run and captured the request.
  16012. ASSERT_TRUE(client.send("hello"));
  16013. std::string msg;
  16014. ASSERT_TRUE(client.read(msg));
  16015. client.close();
  16016. {
  16017. std::lock_guard<std::mutex> lock(mtx);
  16018. // Non-default port must be present in the Host header. Default ports
  16019. // (80/443) are omitted; that logic is covered by
  16020. // MakeHostAndPortStringTest.
  16021. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16022. }
  16023. svr.stop();
  16024. t.join();
  16025. }
  16026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16027. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16028. protected:
  16029. void SetUp() override {
  16030. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16031. SERVER_PRIVATE_KEY_FILE);
  16032. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16033. std::string msg;
  16034. ws::ReadResult ret;
  16035. while ((ret = ws.read(msg))) {
  16036. if (ret == ws::Binary) {
  16037. ws.send(msg.data(), msg.size());
  16038. } else {
  16039. ws.send(msg);
  16040. }
  16041. }
  16042. });
  16043. port_ = server_->bind_to_any_port(HOST);
  16044. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16045. server_->wait_until_ready();
  16046. }
  16047. void TearDown() override {
  16048. server_->stop();
  16049. if (server_thread_.joinable()) { server_thread_.join(); }
  16050. }
  16051. std::unique_ptr<SSLServer> server_;
  16052. std::thread server_thread_;
  16053. int port_ = 0;
  16054. };
  16055. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16056. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16057. "/ws-echo");
  16058. client.enable_server_certificate_verification(false);
  16059. ASSERT_TRUE(client.connect());
  16060. ASSERT_TRUE(client.is_open());
  16061. ASSERT_TRUE(client.send("Hello WSS"));
  16062. std::string msg;
  16063. EXPECT_EQ(ws::Text, client.read(msg));
  16064. EXPECT_EQ("Hello WSS", msg);
  16065. client.close();
  16066. }
  16067. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16068. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16069. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16070. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16071. // client (without calling close() first) is the only path that runs
  16072. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16073. // bug exactly.
  16074. //
  16075. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16076. // when linked against an instrumented libssl; run under Valgrind to catch it
  16077. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16078. // suite (the freed session otherwise stalls on the close handshake) — this test
  16079. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16080. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16081. {
  16082. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16083. "/ws-echo");
  16084. client.enable_server_certificate_verification(false);
  16085. client.set_read_timeout(2, 0);
  16086. client.set_write_timeout(2, 0);
  16087. ASSERT_TRUE(client.connect());
  16088. ASSERT_TRUE(client.is_open());
  16089. ASSERT_TRUE(client.send("still open"));
  16090. // Intentionally do NOT call client.close(): leaving scope runs
  16091. // shutdown_and_close() with the WebSocket still open, which must send the
  16092. // close frame while the TLS session is still alive.
  16093. }
  16094. }
  16095. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16096. // shutdown_and_close() at the start of connect(), reproducing the same
  16097. // use-after-free within the test body rather than at scope exit. The second
  16098. // connect must succeed and echo, proving the close handshake ran over a live
  16099. // session. See the note above about memory-tool requirements.
  16100. TEST_F(WebSocketSSLIntegrationTest,
  16101. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16102. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16103. "/ws-echo");
  16104. client.enable_server_certificate_verification(false);
  16105. client.set_read_timeout(2, 0);
  16106. client.set_write_timeout(2, 0);
  16107. ASSERT_TRUE(client.connect());
  16108. ASSERT_TRUE(client.is_open());
  16109. ASSERT_TRUE(client.send("still open"));
  16110. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16111. // the still-open connection, which must not touch a freed TLS session.
  16112. ASSERT_TRUE(client.connect());
  16113. ASSERT_TRUE(client.is_open());
  16114. ASSERT_TRUE(client.send("after reconnect"));
  16115. std::string msg;
  16116. EXPECT_EQ(ws::Text, client.read(msg));
  16117. EXPECT_EQ("after reconnect", msg);
  16118. client.close();
  16119. }
  16120. #endif
  16121. #ifdef CPPHTTPLIB_SSL_ENABLED
  16122. class WebSocketSSLCATest : public ::testing::Test {
  16123. protected:
  16124. void SetUp() override {
  16125. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16126. SERVER_PRIVATE_KEY_FILE);
  16127. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16128. std::string msg;
  16129. while (ws.read(msg)) {
  16130. ws.send(msg);
  16131. }
  16132. });
  16133. port_ = server_->bind_to_any_port("127.0.0.1");
  16134. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16135. server_->wait_until_ready();
  16136. }
  16137. void TearDown() override {
  16138. server_->stop();
  16139. if (server_thread_.joinable()) { server_thread_.join(); }
  16140. }
  16141. std::string url() const {
  16142. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16143. }
  16144. std::unique_ptr<SSLServer> server_;
  16145. std::thread server_thread_;
  16146. int port_ = 0;
  16147. };
  16148. // A custom CA loaded as PEM verifies the server with full certificate
  16149. // verification enabled
  16150. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16151. ws::WebSocketClient client(url());
  16152. std::string cert;
  16153. read_file(SERVER_CERT2_FILE, cert);
  16154. client.load_ca_cert_store(cert.c_str(), cert.size());
  16155. ASSERT_TRUE(client.connect());
  16156. ASSERT_TRUE(client.send("hello"));
  16157. std::string msg;
  16158. EXPECT_EQ(ws::Text, client.read(msg));
  16159. EXPECT_EQ("hello", msg);
  16160. client.close();
  16161. }
  16162. // A custom CA that does not cover the server must fail verification (the
  16163. // custom CA is exclusive; system certs are not loaded alongside it)
  16164. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16165. ws::WebSocketClient client(url());
  16166. std::string cert;
  16167. read_file(CLIENT_CA_CERT_FILE, cert);
  16168. client.load_ca_cert_store(cert.c_str(), cert.size());
  16169. ASSERT_FALSE(client.connect());
  16170. }
  16171. // Regression test: reconnecting with a native custom CA store used to reuse
  16172. // a store handle the previous TLS context had already freed (use-after-free
  16173. // under the OpenSSL backend). The context now lives as long as the client.
  16174. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16175. ws::WebSocketClient client(url());
  16176. std::string cert;
  16177. read_file(SERVER_CERT2_FILE, cert);
  16178. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16179. ASSERT_TRUE(client.connect());
  16180. client.close();
  16181. ASSERT_TRUE(client.connect());
  16182. ASSERT_TRUE(client.send("again"));
  16183. std::string msg;
  16184. EXPECT_EQ(ws::Text, client.read(msg));
  16185. EXPECT_EQ("again", msg);
  16186. client.close();
  16187. }
  16188. // Regression test: a certificate with a trusted chain but no identity match
  16189. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16190. // verification entirely for IP hosts, so this connection succeeded there.
  16191. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16192. // chain verification while the identity check must still fail.
  16193. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16195. ASSERT_TRUE(svr.is_valid());
  16196. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16197. std::string msg;
  16198. while (ws.read(msg)) {
  16199. ws.send(msg);
  16200. }
  16201. });
  16202. auto port = svr.bind_to_any_port("127.0.0.1");
  16203. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16204. auto se = detail::scope_exit([&] {
  16205. svr.stop();
  16206. t.join();
  16207. });
  16208. svr.wait_until_ready();
  16209. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16210. "/echo");
  16211. std::string cert;
  16212. read_file(SERVER_CERT_FILE, cert);
  16213. client.load_ca_cert_store(cert.c_str(), cert.size());
  16214. ASSERT_FALSE(client.connect());
  16215. }
  16216. #endif
  16217. #if !defined(_WIN32)
  16218. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16219. auto secret_dir = std::string("./symlink_test_secret");
  16220. auto served_dir = std::string("./symlink_test_served");
  16221. auto secret_file = secret_dir + "/secret.txt";
  16222. auto symlink_path = served_dir + "/escape";
  16223. // Setup: create directories and files
  16224. mkdir(secret_dir.c_str(), 0755);
  16225. mkdir(served_dir.c_str(), 0755);
  16226. {
  16227. std::ofstream ofs(secret_file);
  16228. ofs << "SECRET_DATA";
  16229. }
  16230. // Create symlink using absolute path so it resolves correctly
  16231. #ifdef PATH_MAX
  16232. char abs_secret[PATH_MAX];
  16233. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16234. #else
  16235. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16236. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16237. ASSERT_NE(nullptr, abs_secret);
  16238. #endif
  16239. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16240. auto se = detail::scope_exit([&] {
  16241. unlink(symlink_path.c_str());
  16242. unlink(secret_file.c_str());
  16243. rmdir(served_dir.c_str());
  16244. rmdir(secret_dir.c_str());
  16245. });
  16246. Server svr;
  16247. svr.set_mount_point("/", served_dir);
  16248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16249. auto se2 = detail::scope_exit([&] {
  16250. svr.stop();
  16251. listen_thread.join();
  16252. });
  16253. svr.wait_until_ready();
  16254. Client cli("localhost", PORT);
  16255. // Symlink pointing outside base dir should be blocked
  16256. auto res = cli.Get("/escape/secret.txt");
  16257. ASSERT_TRUE(res);
  16258. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16259. }
  16260. #endif
  16261. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16262. // A GET request with Content-Length to a static file handler must have its
  16263. // body drained before the keep-alive connection is reused. Otherwise the
  16264. // unread body bytes are interpreted as the next HTTP request.
  16265. //
  16266. // The body is sent AFTER receiving the first response (as in the original
  16267. // PoC) so that the stream_line_reader cannot buffer it together with the
  16268. // headers of the first request.
  16269. Server svr;
  16270. svr.set_mount_point("/", "./www");
  16271. std::atomic<int> smuggled_count(0);
  16272. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16273. smuggled_count++;
  16274. res.set_content("oops", "text/plain");
  16275. });
  16276. auto port = svr.bind_to_any_port("localhost");
  16277. thread t = thread([&] { svr.listen_after_bind(); });
  16278. auto se = detail::scope_exit([&] {
  16279. svr.stop();
  16280. t.join();
  16281. });
  16282. svr.wait_until_ready();
  16283. auto error = Error::Success;
  16284. auto sock = detail::create_client_socket(
  16285. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16286. /*connection_timeout_sec=*/2, 0,
  16287. /*read_timeout_sec=*/2, 0,
  16288. /*write_timeout_sec=*/2, 0, std::string(), error);
  16289. ASSERT_NE(INVALID_SOCKET, sock);
  16290. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16291. // The "smuggled" request will be sent as the body of the outer GET
  16292. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16293. "Host: localhost\r\n"
  16294. "Connection: close\r\n"
  16295. "\r\n";
  16296. // Step 1: Send only the outer request headers (no body yet)
  16297. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16298. "Host: localhost\r\n"
  16299. "Content-Length: " +
  16300. std::to_string(smuggled.size()) +
  16301. "\r\n"
  16302. "\r\n";
  16303. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16304. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16305. // Step 2: Read the first response (server serves file without reading body)
  16306. std::string first_response;
  16307. char buf[4096];
  16308. for (;;) {
  16309. auto n = recv(sock, buf, sizeof(buf), 0);
  16310. if (n <= 0) break;
  16311. first_response.append(buf, static_cast<size_t>(n));
  16312. // Stop once we have a complete response (headers + body)
  16313. auto hdr_end = first_response.find("\r\n\r\n");
  16314. if (hdr_end != std::string::npos) {
  16315. // Check for Content-Length to know when the body is complete
  16316. auto cl_pos = first_response.find("Content-Length:");
  16317. if (cl_pos != std::string::npos) {
  16318. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16319. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16320. auto cl = std::stoul(
  16321. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16322. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16323. } else {
  16324. break; // No Content-Length, assume headers-only response
  16325. }
  16326. }
  16327. }
  16328. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16329. // Step 3: Now send the body, which looks like a new HTTP request.
  16330. // On a vulnerable server the keep-alive loop reads this as a second request.
  16331. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16332. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16333. // Step 4: Try to read a second response (should NOT exist after fix)
  16334. std::string second_response;
  16335. for (;;) {
  16336. auto n = recv(sock, buf, sizeof(buf), 0);
  16337. if (n <= 0) break;
  16338. second_response.append(buf, static_cast<size_t>(n));
  16339. }
  16340. // The smuggled request must NOT have been processed
  16341. EXPECT_EQ(0, smuggled_count.load());
  16342. }
  16343. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16344. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16345. // must be rejected with 400 Bad Request.
  16346. Server svr;
  16347. svr.Post("/test", [&](const Request &, Response &res) {
  16348. res.set_content("ok", "text/plain");
  16349. });
  16350. thread t = thread([&] { svr.listen(HOST, PORT); });
  16351. auto se = detail::scope_exit([&] {
  16352. svr.stop();
  16353. t.join();
  16354. ASSERT_FALSE(svr.is_running());
  16355. });
  16356. svr.wait_until_ready();
  16357. // Exact "chunked"
  16358. {
  16359. auto req = "POST /test HTTP/1.1\r\n"
  16360. "Host: localhost\r\n"
  16361. "Content-Length: 5\r\n"
  16362. "Transfer-Encoding: chunked\r\n"
  16363. "Connection: close\r\n"
  16364. "\r\n"
  16365. "hello";
  16366. std::string response;
  16367. ASSERT_TRUE(send_request(1, req, &response));
  16368. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16369. response.substr(0, response.find("\r\n")));
  16370. }
  16371. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16372. {
  16373. auto req = "POST /test HTTP/1.1\r\n"
  16374. "Host: localhost\r\n"
  16375. "Content-Length: 5\r\n"
  16376. "Transfer-Encoding: gzip, chunked\r\n"
  16377. "Connection: close\r\n"
  16378. "\r\n"
  16379. "hello";
  16380. std::string response;
  16381. ASSERT_TRUE(send_request(1, req, &response));
  16382. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16383. response.substr(0, response.find("\r\n")));
  16384. }
  16385. }
  16386. // Regression for issue #2450: a DELETE without Content-Length on a
  16387. // keep-alive connection must not let the post-response drain consume the
  16388. // next request's bytes.
  16389. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16390. Server svr;
  16391. std::atomic<int> delete_count(0);
  16392. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16393. delete_count++;
  16394. res.status = StatusCode::NoContent_204;
  16395. });
  16396. auto port = svr.bind_to_any_port(HOST);
  16397. thread t = thread([&] { svr.listen_after_bind(); });
  16398. auto se = detail::scope_exit([&] {
  16399. svr.stop();
  16400. t.join();
  16401. });
  16402. svr.wait_until_ready();
  16403. auto error = Error::Success;
  16404. auto sock = detail::create_client_socket(
  16405. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16406. /*connection_timeout_sec=*/2, 0,
  16407. /*read_timeout_sec=*/2, 0,
  16408. /*write_timeout_sec=*/2, 0, std::string(), error);
  16409. ASSERT_NE(INVALID_SOCKET, sock);
  16410. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16411. auto send_request_and_read_response = [&](const std::string &req,
  16412. std::string &out) -> bool {
  16413. auto sent = send(sock, req.data(), req.size(), 0);
  16414. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16415. char buf[4096];
  16416. for (;;) {
  16417. auto n = recv(sock, buf, sizeof(buf), 0);
  16418. if (n <= 0) { return !out.empty(); }
  16419. out.append(buf, static_cast<size_t>(n));
  16420. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16421. }
  16422. };
  16423. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16424. "Host: localhost\r\n"
  16425. "\r\n";
  16426. std::string resp1;
  16427. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16428. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16429. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16430. "Host: localhost\r\n"
  16431. "Connection: close\r\n"
  16432. "\r\n";
  16433. std::string resp2;
  16434. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16435. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16436. EXPECT_EQ(2, delete_count.load());
  16437. }
  16438. namespace no_proxy_test {
  16439. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16440. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16441. // calling listen().
  16442. class ScopedServer {
  16443. public:
  16444. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16445. ~ScopedServer() {
  16446. svr_.stop();
  16447. if (th_.joinable()) { th_.join(); }
  16448. }
  16449. Server &svr() { return svr_; }
  16450. int port() const { return port_; }
  16451. void listen() {
  16452. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16453. svr_.wait_until_ready();
  16454. }
  16455. private:
  16456. Server svr_;
  16457. std::thread th_;
  16458. int port_ = 0;
  16459. };
  16460. class ProxyAndTargetServers {
  16461. public:
  16462. ProxyAndTargetServers() {
  16463. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16464. proxy_hits_++;
  16465. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16466. res.set_content("via-proxy", "text/plain");
  16467. });
  16468. target_.Get(".*", [this](const Request &req, Response &res) {
  16469. target_hits_++;
  16470. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16471. res.set_content("direct", "text/plain");
  16472. });
  16473. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16474. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16475. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16476. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16477. proxy_mock_.wait_until_ready();
  16478. target_.wait_until_ready();
  16479. }
  16480. ~ProxyAndTargetServers() {
  16481. proxy_mock_.stop();
  16482. target_.stop();
  16483. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16484. if (target_thread_.joinable()) { target_thread_.join(); }
  16485. }
  16486. Server &proxy_mock() { return proxy_mock_; }
  16487. Server &target() { return target_; }
  16488. int proxy_port() const { return proxy_port_; }
  16489. int target_port() const { return target_port_; }
  16490. int proxy_hits() const { return proxy_hits_.load(); }
  16491. int target_hits() const { return target_hits_.load(); }
  16492. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16493. void reset_counters() {
  16494. proxy_hits_ = 0;
  16495. target_hits_ = 0;
  16496. last_had_proxy_authz_ = false;
  16497. }
  16498. private:
  16499. Server proxy_mock_;
  16500. Server target_;
  16501. std::thread proxy_thread_;
  16502. std::thread target_thread_;
  16503. int proxy_port_ = 0;
  16504. int target_port_ = 0;
  16505. std::atomic<int> proxy_hits_{0};
  16506. std::atomic<int> target_hits_{0};
  16507. std::atomic<bool> last_had_proxy_authz_{false};
  16508. };
  16509. inline std::unique_ptr<Client> make_client(const std::string &host,
  16510. ProxyAndTargetServers &s) {
  16511. auto cli = detail::make_unique<Client>(host, s.target_port());
  16512. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16513. cli->set_proxy("127.0.0.1", s.proxy_port());
  16514. return cli;
  16515. }
  16516. } // namespace no_proxy_test
  16517. using no_proxy_test::make_client;
  16518. using no_proxy_test::ProxyAndTargetServers;
  16519. TEST(NoProxyTest, ExactHostnameBypasses) {
  16520. ProxyAndTargetServers s;
  16521. auto cli = make_client("example.com", s);
  16522. cli->set_no_proxy({"example.com"});
  16523. auto res = cli->Get("/");
  16524. ASSERT_TRUE(res);
  16525. EXPECT_EQ(0, s.proxy_hits());
  16526. EXPECT_EQ(1, s.target_hits());
  16527. }
  16528. TEST(NoProxyTest, SubdomainBypasses) {
  16529. ProxyAndTargetServers s;
  16530. auto cli = make_client("foo.example.com", s);
  16531. cli->set_no_proxy({"example.com"});
  16532. auto res = cli->Get("/");
  16533. ASSERT_TRUE(res);
  16534. EXPECT_EQ(0, s.proxy_hits());
  16535. EXPECT_EQ(1, s.target_hits());
  16536. }
  16537. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16538. // Regression guard: "evilexample.com" must not be considered a subdomain
  16539. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16540. // check would let traffic bypass the proxy and leak credentials direct
  16541. // to the attacker host.
  16542. ProxyAndTargetServers s;
  16543. auto cli = make_client("evilexample.com", s);
  16544. cli->set_no_proxy({"example.com"});
  16545. auto res = cli->Get("/");
  16546. ASSERT_TRUE(res);
  16547. EXPECT_GE(s.proxy_hits(), 1);
  16548. EXPECT_EQ(0, s.target_hits());
  16549. }
  16550. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16551. ProxyAndTargetServers s;
  16552. auto cli = make_client("example.com.evil.com", s);
  16553. cli->set_no_proxy({"example.com"});
  16554. auto res = cli->Get("/");
  16555. ASSERT_TRUE(res);
  16556. EXPECT_GE(s.proxy_hits(), 1);
  16557. EXPECT_EQ(0, s.target_hits());
  16558. }
  16559. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16560. ProxyAndTargetServers s;
  16561. auto cli = make_client("example.com", s);
  16562. cli->set_no_proxy({".example.com"});
  16563. auto res = cli->Get("/");
  16564. ASSERT_TRUE(res);
  16565. EXPECT_EQ(0, s.proxy_hits());
  16566. EXPECT_EQ(1, s.target_hits());
  16567. }
  16568. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16569. ProxyAndTargetServers s;
  16570. auto cli = make_client("Example.COM", s);
  16571. cli->set_no_proxy({"EXAMPLE.com"});
  16572. auto res = cli->Get("/");
  16573. ASSERT_TRUE(res);
  16574. EXPECT_EQ(0, s.proxy_hits());
  16575. EXPECT_EQ(1, s.target_hits());
  16576. }
  16577. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16578. ProxyAndTargetServers s;
  16579. auto cli = make_client("example.com.", s);
  16580. cli->set_no_proxy({"example.com"});
  16581. auto res = cli->Get("/");
  16582. ASSERT_TRUE(res);
  16583. EXPECT_EQ(0, s.proxy_hits());
  16584. EXPECT_EQ(1, s.target_hits());
  16585. }
  16586. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16587. // Trailing dots must be normalized on BOTH sides — host and entry.
  16588. // An implementation that only strips the host-side trailing dot would
  16589. // fail to match host "example.com" against entry "example.com." because
  16590. // a literal substring search would compare 11 chars against 12.
  16591. ProxyAndTargetServers s;
  16592. auto cli = make_client("example.com", s);
  16593. cli->set_no_proxy({"example.com."});
  16594. auto res = cli->Get("/");
  16595. ASSERT_TRUE(res);
  16596. EXPECT_EQ(0, s.proxy_hits());
  16597. EXPECT_EQ(1, s.target_hits());
  16598. }
  16599. TEST(NoProxyTest, WildcardBypassesEverything) {
  16600. ProxyAndTargetServers s;
  16601. auto cli = make_client("anything.invalid.test", s);
  16602. cli->set_no_proxy({"*"});
  16603. auto res = cli->Get("/");
  16604. ASSERT_TRUE(res);
  16605. EXPECT_EQ(0, s.proxy_hits());
  16606. EXPECT_EQ(1, s.target_hits());
  16607. }
  16608. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16609. ProxyAndTargetServers s;
  16610. Client cli("127.0.0.1", s.target_port());
  16611. cli.set_proxy("127.0.0.1", s.proxy_port());
  16612. cli.set_no_proxy({"127.0.0.1"});
  16613. auto res = cli.Get("/");
  16614. ASSERT_TRUE(res);
  16615. EXPECT_EQ(0, s.proxy_hits());
  16616. EXPECT_EQ(1, s.target_hits());
  16617. }
  16618. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16619. ProxyAndTargetServers s;
  16620. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16621. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16622. cli.set_proxy("127.0.0.1", s.proxy_port());
  16623. cli.set_no_proxy({"::1"});
  16624. auto res = cli.Get("/");
  16625. ASSERT_TRUE(res);
  16626. EXPECT_EQ(0, s.proxy_hits());
  16627. EXPECT_EQ(1, s.target_hits());
  16628. }
  16629. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16630. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16631. // must still be recognized as IPv6 for CIDR matching. Implementations
  16632. // that detect IPv6 only when the host begins with '[' would parse the
  16633. // host as a hostname and miss the match.
  16634. ProxyAndTargetServers s;
  16635. Client cli("fe80::1", s.target_port());
  16636. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16637. cli.set_proxy("127.0.0.1", s.proxy_port());
  16638. cli.set_no_proxy({"fe80::/10"});
  16639. auto res = cli.Get("/");
  16640. ASSERT_TRUE(res);
  16641. EXPECT_EQ(0, s.proxy_hits());
  16642. EXPECT_EQ(1, s.target_hits());
  16643. }
  16644. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16645. ProxyAndTargetServers s;
  16646. Client cli("::1", s.target_port());
  16647. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16648. cli.set_proxy("127.0.0.1", s.proxy_port());
  16649. cli.set_no_proxy({"[::1]"});
  16650. auto res = cli.Get("/");
  16651. ASSERT_TRUE(res);
  16652. EXPECT_EQ(0, s.proxy_hits());
  16653. EXPECT_EQ(1, s.target_hits());
  16654. }
  16655. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16656. ProxyAndTargetServers s;
  16657. Client cli("fe80::1", s.target_port());
  16658. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16659. cli.set_proxy("127.0.0.1", s.proxy_port());
  16660. cli.set_no_proxy({"[fe80::]/10"});
  16661. auto res = cli.Get("/");
  16662. ASSERT_TRUE(res);
  16663. EXPECT_EQ(0, s.proxy_hits());
  16664. EXPECT_EQ(1, s.target_hits());
  16665. }
  16666. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16667. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16668. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16669. // tricks via address-family conversion.
  16670. ProxyAndTargetServers s;
  16671. Client cli("::ffff:127.0.0.1", s.target_port());
  16672. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16673. cli.set_proxy("127.0.0.1", s.proxy_port());
  16674. cli.set_no_proxy({"127.0.0.1"});
  16675. auto res = cli.Get("/");
  16676. ASSERT_TRUE(res);
  16677. EXPECT_GE(s.proxy_hits(), 1);
  16678. EXPECT_EQ(0, s.target_hits());
  16679. }
  16680. TEST(NoProxyTest, IPv4CidrMatch) {
  16681. ProxyAndTargetServers s;
  16682. Client cli("127.0.0.1", s.target_port());
  16683. cli.set_proxy("127.0.0.1", s.proxy_port());
  16684. cli.set_no_proxy({"127.0.0.0/8"});
  16685. auto res = cli.Get("/");
  16686. ASSERT_TRUE(res);
  16687. EXPECT_EQ(0, s.proxy_hits());
  16688. EXPECT_EQ(1, s.target_hits());
  16689. }
  16690. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16691. ProxyAndTargetServers s;
  16692. Client cli("127.0.0.1", s.target_port());
  16693. cli.set_proxy("127.0.0.1", s.proxy_port());
  16694. cli.set_no_proxy({"10.0.0.0/8"});
  16695. auto res = cli.Get("/");
  16696. ASSERT_TRUE(res);
  16697. EXPECT_GE(s.proxy_hits(), 1);
  16698. EXPECT_EQ(0, s.target_hits());
  16699. }
  16700. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16701. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16702. // IPv4 target matches.
  16703. ProxyAndTargetServers s;
  16704. Client cli("127.0.0.1", s.target_port());
  16705. cli.set_proxy("127.0.0.1", s.proxy_port());
  16706. cli.set_no_proxy({"0.0.0.0/0"});
  16707. auto res = cli.Get("/");
  16708. ASSERT_TRUE(res);
  16709. EXPECT_EQ(0, s.proxy_hits());
  16710. EXPECT_EQ(1, s.target_hits());
  16711. }
  16712. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16713. ProxyAndTargetServers s;
  16714. Client cli("127.0.0.1", s.target_port());
  16715. cli.set_proxy("127.0.0.1", s.proxy_port());
  16716. cli.set_no_proxy({"127.0.0.1"});
  16717. auto res = cli.Get("/");
  16718. ASSERT_TRUE(res);
  16719. EXPECT_EQ(0, s.proxy_hits());
  16720. EXPECT_EQ(1, s.target_hits());
  16721. }
  16722. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16723. ProxyAndTargetServers s;
  16724. Client cli("127.0.0.1", s.target_port());
  16725. cli.set_proxy("127.0.0.1", s.proxy_port());
  16726. cli.set_no_proxy({"127.0.0.0/33"});
  16727. auto res = cli.Get("/");
  16728. ASSERT_TRUE(res);
  16729. EXPECT_GE(s.proxy_hits(), 1);
  16730. EXPECT_EQ(0, s.target_hits());
  16731. }
  16732. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16733. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16734. ProxyAndTargetServers s;
  16735. Client cli("127.0.0.1", s.target_port());
  16736. cli.set_proxy("127.0.0.1", s.proxy_port());
  16737. cli.set_no_proxy({"127.0.0.1/"});
  16738. auto res = cli.Get("/");
  16739. ASSERT_TRUE(res);
  16740. EXPECT_GE(s.proxy_hits(), 1);
  16741. EXPECT_EQ(0, s.target_hits());
  16742. }
  16743. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16744. ProxyAndTargetServers s;
  16745. auto cli = make_client("internal.corp", s);
  16746. cli->set_proxy_basic_auth("u", "p");
  16747. cli->set_no_proxy({"internal.corp"});
  16748. auto res = cli->Get("/");
  16749. ASSERT_TRUE(res);
  16750. EXPECT_EQ(1, s.target_hits());
  16751. EXPECT_EQ(0, s.proxy_hits());
  16752. EXPECT_FALSE(s.last_had_proxy_authz())
  16753. << "Proxy-Authorization must not be sent direct to the target";
  16754. }
  16755. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16756. ProxyAndTargetServers s;
  16757. auto cli = make_client("public.example", s);
  16758. cli->set_proxy_basic_auth("u", "p");
  16759. cli->set_no_proxy({"internal.corp"}); // does not match
  16760. auto res = cli->Get("/");
  16761. ASSERT_TRUE(res);
  16762. EXPECT_GE(s.proxy_hits(), 1);
  16763. EXPECT_TRUE(s.last_had_proxy_authz());
  16764. }
  16765. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16766. ProxyAndTargetServers s;
  16767. auto cli = make_client("anything.test", s);
  16768. auto res = cli->Get("/");
  16769. ASSERT_TRUE(res);
  16770. EXPECT_GE(s.proxy_hits(), 1);
  16771. EXPECT_EQ(0, s.target_hits());
  16772. }
  16773. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16774. ProxyAndTargetServers s;
  16775. auto cli = make_client("example.com", s);
  16776. cli->set_no_proxy({"example.com:8080"});
  16777. auto res = cli->Get("/");
  16778. ASSERT_TRUE(res);
  16779. EXPECT_GE(s.proxy_hits(), 1);
  16780. EXPECT_EQ(0, s.target_hits());
  16781. }
  16782. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16783. ProxyAndTargetServers s;
  16784. auto cli = make_client("anything.test", s);
  16785. cli->set_no_proxy({"", " ", "\t"});
  16786. auto res = cli->Get("/");
  16787. ASSERT_TRUE(res);
  16788. EXPECT_GE(s.proxy_hits(), 1);
  16789. EXPECT_EQ(0, s.target_hits());
  16790. }
  16791. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16792. // An entry with leading/trailing whitespace must still match — env-style
  16793. // values are commonly pasted with stray spaces and an implementation
  16794. // that feeds the raw token directly to inet_pton would fail to match
  16795. // valid CIDRs because of the spaces.
  16796. ProxyAndTargetServers s;
  16797. Client cli("127.0.0.1", s.target_port());
  16798. cli.set_proxy("127.0.0.1", s.proxy_port());
  16799. cli.set_no_proxy({" 127.0.0.0/8 "});
  16800. auto res = cli.Get("/");
  16801. ASSERT_TRUE(res);
  16802. EXPECT_EQ(0, s.proxy_hits());
  16803. EXPECT_EQ(1, s.target_hits());
  16804. }
  16805. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16806. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16807. // go direct and must NOT carry Proxy-Authorization.
  16808. std::atomic<int> proxy_hits{0};
  16809. std::atomic<int> target_hits{0};
  16810. std::atomic<bool> target_saw_authz{false};
  16811. no_proxy_test::ScopedServer proxy_mock, target;
  16812. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16813. proxy_hits++;
  16814. res.status = 302;
  16815. res.set_header("Location", "http://127.0.0.1:" +
  16816. std::to_string(target.port()) + "/landed");
  16817. });
  16818. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16819. target_hits++;
  16820. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  16821. res.set_content("direct", "text/plain");
  16822. });
  16823. proxy_mock.listen();
  16824. target.listen();
  16825. Client cli("public.example", target.port());
  16826. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16827. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16828. cli.set_proxy_basic_auth("u", "p");
  16829. cli.set_no_proxy({"127.0.0.1"});
  16830. cli.set_follow_location(true);
  16831. auto res = cli.Get("/redir");
  16832. ASSERT_TRUE(res);
  16833. EXPECT_GE(proxy_hits.load(), 1);
  16834. EXPECT_GE(target_hits.load(), 1);
  16835. EXPECT_FALSE(target_saw_authz.load());
  16836. }
  16837. #ifdef CPPHTTPLIB_SSL_ENABLED
  16838. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  16839. // Direct origin replying 407 must not trigger the digest retry; otherwise
  16840. // proxy creds would be sent to the (possibly hostile) origin.
  16841. std::atomic<int> target_hits{0};
  16842. std::atomic<bool> target_saw_proxy_authz{false};
  16843. no_proxy_test::ScopedServer target;
  16844. target.svr().Get(".*", [&](const Request &req, Response &res) {
  16845. target_hits++;
  16846. if (req.has_header("Proxy-Authorization")) {
  16847. target_saw_proxy_authz = true;
  16848. }
  16849. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16850. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  16851. "nonce=\"abc\", algorithm=MD5");
  16852. });
  16853. target.listen();
  16854. // The proxy address is set to the target's port: the bypass MUST kick in;
  16855. // if it doesn't, the test still routes "via proxy" to the same server and
  16856. // the Proxy-Authorization assertion below catches the leak.
  16857. Client cli("evil.example", target.port());
  16858. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  16859. cli.set_proxy("127.0.0.1", target.port());
  16860. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16861. cli.set_no_proxy({"evil.example"});
  16862. auto res = cli.Get("/x");
  16863. ASSERT_TRUE(res);
  16864. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16865. EXPECT_EQ(1, target_hits.load());
  16866. EXPECT_FALSE(target_saw_proxy_authz.load());
  16867. }
  16868. #endif
  16869. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  16870. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  16871. std::atomic<int> proxy_hits{0};
  16872. std::atomic<int> bypass_hits{0};
  16873. std::atomic<bool> proxy_saw_c_url{false};
  16874. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  16875. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  16876. proxy_hits++;
  16877. if (req.path.find("/start") != std::string::npos) {
  16878. res.status = 302;
  16879. res.set_header("Location", "http://127.0.0.1:" +
  16880. std::to_string(bypass_server.port()) +
  16881. "/middle");
  16882. return;
  16883. }
  16884. if (req.path.find("/end") != std::string::npos) {
  16885. proxy_saw_c_url = true;
  16886. res.set_content("c-via-proxy", "text/plain");
  16887. return;
  16888. }
  16889. res.set_content("unexpected", "text/plain");
  16890. });
  16891. // public.example's "advertised" port is arbitrary (the request never lands
  16892. // there — it goes through the proxy), but use a dynamic value to stay
  16893. // friendly with sharded parallel runs.
  16894. int public_port = bypass_server.port();
  16895. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  16896. bypass_hits++;
  16897. res.status = 302;
  16898. res.set_header("Location", "http://public.example:" +
  16899. std::to_string(public_port) + "/end");
  16900. });
  16901. proxy_mock.listen();
  16902. bypass_server.listen();
  16903. Client cli("public.example", public_port);
  16904. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16905. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16906. cli.set_no_proxy({"127.0.0.1"});
  16907. cli.set_follow_location(true);
  16908. auto res = cli.Get("/start");
  16909. ASSERT_TRUE(res);
  16910. EXPECT_EQ(StatusCode::OK_200, res->status);
  16911. EXPECT_EQ("c-via-proxy", res->body);
  16912. EXPECT_GE(proxy_hits.load(), 2);
  16913. EXPECT_GE(bypass_hits.load(), 1);
  16914. EXPECT_TRUE(proxy_saw_c_url.load());
  16915. }
  16916. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  16917. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  16918. // request reconnects to the correct endpoint.
  16919. std::atomic<int> proxy_hits{0};
  16920. std::atomic<int> target_hits{0};
  16921. no_proxy_test::ScopedServer proxy_mock, target;
  16922. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  16923. proxy_hits++;
  16924. res.set_content("via-proxy", "text/plain");
  16925. });
  16926. target.svr().Get(".*", [&](const Request &, Response &res) {
  16927. target_hits++;
  16928. res.set_content("direct", "text/plain");
  16929. });
  16930. proxy_mock.listen();
  16931. target.listen();
  16932. Client cli("public.example", target.port());
  16933. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16934. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16935. cli.set_keep_alive(true);
  16936. auto res1 = cli.Get("/a");
  16937. ASSERT_TRUE(res1);
  16938. EXPECT_EQ("via-proxy", res1->body);
  16939. EXPECT_EQ(1, proxy_hits.load());
  16940. EXPECT_EQ(0, target_hits.load());
  16941. cli.set_no_proxy({"public.example"});
  16942. auto res2 = cli.Get("/b");
  16943. ASSERT_TRUE(res2);
  16944. EXPECT_EQ("direct", res2->body);
  16945. EXPECT_EQ(1, proxy_hits.load());
  16946. EXPECT_EQ(1, target_hits.load());
  16947. }
  16948. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16949. namespace proxy_tunnel_test {
  16950. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16951. class ScopedSSLServer {
  16952. public:
  16953. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16954. port_ = svr_.bind_to_any_port("127.0.0.1");
  16955. }
  16956. ~ScopedSSLServer() {
  16957. svr_.stop();
  16958. if (th_.joinable()) { th_.join(); }
  16959. }
  16960. SSLServer &svr() { return svr_; }
  16961. int port() const { return port_; }
  16962. void listen() {
  16963. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16964. svr_.wait_until_ready();
  16965. }
  16966. private:
  16967. SSLServer svr_;
  16968. std::thread th_;
  16969. int port_ = 0;
  16970. };
  16971. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16972. class ScopedConnectProxy {
  16973. public:
  16974. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16975. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16976. if (listen_fd_ < 0) { return; }
  16977. int yes = 1;
  16978. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16979. sockaddr_in a{};
  16980. a.sin_family = AF_INET;
  16981. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16982. a.sin_port = 0;
  16983. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16984. return;
  16985. }
  16986. socklen_t alen = sizeof(a);
  16987. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16988. 0) {
  16989. return;
  16990. }
  16991. port_ = ntohs(a.sin_port);
  16992. if (::listen(listen_fd_, 1) != 0) { return; }
  16993. th_ = std::thread([this] { run(); });
  16994. }
  16995. ~ScopedConnectProxy() {
  16996. stop_ = true;
  16997. if (listen_fd_ >= 0) {
  16998. ::shutdown(listen_fd_, SHUT_RDWR);
  16999. ::close(listen_fd_);
  17000. }
  17001. if (th_.joinable()) { th_.join(); }
  17002. }
  17003. int port() const { return port_; }
  17004. int connect_hits() const { return connect_hits_.load(); }
  17005. private:
  17006. void run() {
  17007. while (!stop_.load()) {
  17008. fd_set rfds;
  17009. FD_ZERO(&rfds);
  17010. FD_SET(listen_fd_, &rfds);
  17011. timeval tv{0, 100 * 1000};
  17012. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17013. if (sel <= 0) { continue; }
  17014. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17015. if (client_fd < 0) { continue; }
  17016. std::string req;
  17017. char buf[2048];
  17018. while (req.find("\r\n\r\n") == std::string::npos) {
  17019. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17020. if (n <= 0) { break; }
  17021. req.append(buf, static_cast<size_t>(n));
  17022. }
  17023. if (req.compare(0, 7, "CONNECT") != 0) {
  17024. ::close(client_fd);
  17025. continue;
  17026. }
  17027. connect_hits_++;
  17028. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17029. ::send(client_fd, ok, std::strlen(ok), 0);
  17030. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17031. sockaddr_in o{};
  17032. o.sin_family = AF_INET;
  17033. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17034. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17035. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17036. 0) {
  17037. ::close(client_fd);
  17038. ::close(origin_fd);
  17039. continue;
  17040. }
  17041. auto forward = [](int from, int to) {
  17042. char b[8192];
  17043. for (;;) {
  17044. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17045. if (n <= 0) { break; }
  17046. ssize_t off = 0;
  17047. while (off < n) {
  17048. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17049. if (s <= 0) {
  17050. off = n;
  17051. break;
  17052. }
  17053. off += s;
  17054. }
  17055. }
  17056. ::shutdown(to, SHUT_WR);
  17057. };
  17058. std::thread t1([&] { forward(client_fd, origin_fd); });
  17059. std::thread t2([&] { forward(origin_fd, client_fd); });
  17060. t1.join();
  17061. t2.join();
  17062. ::close(client_fd);
  17063. ::close(origin_fd);
  17064. }
  17065. }
  17066. int forward_port_ = -1;
  17067. int listen_fd_ = -1;
  17068. int port_ = 0;
  17069. std::thread th_;
  17070. std::atomic<bool> stop_{false};
  17071. std::atomic<int> connect_hits_{0};
  17072. };
  17073. } // namespace proxy_tunnel_test
  17074. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17075. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17076. // retry; otherwise proxy creds would be sent to the origin.
  17077. std::atomic<int> origin_hits{0};
  17078. std::atomic<bool> origin_saw_proxy_authz{false};
  17079. proxy_tunnel_test::ScopedSSLServer origin;
  17080. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17081. origin_hits++;
  17082. if (req.has_header("Proxy-Authorization")) {
  17083. origin_saw_proxy_authz = true;
  17084. }
  17085. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17086. res.set_header("Proxy-Authenticate",
  17087. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17088. "algorithm=MD5");
  17089. });
  17090. origin.listen();
  17091. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17092. ASSERT_NE(0, proxy.port());
  17093. SSLClient cli(HOST, origin.port());
  17094. cli.enable_server_certificate_verification(false);
  17095. cli.set_proxy(HOST, proxy.port());
  17096. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17097. auto res = cli.Get("/x");
  17098. ASSERT_TRUE(res);
  17099. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17100. EXPECT_EQ(1, origin_hits.load());
  17101. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17102. EXPECT_EQ(1, proxy.connect_hits());
  17103. }
  17104. #endif