1
0

test.cc 550 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910
  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_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  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("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. TEST_F(ServerTest, GetStreamed2) {
  4331. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4334. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4335. EXPECT_EQ(true, res->has_header("Content-Range"));
  4336. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4337. EXPECT_EQ(std::string("ab"), res->body);
  4338. }
  4339. TEST_F(ServerTest, GetStreamed) {
  4340. auto res = cli_.Get("/streamed");
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ(std::string("aaabbb"), res->body);
  4345. }
  4346. TEST_F(ServerTest, GetStreamedWithRange1) {
  4347. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4350. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4351. EXPECT_EQ(true, res->has_header("Content-Range"));
  4352. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4353. EXPECT_EQ(std::string("def"), res->body);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithRange2) {
  4356. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4359. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4360. EXPECT_EQ(true, res->has_header("Content-Range"));
  4361. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4362. EXPECT_EQ(std::string("bcdefg"), res->body);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4365. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4368. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4371. EXPECT_EQ(std::string("efg"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4374. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4377. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(false, res->has_header("Content-Range"));
  4379. EXPECT_EQ(0U, res->body.size());
  4380. }
  4381. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4382. auto res = cli_.Get("/streamed-with-range",
  4383. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4384. "92233720368547758079223372036854775807"}});
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4387. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4388. EXPECT_EQ(false, res->has_header("Content-Range"));
  4389. EXPECT_EQ(0U, res->body.size());
  4390. }
  4391. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4392. auto res = cli_.Get(
  4393. "/with-range",
  4394. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4395. {"Accept-Encoding", ""}});
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4398. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4399. EXPECT_EQ(true, res->has_header("Content-Range"));
  4400. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4401. EXPECT_EQ(std::string("abcdefg"), res->body);
  4402. }
  4403. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4404. auto res = cli_.Get("/with-range", {
  4405. {"Range", "bytes=0-"},
  4406. {"Accept-Encoding", ""},
  4407. });
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4410. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4411. EXPECT_EQ(true, res->has_header("Content-Range"));
  4412. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4413. EXPECT_EQ(std::string("abcdefg"), res->body);
  4414. }
  4415. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4416. auto res =
  4417. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4420. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4421. EXPECT_EQ(false, res->has_header("Content-Range"));
  4422. EXPECT_EQ(267U, res->body.size());
  4423. // Check that both range contents are present
  4424. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4425. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4426. // Check that Content-Range headers are present for both ranges
  4427. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4428. std::string::npos);
  4429. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4430. std::string::npos);
  4431. }
  4432. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4433. Ranges ranges;
  4434. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4435. ranges.emplace_back(0, -1);
  4436. }
  4437. auto res =
  4438. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4441. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4442. EXPECT_EQ(false, res->has_header("Content-Range"));
  4443. EXPECT_EQ(0U, res->body.size());
  4444. }
  4445. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4446. auto res =
  4447. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4450. EXPECT_EQ(5U, res->body.size());
  4451. // Check that overlapping ranges are coalesced into a single range
  4452. EXPECT_EQ("bcdef", res->body);
  4453. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4454. // Should be single range, not multipart
  4455. EXPECT_TRUE(res->has_header("Content-Range"));
  4456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4457. }
  4458. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4459. auto res =
  4460. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4463. EXPECT_EQ(268U, res->body.size());
  4464. // Check that both range contents are present
  4465. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4466. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4467. // Check that Content-Range headers are present for both ranges
  4468. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4469. std::string::npos);
  4470. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4471. std::string::npos);
  4472. }
  4473. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4474. auto res =
  4475. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4476. ASSERT_TRUE(res);
  4477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4478. EXPECT_EQ(269U, res->body.size());
  4479. // Check that both duplicate range contents are present
  4480. size_t first_abc = res->body.find("abc\r\n");
  4481. EXPECT_TRUE(first_abc != std::string::npos);
  4482. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4483. EXPECT_TRUE(second_abc != std::string::npos);
  4484. // Check that Content-Range headers are present for both ranges
  4485. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4486. EXPECT_TRUE(first_range != std::string::npos);
  4487. size_t second_range =
  4488. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4489. EXPECT_TRUE(second_range != std::string::npos);
  4490. }
  4491. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4492. auto res = cli_.Get("/streamed-with-range?error",
  4493. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4496. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4497. EXPECT_EQ(false, res->has_header("Content-Range"));
  4498. EXPECT_EQ(0U, res->body.size());
  4499. }
  4500. TEST_F(ServerTest, GetStreamedEndless) {
  4501. uint64_t offset = 0;
  4502. auto res = cli_.Get("/streamed-cancel",
  4503. [&](const char * /*data*/, uint64_t data_length) {
  4504. if (offset < 100) {
  4505. offset += data_length;
  4506. return true;
  4507. }
  4508. return false;
  4509. });
  4510. ASSERT_TRUE(!res);
  4511. EXPECT_EQ(Error::Canceled, res.error());
  4512. }
  4513. TEST_F(ServerTest, ClientStop) {
  4514. std::atomic_size_t count{4};
  4515. std::vector<std::thread> threads;
  4516. for (auto i = count.load(); i != 0; --i) {
  4517. threads.emplace_back([&]() {
  4518. auto res = cli_.Get("/streamed-cancel",
  4519. [&](const char *, uint64_t) { return true; });
  4520. --count;
  4521. ASSERT_TRUE(!res);
  4522. EXPECT_TRUE(res.error() == Error::Canceled ||
  4523. res.error() == Error::Read || res.error() == Error::Write);
  4524. });
  4525. }
  4526. std::this_thread::sleep_for(std::chrono::seconds(2));
  4527. while (count != 0) {
  4528. cli_.stop();
  4529. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4530. }
  4531. for (auto &t : threads) {
  4532. t.join();
  4533. }
  4534. }
  4535. TEST_F(ServerTest, GetWithRange1) {
  4536. auto res = cli_.Get("/with-range", {
  4537. make_range_header({{3, 5}}),
  4538. {"Accept-Encoding", ""},
  4539. });
  4540. ASSERT_TRUE(res);
  4541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4542. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ(true, res->has_header("Content-Range"));
  4544. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4545. EXPECT_EQ(std::string("def"), res->body);
  4546. }
  4547. TEST_F(ServerTest, GetWithRange2) {
  4548. auto res = cli_.Get("/with-range", {
  4549. make_range_header({{1, -1}}),
  4550. {"Accept-Encoding", ""},
  4551. });
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4555. EXPECT_EQ(true, res->has_header("Content-Range"));
  4556. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4557. EXPECT_EQ(std::string("bcdefg"), res->body);
  4558. }
  4559. TEST_F(ServerTest, GetWithRange3) {
  4560. auto res = cli_.Get("/with-range", {
  4561. make_range_header({{0, 0}}),
  4562. {"Accept-Encoding", ""},
  4563. });
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4566. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4567. EXPECT_EQ(true, res->has_header("Content-Range"));
  4568. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4569. EXPECT_EQ(std::string("a"), res->body);
  4570. }
  4571. TEST_F(ServerTest, GetWithRange4) {
  4572. auto res = cli_.Get("/with-range", {
  4573. make_range_header({{-1, 2}}),
  4574. {"Accept-Encoding", ""},
  4575. });
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4578. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4579. EXPECT_EQ(true, res->has_header("Content-Range"));
  4580. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4581. EXPECT_EQ(std::string("fg"), res->body);
  4582. }
  4583. TEST_F(ServerTest, GetWithRange5) {
  4584. auto res = cli_.Get("/with-range", {
  4585. make_range_header({{0, 5}}),
  4586. {"Accept-Encoding", ""},
  4587. });
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4590. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4591. EXPECT_EQ(true, res->has_header("Content-Range"));
  4592. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4593. EXPECT_EQ(std::string("abcdef"), res->body);
  4594. }
  4595. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4596. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4597. ASSERT_TRUE(res);
  4598. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4599. }
  4600. TEST_F(ServerTest, GetWithRangeMultipart) {
  4601. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4604. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4605. EXPECT_EQ(false, res->has_header("Content-Range"));
  4606. EXPECT_EQ(267U, res->body.size());
  4607. }
  4608. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4609. auto res =
  4610. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4613. }
  4614. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4615. auto res = cli_.Get("/with-range-customized-response",
  4616. {{make_range_header({{1, 2}})}});
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4619. EXPECT_EQ(true, res->has_header("Content-Length"));
  4620. EXPECT_EQ(false, res->has_header("Content-Range"));
  4621. EXPECT_EQ(JSON_DATA, res->body);
  4622. }
  4623. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4624. auto res = cli_.Get("/with-range-customized-response",
  4625. {{make_range_header({{1, 2}, {4, 5}})}});
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4628. EXPECT_EQ(true, res->has_header("Content-Length"));
  4629. EXPECT_EQ(false, res->has_header("Content-Range"));
  4630. EXPECT_EQ(JSON_DATA, res->body);
  4631. }
  4632. TEST_F(ServerTest, Issue1772) {
  4633. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4636. }
  4637. TEST_F(ServerTest, Issue609) {
  4638. auto res = cli_.Delete("/issue609");
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ(std::string("ok"), res->body);
  4642. }
  4643. TEST_F(ServerTest, GetStreamedChunked) {
  4644. auto res = cli_.Get("/streamed-chunked");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ(std::string("123456789"), res->body);
  4648. }
  4649. TEST_F(ServerTest, GetStreamedChunked2) {
  4650. auto res = cli_.Get("/streamed-chunked2");
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. EXPECT_EQ(std::string("123456789"), res->body);
  4654. }
  4655. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4656. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(std::string("123456789"), res->body);
  4660. EXPECT_TRUE(res->has_header("Trailer"));
  4661. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4662. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4663. // Trailers are now stored separately from headers (security fix)
  4664. EXPECT_EQ(2U, res->trailers.size());
  4665. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4666. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4667. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4668. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4669. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4670. // Verify trailers are NOT in headers (security verification)
  4671. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4672. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4673. }
  4674. TEST_F(ServerTest, LargeChunkedPost) {
  4675. Request req;
  4676. req.method = "POST";
  4677. req.path = "/large-chunked";
  4678. std::string host_and_port;
  4679. host_and_port += HOST;
  4680. host_and_port += ":";
  4681. host_and_port += std::to_string(PORT);
  4682. req.headers.emplace("Host", host_and_port.c_str());
  4683. req.headers.emplace("Accept", "*/*");
  4684. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4685. req.headers.emplace("Content-Type", "text/plain");
  4686. req.headers.emplace("Content-Length", "0");
  4687. req.headers.emplace("Transfer-Encoding", "chunked");
  4688. std::string long_string(30 * 1024u, 'a');
  4689. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4690. // Attempt to make a large enough post to exceed OS buffers, to test that
  4691. // the server handles short reads if the full chunk data isn't available.
  4692. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4693. auto res = std::make_shared<Response>();
  4694. auto error = Error::Success;
  4695. auto ret = cli_.send(req, *res, error);
  4696. ASSERT_TRUE(ret);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4700. auto res = cli_.Get("/remote_addr");
  4701. ASSERT_TRUE(res);
  4702. EXPECT_EQ(StatusCode::OK_200, res->status);
  4703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4704. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4705. }
  4706. TEST_F(ServerTest, GetMethodLocalAddr) {
  4707. auto res = cli_.Get("/local_addr");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4711. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4712. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4713. }
  4714. TEST_F(ServerTest, HTTPResponseSplitting) {
  4715. auto res = cli_.Get("/http_response_splitting");
  4716. ASSERT_TRUE(res);
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. }
  4719. TEST_F(ServerTest, SlowRequest) {
  4720. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4721. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4722. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4723. }
  4724. #if 0
  4725. TEST_F(ServerTest, SlowPost) {
  4726. char buffer[64 * 1024];
  4727. memset(buffer, 0x42, sizeof(buffer));
  4728. auto res = cli_.Post(
  4729. "/slowpost", 64 * 1024 * 1024,
  4730. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4731. auto ret = sink.write(buffer, sizeof(buffer));
  4732. EXPECT_TRUE(ret);
  4733. return true;
  4734. },
  4735. "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. }
  4739. TEST_F(ServerTest, SlowPostFail) {
  4740. char buffer[64 * 1024];
  4741. memset(buffer, 0x42, sizeof(buffer));
  4742. cli_.set_write_timeout(std::chrono::seconds(0));
  4743. auto res = cli_.Post(
  4744. "/slowpost", 64 * 1024 * 1024,
  4745. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4746. sink.write(buffer, sizeof(buffer));
  4747. return true;
  4748. },
  4749. "text/plain");
  4750. ASSERT_TRUE(!res);
  4751. EXPECT_EQ(Error::Write, res.error());
  4752. }
  4753. #endif
  4754. TEST_F(ServerTest, Put) {
  4755. auto res = cli_.Put("/put", "PUT", "text/plain");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("PUT", res->body);
  4759. }
  4760. TEST_F(ServerTest, PutWithContentProvider) {
  4761. auto res = cli_.Put(
  4762. "/put", 3,
  4763. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4764. sink.os << "PUT";
  4765. return true;
  4766. },
  4767. "text/plain");
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ("PUT", res->body);
  4771. }
  4772. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4773. auto res = cli_.Post(
  4774. "/post", 42,
  4775. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4776. return false;
  4777. },
  4778. "text/plain");
  4779. ASSERT_TRUE(!res);
  4780. EXPECT_EQ(Error::Canceled, res.error());
  4781. }
  4782. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4783. auto res = cli_.Put(
  4784. "/put",
  4785. [](size_t /*offset*/, DataSink &sink) {
  4786. sink.os << "PUT";
  4787. sink.done();
  4788. return true;
  4789. },
  4790. "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PUT", res->body);
  4794. }
  4795. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4796. auto res = cli_.Post(
  4797. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4798. "text/plain");
  4799. ASSERT_TRUE(!res);
  4800. EXPECT_EQ(Error::Canceled, res.error());
  4801. }
  4802. TEST_F(ServerTest, PostLoopBack) {
  4803. std::string body;
  4804. auto res = cli_.Post(
  4805. "/post-loopback", 9,
  4806. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4807. EXPECT_EQ(9u, length);
  4808. sink.write("123", 3);
  4809. sink.write("456", 3);
  4810. sink.write("789", 3);
  4811. return true;
  4812. },
  4813. "text/plain",
  4814. [&body](const char *data, size_t data_length) {
  4815. body.append(data, data_length);
  4816. return true;
  4817. });
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("123456789", body);
  4821. }
  4822. TEST_F(ServerTest, PutLoopBack) {
  4823. std::string body;
  4824. auto res = cli_.Put(
  4825. "/put-loopback", 9,
  4826. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4827. EXPECT_EQ(9u, length);
  4828. sink.write("123", 3);
  4829. sink.write("456", 3);
  4830. sink.write("789", 3);
  4831. return true;
  4832. },
  4833. "text/plain",
  4834. [&body](const char *data, size_t data_length) {
  4835. body.append(data, data_length);
  4836. return true;
  4837. });
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("123456789", body);
  4841. }
  4842. TEST_F(ServerTest, PatchLoopBack) {
  4843. std::string body;
  4844. auto res = cli_.Patch(
  4845. "/patch-loopback", 9,
  4846. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4847. EXPECT_EQ(9u, length);
  4848. sink.write("123", 3);
  4849. sink.write("456", 3);
  4850. sink.write("789", 3);
  4851. return true;
  4852. },
  4853. "text/plain",
  4854. [&body](const char *data, size_t data_length) {
  4855. body.append(data, data_length);
  4856. return true;
  4857. });
  4858. ASSERT_TRUE(res);
  4859. EXPECT_EQ(StatusCode::OK_200, res->status);
  4860. EXPECT_EQ("123456789", body);
  4861. }
  4862. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4863. std::string body;
  4864. auto res = cli_.Post(
  4865. "/post-loopback",
  4866. [](size_t /*offset*/, DataSink &sink) {
  4867. sink.write("123", 3);
  4868. sink.write("456", 3);
  4869. sink.write("789", 3);
  4870. sink.done();
  4871. return true;
  4872. },
  4873. "text/plain",
  4874. [&body](const char *data, size_t data_length) {
  4875. body.append(data, data_length);
  4876. return true;
  4877. });
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. EXPECT_EQ("123456789", body);
  4881. }
  4882. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4883. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4884. cli_.set_compress(true);
  4885. auto res = cli_.Put(
  4886. "/put", 3,
  4887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4888. sink.os << "PUT";
  4889. return true;
  4890. },
  4891. "text/plain");
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. EXPECT_EQ("PUT", res->body);
  4895. }
  4896. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4897. cli_.set_compress(true);
  4898. auto res = cli_.Post(
  4899. "/post", 42,
  4900. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4901. return false;
  4902. },
  4903. "text/plain");
  4904. ASSERT_TRUE(!res);
  4905. EXPECT_EQ(Error::Canceled, res.error());
  4906. }
  4907. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4908. cli_.set_compress(true);
  4909. auto res = cli_.Put(
  4910. "/put",
  4911. [](size_t /*offset*/, DataSink &sink) {
  4912. sink.os << "PUT";
  4913. sink.done();
  4914. return true;
  4915. },
  4916. "text/plain");
  4917. ASSERT_TRUE(res);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("PUT", res->body);
  4920. }
  4921. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4922. cli_.set_compress(true);
  4923. auto res = cli_.Post(
  4924. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4925. "text/plain");
  4926. ASSERT_TRUE(!res);
  4927. EXPECT_EQ(Error::Canceled, res.error());
  4928. }
  4929. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4930. cli_.set_compress(true);
  4931. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4932. ASSERT_TRUE(res);
  4933. EXPECT_EQ(StatusCode::OK_200, res->status);
  4934. EXPECT_EQ(LARGE_DATA, res->body);
  4935. }
  4936. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4937. #ifdef CPPHTTPLIB_SSL_ENABLED
  4938. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4939. Client cli(s.c_str());
  4940. cli.enable_server_certificate_verification(false);
  4941. #else
  4942. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4943. Client cli(s.c_str());
  4944. #endif
  4945. cli.set_compress(true);
  4946. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4947. ASSERT_TRUE(res);
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. EXPECT_EQ(LARGE_DATA, res->body);
  4950. // The compressed size should be less than a 10th of the original. May vary
  4951. // depending on the zlib library.
  4952. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4953. static_cast<uint64_t>(10 * 1024 * 1024));
  4954. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4955. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4956. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4957. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4958. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4959. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4960. #endif
  4961. }
  4962. TEST_F(ServerTest, PutContentWithDeflate) {
  4963. cli_.set_compress(false);
  4964. Headers headers;
  4965. headers.emplace("Content-Encoding", "deflate");
  4966. // PUT in deflate format:
  4967. auto res = cli_.Put("/put", headers,
  4968. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4969. ASSERT_TRUE(res);
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("PUT", res->body);
  4972. }
  4973. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4974. Headers headers;
  4975. headers.emplace("Accept-Encoding", "gzip, deflate");
  4976. auto res = cli_.Get("/streamed-chunked", headers);
  4977. ASSERT_TRUE(res);
  4978. EXPECT_EQ(StatusCode::OK_200, res->status);
  4979. EXPECT_EQ(std::string("123456789"), res->body);
  4980. }
  4981. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4982. Headers headers;
  4983. headers.emplace("Accept-Encoding", "gzip, deflate");
  4984. auto res = cli_.Get("/streamed-chunked2", headers);
  4985. ASSERT_TRUE(res);
  4986. EXPECT_EQ(StatusCode::OK_200, res->status);
  4987. EXPECT_EQ(std::string("123456789"), res->body);
  4988. }
  4989. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4990. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4991. ASSERT_TRUE(res);
  4992. EXPECT_EQ(StatusCode::OK_200, res->status);
  4993. }
  4994. TEST(GzipDecompressor, ChunkedDecompression) {
  4995. std::string data;
  4996. for (size_t i = 0; i < 32 * 1024; ++i) {
  4997. data.push_back(static_cast<char>('a' + i % 26));
  4998. }
  4999. std::string compressed_data;
  5000. {
  5001. httplib::detail::gzip_compressor compressor;
  5002. bool result = compressor.compress(
  5003. data.data(), data.size(),
  5004. /*last=*/true,
  5005. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5006. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5007. compressed_data_size);
  5008. return true;
  5009. });
  5010. ASSERT_TRUE(result);
  5011. }
  5012. std::string decompressed_data;
  5013. {
  5014. httplib::detail::gzip_decompressor decompressor;
  5015. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5016. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5017. size_t chunk_size = 130;
  5018. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5019. chunk_begin += chunk_size) {
  5020. size_t current_chunk_size =
  5021. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5022. bool result = decompressor.decompress(
  5023. compressed_data.data() + chunk_begin, current_chunk_size,
  5024. [&](const char *decompressed_data_chunk,
  5025. size_t decompressed_data_chunk_size) {
  5026. decompressed_data.insert(decompressed_data.size(),
  5027. decompressed_data_chunk,
  5028. decompressed_data_chunk_size);
  5029. return true;
  5030. });
  5031. ASSERT_TRUE(result);
  5032. }
  5033. }
  5034. ASSERT_EQ(data, decompressed_data);
  5035. }
  5036. TEST(GzipDecompressor, DeflateDecompression) {
  5037. std::string original_text = "Raw deflate without gzip";
  5038. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5039. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5040. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5041. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5042. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5043. std::string decompressed_data;
  5044. {
  5045. httplib::detail::gzip_decompressor decompressor;
  5046. bool result = decompressor.decompress(
  5047. compressed_data.data(), compressed_data.size(),
  5048. [&](const char *decompressed_data_chunk,
  5049. size_t decompressed_data_chunk_size) {
  5050. decompressed_data.insert(decompressed_data.size(),
  5051. decompressed_data_chunk,
  5052. decompressed_data_chunk_size);
  5053. return true;
  5054. });
  5055. ASSERT_TRUE(result);
  5056. }
  5057. ASSERT_EQ(original_text, decompressed_data);
  5058. }
  5059. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5060. std::string original_text = "Raw deflate without gzip";
  5061. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5062. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5063. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5064. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5065. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5066. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5067. std::string decompressed_data;
  5068. {
  5069. httplib::detail::gzip_decompressor decompressor;
  5070. bool result = decompressor.decompress(
  5071. compressed_data.data(), compressed_data.size(),
  5072. [&](const char *decompressed_data_chunk,
  5073. size_t decompressed_data_chunk_size) {
  5074. decompressed_data.insert(decompressed_data.size(),
  5075. decompressed_data_chunk,
  5076. decompressed_data_chunk_size);
  5077. return true;
  5078. });
  5079. ASSERT_TRUE(result);
  5080. }
  5081. ASSERT_EQ(original_text, decompressed_data);
  5082. }
  5083. #endif
  5084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5085. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "br");
  5088. auto res = cli_.Get("/streamed-chunked", headers);
  5089. ASSERT_TRUE(res);
  5090. EXPECT_EQ(StatusCode::OK_200, res->status);
  5091. EXPECT_EQ(std::string("123456789"), res->body);
  5092. }
  5093. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5094. Headers headers;
  5095. headers.emplace("Accept-Encoding", "br");
  5096. auto res = cli_.Get("/streamed-chunked2", headers);
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ(std::string("123456789"), res->body);
  5100. }
  5101. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5102. cli_.set_compress(true);
  5103. auto res = cli_.Put(
  5104. "/put", 3,
  5105. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5106. sink.os << "PUT";
  5107. return true;
  5108. },
  5109. "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("PUT", res->body);
  5113. }
  5114. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5115. cli_.set_compress(true);
  5116. auto res = cli_.Put(
  5117. "/put",
  5118. [](size_t /*offset*/, DataSink &sink) {
  5119. sink.os << "PUT";
  5120. sink.done();
  5121. return true;
  5122. },
  5123. "text/plain");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("PUT", res->body);
  5127. }
  5128. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5131. ASSERT_TRUE(res);
  5132. EXPECT_EQ(StatusCode::OK_200, res->status);
  5133. EXPECT_EQ(LARGE_DATA, res->body);
  5134. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5135. }
  5136. #endif
  5137. TEST_F(ServerTest, Patch) {
  5138. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5139. ASSERT_TRUE(res);
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("PATCH", res->body);
  5142. }
  5143. TEST_F(ServerTest, Delete) {
  5144. auto res = cli_.Delete("/delete");
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(StatusCode::OK_200, res->status);
  5147. EXPECT_EQ("DELETE", res->body);
  5148. }
  5149. TEST_F(ServerTest, DeleteContentReceiver) {
  5150. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("content", res->body);
  5154. }
  5155. TEST_F(ServerTest, Options) {
  5156. auto res = cli_.Options("*");
  5157. ASSERT_TRUE(res);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5160. EXPECT_TRUE(res->body.empty());
  5161. }
  5162. TEST_F(ServerTest, URL) {
  5163. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. }
  5167. TEST_F(ServerTest, ArrayParam) {
  5168. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. }
  5172. TEST_F(ServerTest, ArrayParamValues) {
  5173. auto res =
  5174. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5175. ASSERT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, NoMultipleHeaders) {
  5179. Headers headers = {{"Content-Length", "5"}};
  5180. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5181. "text/plain");
  5182. ASSERT_TRUE(res);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. }
  5185. TEST_F(ServerTest, PostContentReceiver) {
  5186. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5187. ASSERT_TRUE(res);
  5188. ASSERT_EQ(StatusCode::OK_200, res->status);
  5189. ASSERT_EQ("content", res->body);
  5190. }
  5191. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5192. UploadFormDataItems items = {
  5193. {"text1", "text default", "", ""},
  5194. {"text2", "aωb", "", ""},
  5195. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5196. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5197. {"file3", "", "", "application/octet-stream"},
  5198. };
  5199. auto res = cli_.Post("/content_receiver", items);
  5200. ASSERT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::OK_200, res->status);
  5202. }
  5203. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5204. UploadFormDataItems items = {
  5205. {"text1", "text default", "", ""},
  5206. {"text2", "aωb", "", ""},
  5207. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5208. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5209. {"file3", "", "", "application/octet-stream"},
  5210. };
  5211. auto boundary = std::string("+++++");
  5212. std::string body;
  5213. for (const auto &item : items) {
  5214. body += "--" + boundary + "\r\n";
  5215. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5216. if (!item.filename.empty()) {
  5217. body += "; filename=\"" + item.filename + "\"";
  5218. }
  5219. body += "\r\n";
  5220. if (!item.content_type.empty()) {
  5221. body += "Content-Type: " + item.content_type + "\r\n";
  5222. }
  5223. body += "\r\n";
  5224. body += item.content + "\r\n";
  5225. }
  5226. body += "--" + boundary + "--\r\n";
  5227. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5228. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5229. ASSERT_TRUE(res);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. }
  5232. TEST_F(ServerTest, PostContentReceiverGzip) {
  5233. cli_.set_compress(true);
  5234. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5235. ASSERT_TRUE(res);
  5236. ASSERT_EQ(StatusCode::OK_200, res->status);
  5237. ASSERT_EQ("content", res->body);
  5238. }
  5239. TEST_F(ServerTest, PutContentReceiver) {
  5240. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5241. ASSERT_TRUE(res);
  5242. ASSERT_EQ(StatusCode::OK_200, res->status);
  5243. ASSERT_EQ("content", res->body);
  5244. }
  5245. TEST_F(ServerTest, PatchContentReceiver) {
  5246. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5247. ASSERT_TRUE(res);
  5248. ASSERT_EQ(StatusCode::OK_200, res->status);
  5249. ASSERT_EQ("content", res->body);
  5250. }
  5251. template <typename ClientType>
  5252. void TestWithHeadersAndContentReceiver(
  5253. ClientType &cli,
  5254. std::function<Result(ClientType &, const std::string &, const Headers &,
  5255. const std::string &, const std::string &,
  5256. ContentReceiver, DownloadProgress)>
  5257. request_func) {
  5258. Headers headers;
  5259. headers.emplace("X-Custom-Header", "test-value");
  5260. std::string received_body;
  5261. auto res = request_func(
  5262. cli, "/content_receiver", headers, "content", "application/json",
  5263. [&](const char *data, size_t data_length) {
  5264. received_body.append(data, data_length);
  5265. return true;
  5266. },
  5267. nullptr);
  5268. ASSERT_TRUE(res);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("content", received_body);
  5271. }
  5272. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5273. #ifdef CPPHTTPLIB_SSL_ENABLED
  5274. using ClientT = SSLClient;
  5275. #else
  5276. using ClientT = Client;
  5277. #endif
  5278. TestWithHeadersAndContentReceiver<ClientT>(
  5279. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5280. const std::string &body, const std::string &content_type,
  5281. ContentReceiver receiver, DownloadProgress progress) {
  5282. return cli.Post(path, headers, body, content_type, receiver, progress);
  5283. });
  5284. }
  5285. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5286. #ifdef CPPHTTPLIB_SSL_ENABLED
  5287. using ClientT = SSLClient;
  5288. #else
  5289. using ClientT = Client;
  5290. #endif
  5291. TestWithHeadersAndContentReceiver<ClientT>(
  5292. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5293. const std::string &body, const std::string &content_type,
  5294. ContentReceiver receiver, DownloadProgress progress) {
  5295. return cli.Put(path, headers, body, content_type, receiver, progress);
  5296. });
  5297. }
  5298. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5299. #ifdef CPPHTTPLIB_SSL_ENABLED
  5300. using ClientT = SSLClient;
  5301. #else
  5302. using ClientT = Client;
  5303. #endif
  5304. TestWithHeadersAndContentReceiver<ClientT>(
  5305. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5306. const std::string &body, const std::string &content_type,
  5307. ContentReceiver receiver, DownloadProgress progress) {
  5308. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5309. });
  5310. }
  5311. template <typename ClientType>
  5312. void TestWithHeadersAndContentReceiverWithProgress(
  5313. ClientType &cli,
  5314. std::function<Result(ClientType &, const std::string &, const Headers &,
  5315. const std::string &, const std::string &,
  5316. ContentReceiver, DownloadProgress)>
  5317. request_func) {
  5318. Headers headers;
  5319. headers.emplace("X-Test-Header", "progress-test");
  5320. std::string received_body;
  5321. auto progress_called = false;
  5322. auto res = request_func(
  5323. cli, "/content_receiver", headers, "content", "text/plain",
  5324. [&](const char *data, size_t data_length) {
  5325. received_body.append(data, data_length);
  5326. return true;
  5327. },
  5328. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5329. progress_called = true;
  5330. return true;
  5331. });
  5332. ASSERT_TRUE(res);
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. EXPECT_EQ("content", received_body);
  5335. EXPECT_TRUE(progress_called);
  5336. }
  5337. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5338. #ifdef CPPHTTPLIB_SSL_ENABLED
  5339. using ClientT = SSLClient;
  5340. #else
  5341. using ClientT = Client;
  5342. #endif
  5343. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5344. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5345. const std::string &body, const std::string &content_type,
  5346. ContentReceiver receiver, DownloadProgress progress) {
  5347. return cli.Post(path, headers, body, content_type, receiver, progress);
  5348. });
  5349. }
  5350. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5351. #ifdef CPPHTTPLIB_SSL_ENABLED
  5352. using ClientT = SSLClient;
  5353. #else
  5354. using ClientT = Client;
  5355. #endif
  5356. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5357. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5358. const std::string &body, const std::string &content_type,
  5359. ContentReceiver receiver, DownloadProgress progress) {
  5360. return cli.Put(path, headers, body, content_type, receiver, progress);
  5361. });
  5362. }
  5363. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5364. #ifdef CPPHTTPLIB_SSL_ENABLED
  5365. using ClientT = SSLClient;
  5366. #else
  5367. using ClientT = Client;
  5368. #endif
  5369. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5370. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5371. const std::string &body, const std::string &content_type,
  5372. ContentReceiver receiver, DownloadProgress progress) {
  5373. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5374. });
  5375. }
  5376. template <typename ClientType>
  5377. void TestWithHeadersAndContentReceiverError(
  5378. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5379. const Headers &, const std::string &,
  5380. const std::string &, ContentReceiver)>
  5381. request_func) {
  5382. Headers headers;
  5383. headers.emplace("X-Error-Test", "true");
  5384. std::string received_body;
  5385. auto receiver_failed = false;
  5386. auto res =
  5387. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5388. [&](const char *data, size_t data_length) {
  5389. received_body.append(data, data_length);
  5390. receiver_failed = true;
  5391. return false;
  5392. });
  5393. ASSERT_FALSE(res);
  5394. EXPECT_TRUE(receiver_failed);
  5395. }
  5396. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5397. #ifdef CPPHTTPLIB_SSL_ENABLED
  5398. using ClientT = SSLClient;
  5399. #else
  5400. using ClientT = Client;
  5401. #endif
  5402. TestWithHeadersAndContentReceiverError<ClientT>(
  5403. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5404. const std::string &body, const std::string &content_type,
  5405. ContentReceiver receiver) {
  5406. return cli.Post(path, headers, body, content_type, receiver);
  5407. });
  5408. }
  5409. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5410. #ifdef CPPHTTPLIB_SSL_ENABLED
  5411. using ClientT = SSLClient;
  5412. #else
  5413. using ClientT = Client;
  5414. #endif
  5415. TestWithHeadersAndContentReceiverError<ClientT>(
  5416. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5417. const std::string &body, const std::string &content_type,
  5418. ContentReceiver receiver) {
  5419. return cli.Put(path, headers, body, content_type, receiver);
  5420. });
  5421. }
  5422. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5423. #ifdef CPPHTTPLIB_SSL_ENABLED
  5424. using ClientT = SSLClient;
  5425. #else
  5426. using ClientT = Client;
  5427. #endif
  5428. TestWithHeadersAndContentReceiverError<ClientT>(
  5429. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5430. const std::string &body, const std::string &content_type,
  5431. ContentReceiver receiver) {
  5432. return cli.Patch(path, headers, body, content_type, receiver);
  5433. });
  5434. }
  5435. TEST_F(ServerTest, PostQueryStringAndBody) {
  5436. auto res =
  5437. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5438. ASSERT_TRUE(res);
  5439. ASSERT_EQ(StatusCode::OK_200, res->status);
  5440. }
  5441. TEST_F(ServerTest, HTTP2Magic) {
  5442. Request req;
  5443. req.method = "PRI";
  5444. req.path = "*";
  5445. req.body = "SM";
  5446. auto res = std::make_shared<Response>();
  5447. auto error = Error::Success;
  5448. auto ret = cli_.send(req, *res, error);
  5449. ASSERT_TRUE(ret);
  5450. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5451. }
  5452. TEST_F(ServerTest, KeepAlive) {
  5453. auto res = cli_.Get("/hi");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(StatusCode::OK_200, res->status);
  5456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("Hello World!", res->body);
  5458. res = cli_.Get("/hi");
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("Hello World!", res->body);
  5463. res = cli_.Get("/hi");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5467. EXPECT_EQ("Hello World!", res->body);
  5468. res = cli_.Get("/not-exist");
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5471. res = cli_.Post("/empty", "", "text/plain");
  5472. ASSERT_TRUE(res);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5475. EXPECT_EQ("empty", res->body);
  5476. EXPECT_EQ("close", res->get_header_value("Connection"));
  5477. res = cli_.Post(
  5478. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5479. "text/plain");
  5480. ASSERT_TRUE(res);
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ("empty", res->body);
  5484. cli_.set_keep_alive(false);
  5485. res = cli_.Get("/last-request");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("close", res->get_header_value("Connection"));
  5489. }
  5490. TEST_F(ServerTest, TooManyRedirect) {
  5491. cli_.set_follow_location(true);
  5492. auto res = cli_.Get("/redirect/0");
  5493. ASSERT_TRUE(!res);
  5494. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5495. }
  5496. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5497. Request req;
  5498. req.method = "FOOBAR";
  5499. req.path = "/hi";
  5500. cli_.set_keep_alive(true);
  5501. auto res = cli_.send(req);
  5502. ASSERT_TRUE(res);
  5503. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5504. EXPECT_EQ("close", res->get_header_value("Connection"));
  5505. EXPECT_FALSE(cli_.is_socket_open());
  5506. }
  5507. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5508. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5509. TEST_F(ServerTest, Gzip) {
  5510. Headers headers;
  5511. headers.emplace("Accept-Encoding", "gzip, deflate");
  5512. auto res = cli_.Get("/compress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5515. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5516. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5517. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5518. "7890123456789012345678901234567890",
  5519. res->body);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. }
  5522. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5523. Headers headers;
  5524. headers.emplace("Accept-Encoding", "gzip, deflate");
  5525. auto res = cli_.Get("/compress-with-charset", headers);
  5526. ASSERT_TRUE(res);
  5527. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5528. EXPECT_EQ("application/json; charset=utf-8",
  5529. res->get_header_value("Content-Type"));
  5530. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5531. "7890123456789012345678901234567890",
  5532. res->body);
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. }
  5535. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5536. Headers headers;
  5537. headers.emplace("Accept-Encoding", "");
  5538. auto res = cli_.Get("/compress", headers);
  5539. ASSERT_TRUE(res);
  5540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5544. "7890123456789012345678901234567890",
  5545. res->body);
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. }
  5548. TEST_F(ServerTest, GzipWithContentReceiver) {
  5549. Headers headers;
  5550. headers.emplace("Accept-Encoding", "gzip, deflate");
  5551. std::string body;
  5552. auto res = cli_.Get("/compress", headers,
  5553. [&](const char *data, uint64_t data_length) {
  5554. EXPECT_EQ(100U, data_length);
  5555. body.append(data, data_length);
  5556. return true;
  5557. });
  5558. ASSERT_TRUE(res);
  5559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5561. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5562. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5563. "7890123456789012345678901234567890",
  5564. body);
  5565. EXPECT_EQ(StatusCode::OK_200, res->status);
  5566. }
  5567. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5568. Headers headers;
  5569. headers.emplace("Accept-Encoding", "gzip, deflate");
  5570. cli_.set_decompress(false);
  5571. auto res = cli_.Get("/compress", headers);
  5572. ASSERT_TRUE(res);
  5573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5576. EXPECT_EQ(33U, res->body.size());
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. }
  5579. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5580. Headers headers;
  5581. headers.emplace("Accept-Encoding", "");
  5582. std::string body;
  5583. auto res = cli_.Get("/compress", headers,
  5584. [&](const char *data, uint64_t data_length) {
  5585. EXPECT_EQ(100U, data_length);
  5586. body.append(data, data_length);
  5587. return true;
  5588. });
  5589. ASSERT_TRUE(res);
  5590. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5592. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5593. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5594. "7890123456789012345678901234567890",
  5595. body);
  5596. EXPECT_EQ(StatusCode::OK_200, res->status);
  5597. }
  5598. TEST_F(ServerTest, NoGzip) {
  5599. Headers headers;
  5600. headers.emplace("Accept-Encoding", "gzip, deflate");
  5601. auto res = cli_.Get("/nocompress", headers);
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5604. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5605. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5607. "7890123456789012345678901234567890",
  5608. res->body);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. }
  5611. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5612. Headers headers;
  5613. headers.emplace("Accept-Encoding", "gzip, deflate");
  5614. std::string body;
  5615. auto res = cli_.Get("/nocompress", headers,
  5616. [&](const char *data, uint64_t data_length) {
  5617. EXPECT_EQ(100U, data_length);
  5618. body.append(data, data_length);
  5619. return true;
  5620. });
  5621. ASSERT_TRUE(res);
  5622. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5623. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5626. "7890123456789012345678901234567890",
  5627. body);
  5628. EXPECT_EQ(StatusCode::OK_200, res->status);
  5629. }
  5630. TEST_F(ServerTest, MultipartFormDataGzip) {
  5631. UploadFormDataItems items = {
  5632. {"key1", "test", "", ""},
  5633. {"key2", "--abcdefg123", "", ""},
  5634. };
  5635. cli_.set_compress(true);
  5636. auto res = cli_.Post("/compress-multipart", items);
  5637. ASSERT_TRUE(res);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. }
  5640. #endif
  5641. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5642. TEST_F(ServerTest, Brotli) {
  5643. Headers headers;
  5644. headers.emplace("Accept-Encoding", "br");
  5645. auto res = cli_.Get("/compress", headers);
  5646. ASSERT_TRUE(res);
  5647. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5649. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5650. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5651. "7890123456789012345678901234567890",
  5652. res->body);
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. }
  5655. #endif
  5656. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5657. TEST_F(ServerTest, Zstd) {
  5658. Headers headers;
  5659. headers.emplace("Accept-Encoding", "zstd");
  5660. auto res = cli_.Get("/compress", headers);
  5661. ASSERT_TRUE(res);
  5662. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5664. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5666. "7890123456789012345678901234567890",
  5667. res->body);
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. }
  5670. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5671. Headers headers;
  5672. headers.emplace("Accept-Encoding", "");
  5673. auto res = cli_.Get("/compress", headers);
  5674. ASSERT_TRUE(res);
  5675. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5677. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5678. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5679. "7890123456789012345678901234567890",
  5680. res->body);
  5681. EXPECT_EQ(StatusCode::OK_200, res->status);
  5682. }
  5683. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5684. Headers headers;
  5685. headers.emplace("Accept-Encoding", "zstd");
  5686. std::string body;
  5687. auto res = cli_.Get("/compress", headers,
  5688. [&](const char *data, uint64_t data_length) {
  5689. EXPECT_EQ(100U, data_length);
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. ASSERT_TRUE(res);
  5694. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5696. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5697. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5698. "7890123456789012345678901234567890",
  5699. body);
  5700. EXPECT_EQ(StatusCode::OK_200, res->status);
  5701. }
  5702. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5703. Headers headers;
  5704. headers.emplace("Accept-Encoding", "zstd");
  5705. cli_.set_decompress(false);
  5706. auto res = cli_.Get("/compress", headers);
  5707. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5708. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5709. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5710. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5714. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. ASSERT_EQ(26U, res->body.size());
  5717. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5718. 0);
  5719. }
  5720. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5721. Headers headers;
  5722. headers.emplace("Accept-Encoding", "");
  5723. std::string body;
  5724. auto res = cli_.Get("/compress", headers,
  5725. [&](const char *data, uint64_t data_length) {
  5726. EXPECT_EQ(100U, data_length);
  5727. body.append(data, data_length);
  5728. return true;
  5729. });
  5730. ASSERT_TRUE(res);
  5731. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5733. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5734. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5735. "7890123456789012345678901234567890",
  5736. body);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. }
  5739. TEST_F(ServerTest, NoZstd) {
  5740. Headers headers;
  5741. headers.emplace("Accept-Encoding", "zstd");
  5742. auto res = cli_.Get("/nocompress", headers);
  5743. ASSERT_TRUE(res);
  5744. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5745. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5746. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5747. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5748. "7890123456789012345678901234567890",
  5749. res->body);
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. }
  5752. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5753. Headers headers;
  5754. headers.emplace("Accept-Encoding", "zstd");
  5755. std::string body;
  5756. auto res = cli_.Get("/nocompress", headers,
  5757. [&](const char *data, uint64_t data_length) {
  5758. EXPECT_EQ(100U, data_length);
  5759. body.append(data, data_length);
  5760. return true;
  5761. });
  5762. ASSERT_TRUE(res);
  5763. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5764. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5767. "7890123456789012345678901234567890",
  5768. body);
  5769. EXPECT_EQ(StatusCode::OK_200, res->status);
  5770. }
  5771. // TODO: How to enable zstd ??
  5772. TEST_F(ServerTest, MultipartFormDataZstd) {
  5773. UploadFormDataItems items = {
  5774. {"key1", "test", "", ""},
  5775. {"key2", "--abcdefg123", "", ""},
  5776. };
  5777. Headers headers;
  5778. headers.emplace("Accept-Encoding", "zstd");
  5779. cli_.set_compress(true);
  5780. auto res = cli_.Post("/compress-multipart", headers, items);
  5781. ASSERT_TRUE(res);
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5785. Headers headers;
  5786. headers.emplace("Accept-Encoding", "zstd");
  5787. cli_.set_compress(true);
  5788. auto res = cli_.Put(
  5789. "/put", headers, 3,
  5790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5791. sink.os << "PUT";
  5792. return true;
  5793. },
  5794. "text/plain");
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("PUT", res->body);
  5798. }
  5799. // Pre-compression logging tests
  5800. TEST_F(ServerTest, PreCompressionLogging) {
  5801. // Test data for compression (matches the actual /compress endpoint content)
  5802. const std::string test_content =
  5803. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5804. "3456789012345678901234567890";
  5805. // Variables to capture logging data
  5806. std::string pre_compression_body;
  5807. std::string pre_compression_content_type;
  5808. std::string pre_compression_content_encoding;
  5809. std::string post_compression_body;
  5810. std::string post_compression_content_type;
  5811. std::string post_compression_content_encoding;
  5812. // Set up pre-compression logger
  5813. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5814. const Response &res) {
  5815. pre_compression_body = res.body;
  5816. pre_compression_content_type = res.get_header_value("Content-Type");
  5817. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5818. });
  5819. // Set up post-compression logger
  5820. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5821. post_compression_body = res.body;
  5822. post_compression_content_type = res.get_header_value("Content-Type");
  5823. post_compression_content_encoding =
  5824. res.get_header_value("Content-Encoding");
  5825. });
  5826. // Test with gzip compression
  5827. Headers headers;
  5828. headers.emplace("Accept-Encoding", "gzip");
  5829. auto res = cli_.Get("/compress", headers);
  5830. // Verify response was compressed
  5831. ASSERT_TRUE(res);
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5834. // Verify pre-compression logger captured uncompressed content
  5835. EXPECT_EQ(test_content, pre_compression_body);
  5836. EXPECT_EQ("text/plain", pre_compression_content_type);
  5837. EXPECT_TRUE(pre_compression_content_encoding
  5838. .empty()); // No encoding header before compression
  5839. // Verify post-compression logger captured compressed content
  5840. EXPECT_NE(test_content,
  5841. post_compression_body); // Should be different after compression
  5842. EXPECT_EQ("text/plain", post_compression_content_type);
  5843. EXPECT_EQ("gzip", post_compression_content_encoding);
  5844. // Verify compressed content is smaller
  5845. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5846. }
  5847. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5848. const std::string test_content =
  5849. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5850. "3456789012345678901234567890";
  5851. std::string pre_compression_body;
  5852. std::string post_compression_body;
  5853. svr_.set_pre_compression_logger(
  5854. [&](const Request & /*req*/, const Response &res) {
  5855. pre_compression_body = res.body;
  5856. });
  5857. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5858. post_compression_body = res.body;
  5859. });
  5860. Headers headers;
  5861. headers.emplace("Accept-Encoding", "br");
  5862. auto res = cli_.Get("/compress", headers);
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5866. // Verify pre-compression content is uncompressed
  5867. EXPECT_EQ(test_content, pre_compression_body);
  5868. // Verify post-compression content is compressed
  5869. EXPECT_NE(test_content, post_compression_body);
  5870. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5871. }
  5872. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5873. const std::string test_content =
  5874. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5875. "3456789012345678901234567890";
  5876. std::string pre_compression_body;
  5877. std::string post_compression_body;
  5878. svr_.set_pre_compression_logger(
  5879. [&](const Request & /*req*/, const Response &res) {
  5880. pre_compression_body = res.body;
  5881. });
  5882. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5883. post_compression_body = res.body;
  5884. });
  5885. // Request without compression (use /nocompress endpoint)
  5886. Headers headers;
  5887. auto res = cli_.Get("/nocompress", headers);
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5891. // Pre-compression logger should not be called when no compression is applied
  5892. EXPECT_TRUE(
  5893. pre_compression_body.empty()); // Pre-compression logger not called
  5894. EXPECT_EQ(
  5895. test_content,
  5896. post_compression_body); // Post-compression logger captures final content
  5897. }
  5898. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5899. const std::string test_content =
  5900. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5901. "3456789012345678901234567890";
  5902. std::string pre_compression_body;
  5903. bool pre_logger_called = false;
  5904. // Set only pre-compression logger
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. pre_logger_called = true;
  5909. });
  5910. Headers headers;
  5911. headers.emplace("Accept-Encoding", "gzip");
  5912. auto res = cli_.Get("/compress", headers);
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5916. // Verify pre-compression logger was called
  5917. EXPECT_TRUE(pre_logger_called);
  5918. EXPECT_EQ(test_content, pre_compression_body);
  5919. }
  5920. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5921. {
  5922. // Test with Expect: 100-continue header - success case
  5923. // Server returns 100 Continue, client sends body, server returns 200 OK
  5924. Request req;
  5925. req.method = "POST";
  5926. req.path = "/post-large";
  5927. req.set_header("Expect", "100-continue");
  5928. req.body = LARGE_DATA;
  5929. Response res;
  5930. auto error = Error::Success;
  5931. cli_.set_keep_alive(true);
  5932. auto ret = cli_.send(req, res, error);
  5933. EXPECT_TRUE(ret);
  5934. EXPECT_EQ(StatusCode::OK_200, res.status);
  5935. EXPECT_EQ(LARGE_DATA, res.body);
  5936. }
  5937. {
  5938. // Test with Expect: 100-continue header - error case
  5939. // Client should not send the body when server returns an error
  5940. Request req;
  5941. req.method = "POST";
  5942. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5943. req.set_header("Expect", "100-continue");
  5944. req.body = LARGE_DATA;
  5945. Response res;
  5946. auto error = Error::Success;
  5947. auto start = std::chrono::high_resolution_clock::now();
  5948. cli_.set_keep_alive(true);
  5949. auto ret = cli_.send(req, res, error);
  5950. auto end = std::chrono::high_resolution_clock::now();
  5951. auto elapsed =
  5952. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5953. .count();
  5954. // With Expect: 100-continue, request completes successfully but with error
  5955. EXPECT_TRUE(ret);
  5956. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5957. EXPECT_EQ("close", res.get_header_value("Connection"));
  5958. EXPECT_FALSE(cli_.is_socket_open());
  5959. EXPECT_LE(elapsed, 2000);
  5960. }
  5961. {
  5962. // Send an extra GET request to ensure error recovery without hanging
  5963. Request req;
  5964. req.method = "GET";
  5965. req.path = "/hi";
  5966. auto start = std::chrono::high_resolution_clock::now();
  5967. auto res = cli_.send(req);
  5968. auto end = std::chrono::high_resolution_clock::now();
  5969. auto elapsed =
  5970. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5971. .count();
  5972. ASSERT_TRUE(res);
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ("Hello World!", res->body);
  5975. EXPECT_LE(elapsed, 500);
  5976. }
  5977. }
  5978. TEST(ZstdDecompressor, ChunkedDecompression) {
  5979. std::string data;
  5980. for (size_t i = 0; i < 32 * 1024; ++i) {
  5981. data.push_back(static_cast<char>('a' + i % 26));
  5982. }
  5983. std::string compressed_data;
  5984. {
  5985. httplib::detail::zstd_compressor compressor;
  5986. bool result = compressor.compress(
  5987. data.data(), data.size(),
  5988. /*last=*/true,
  5989. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5990. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5991. compressed_data_size);
  5992. return true;
  5993. });
  5994. ASSERT_TRUE(result);
  5995. }
  5996. std::string decompressed_data;
  5997. {
  5998. httplib::detail::zstd_decompressor decompressor;
  5999. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6000. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6001. size_t chunk_size = 130;
  6002. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6003. chunk_begin += chunk_size) {
  6004. size_t current_chunk_size =
  6005. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6006. bool result = decompressor.decompress(
  6007. compressed_data.data() + chunk_begin, current_chunk_size,
  6008. [&](const char *decompressed_data_chunk,
  6009. size_t decompressed_data_chunk_size) {
  6010. decompressed_data.insert(decompressed_data.size(),
  6011. decompressed_data_chunk,
  6012. decompressed_data_chunk_size);
  6013. return true;
  6014. });
  6015. ASSERT_TRUE(result);
  6016. }
  6017. }
  6018. ASSERT_EQ(data, decompressed_data);
  6019. }
  6020. TEST(ZstdDecompressor, Decompress) {
  6021. std::string original_text = "Compressed with ZSTD";
  6022. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6023. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6024. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6025. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6026. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6027. std::string decompressed_data;
  6028. {
  6029. httplib::detail::zstd_decompressor decompressor;
  6030. bool result = decompressor.decompress(
  6031. compressed_data.data(), compressed_data.size(),
  6032. [&](const char *decompressed_data_chunk,
  6033. size_t decompressed_data_chunk_size) {
  6034. decompressed_data.insert(decompressed_data.size(),
  6035. decompressed_data_chunk,
  6036. decompressed_data_chunk_size);
  6037. return true;
  6038. });
  6039. ASSERT_TRUE(result);
  6040. }
  6041. ASSERT_EQ(original_text, decompressed_data);
  6042. }
  6043. #endif
  6044. // Sends a raw request to a server listening at HOST:PORT.
  6045. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6046. std::string *resp = nullptr) {
  6047. auto error = Error::Success;
  6048. auto client_sock = detail::create_client_socket(
  6049. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6050. /*connection_timeout_sec=*/5, 0,
  6051. /*read_timeout_sec=*/5, 0,
  6052. /*write_timeout_sec=*/5, 0, std::string(), error);
  6053. if (client_sock == INVALID_SOCKET) { return false; }
  6054. auto ret = detail::process_client_socket(
  6055. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6056. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6057. if (req.size() !=
  6058. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6059. return false;
  6060. }
  6061. char buf[512];
  6062. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6063. while (line_reader.getline()) {
  6064. if (resp) { *resp += line_reader.ptr(); }
  6065. }
  6066. return true;
  6067. });
  6068. detail::close_socket(client_sock);
  6069. return ret;
  6070. }
  6071. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6072. Server svr;
  6073. std::string header_value;
  6074. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6075. header_value = req.get_header_value("foo");
  6076. res.set_content("ok", "text/plain");
  6077. });
  6078. thread t = thread([&] { svr.listen(HOST, PORT); });
  6079. auto se = detail::scope_exit([&] {
  6080. svr.stop();
  6081. t.join();
  6082. ASSERT_FALSE(svr.is_running());
  6083. });
  6084. svr.wait_until_ready();
  6085. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6086. // like characters are not treated the same - use vertical tab and escape.
  6087. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6088. "foo: \t \v bar \x1B\t \r\n"
  6089. "Connection: close\r\n"
  6090. "\r\n";
  6091. std::string res;
  6092. ASSERT_TRUE(send_request(5, req, &res));
  6093. EXPECT_EQ(header_value, "");
  6094. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6095. }
  6096. // Sends a raw request and verifies that there isn't a crash or exception.
  6097. static void test_raw_request(const std::string &req,
  6098. std::string *out = nullptr) {
  6099. Server svr;
  6100. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6101. res.set_content("ok", "text/plain");
  6102. });
  6103. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6104. res.set_content("ok", "text/plain");
  6105. });
  6106. svr.Get("/header_field_value_check",
  6107. [&](const Request & /*req*/, Response &res) {
  6108. res.set_content("ok", "text/plain");
  6109. });
  6110. // Server read timeout must be longer than the client read timeout for the
  6111. // bug to reproduce, probably to force the server to process a request
  6112. // without a trailing blank line.
  6113. const time_t client_read_timeout_sec = 1;
  6114. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6115. bool listen_thread_ok = false;
  6116. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6117. auto se = detail::scope_exit([&] {
  6118. svr.stop();
  6119. t.join();
  6120. ASSERT_FALSE(svr.is_running());
  6121. EXPECT_TRUE(listen_thread_ok);
  6122. });
  6123. svr.wait_until_ready();
  6124. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6125. }
  6126. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6127. // A certain header line causes an exception if the header property is parsed
  6128. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6129. test_raw_request(
  6130. "GET /hi HTTP/1.1\r\n"
  6131. " : "
  6132. " "
  6133. " ");
  6134. }
  6135. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6136. // A certain header line causes an exception if the header property *name* is
  6137. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6138. // greedy matcher and requires backtracking when there are a lot of ":"
  6139. // characters.
  6140. // This occurs with libc++ but not libstdc++.
  6141. test_raw_request(
  6142. "GET /hi HTTP/1.1\r\n"
  6143. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6144. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6145. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6146. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6147. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6148. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6149. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6150. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6151. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6152. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6153. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6154. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6155. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6156. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6157. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6158. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6159. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6160. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6161. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6162. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6163. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6164. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6165. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6166. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6167. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6168. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6169. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6170. "&&&%%%");
  6171. }
  6172. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6173. // Make sure this doesn't crash the server.
  6174. // In a previous version of the header line regex, the "\r" rendered the line
  6175. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6176. // a new position where the leading white space ended and the field value
  6177. // began.
  6178. // The crash occurs with libc++ but not libstdc++.
  6179. test_raw_request("GET /hi HTTP/1.1\r\n"
  6180. "a:" +
  6181. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6182. "\r\n"
  6183. "\r\n");
  6184. }
  6185. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6186. std::string out;
  6187. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6188. "Content-Type: text/plain\r\n"
  6189. "Transfer-Encoding: chunked\r\n"
  6190. "\r\n"
  6191. "nothex\r\n",
  6192. &out);
  6193. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6194. }
  6195. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6196. std::string out;
  6197. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6198. "Content-Type: text/plain\r\n"
  6199. "Transfer-Encoding: chunked\r\n"
  6200. "\r\n"
  6201. "3\r\n"
  6202. "xyz\r\n"
  6203. "NaN\r\n",
  6204. &out);
  6205. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6206. }
  6207. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6208. std::string out;
  6209. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6210. "Content-Type: text/plain\r\n"
  6211. "Transfer-Encoding: chunked\r\n"
  6212. "\r\n"
  6213. // Length is too large for 64 bits.
  6214. "1ffffffffffffffff\r\n"
  6215. "xyz\r\n",
  6216. &out);
  6217. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6218. }
  6219. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6220. test_raw_request("GET /hi HTTP/1.1\r\n"
  6221. "Content-Type: text/plain\r\n\r");
  6222. }
  6223. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6224. std::string out;
  6225. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6226. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6227. }
  6228. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6229. Server svr;
  6230. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6231. EXPECT_TRUE(!req.remote_addr.empty());
  6232. });
  6233. thread t = thread([&] { svr.listen(HOST, PORT); });
  6234. auto se = detail::scope_exit([&] {
  6235. svr.stop();
  6236. t.join();
  6237. ASSERT_FALSE(svr.is_running());
  6238. });
  6239. svr.wait_until_ready();
  6240. // Send an invalid request line to trigger Bad Request
  6241. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6242. std::string out;
  6243. ASSERT_TRUE(send_request(5, bad_req, &out));
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6247. std::string out;
  6248. std::string request(
  6249. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6250. test_raw_request(request, &out);
  6251. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6252. }
  6253. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6254. std::string out;
  6255. std::string request(
  6256. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6257. test_raw_request(request, &out);
  6258. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6259. }
  6260. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6261. std::string out;
  6262. std::string request(
  6263. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6264. test_raw_request(request, &out);
  6265. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6266. }
  6267. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6268. std::string out;
  6269. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6270. "Test: \r\n\r\n",
  6271. &out);
  6272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6273. }
  6274. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6275. Server svr;
  6276. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6277. res.set_header("Cache-Control", "no-cache");
  6278. res.set_chunked_content_provider(
  6279. "text/event-stream", [](size_t offset, DataSink &sink) {
  6280. std::string s = "data:";
  6281. s += std::to_string(offset);
  6282. s += "\n\n";
  6283. auto ret = sink.write(s.data(), s.size());
  6284. EXPECT_TRUE(ret);
  6285. std::this_thread::sleep_for(std::chrono::seconds(1));
  6286. return true;
  6287. });
  6288. });
  6289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6290. svr.wait_until_ready();
  6291. Client client(HOST, PORT);
  6292. const Headers headers = {{"Accept", "text/event-stream"}};
  6293. auto get_thread = std::thread([&client, &headers]() {
  6294. auto res = client.Get(
  6295. "/events", headers,
  6296. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6297. });
  6298. auto se = detail::scope_exit([&] {
  6299. svr.stop();
  6300. get_thread.join();
  6301. listen_thread.join();
  6302. ASSERT_FALSE(svr.is_running());
  6303. });
  6304. // Give GET time to get a few messages.
  6305. std::this_thread::sleep_for(std::chrono::seconds(2));
  6306. }
  6307. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6308. httplib::Server svr;
  6309. svr.Post("/hi",
  6310. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6311. res.status = StatusCode::OK_200;
  6312. });
  6313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6314. svr.wait_until_ready();
  6315. Client cli(HOST, PORT);
  6316. auto res = cli.Post("/hi", "data", "text/plain");
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. svr.stop();
  6320. thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. res = cli.Post("/hi", "data", "text/plain");
  6323. ASSERT_FALSE(res);
  6324. }
  6325. TEST(ServerStopTest, ListenFailure) {
  6326. Server svr;
  6327. auto t = thread([&]() {
  6328. auto ret = svr.listen("????", PORT);
  6329. EXPECT_FALSE(ret);
  6330. });
  6331. svr.wait_until_ready();
  6332. svr.stop();
  6333. t.join();
  6334. }
  6335. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6336. TEST(ServerStopTest, Decommision) {
  6337. Server svr;
  6338. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6339. for (int i = 0; i < 4; i++) {
  6340. auto is_even = !(i % 2);
  6341. std::thread t{[&] {
  6342. try {
  6343. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6344. if (is_even) {
  6345. throw std::runtime_error("Some thing that happens to go wrong.");
  6346. }
  6347. svr.listen(HOST, PORT);
  6348. } catch (...) { svr.decommission(); }
  6349. }};
  6350. svr.wait_until_ready();
  6351. // Server is up
  6352. {
  6353. Client cli(HOST, PORT);
  6354. auto res = cli.Get("/hi");
  6355. if (is_even) {
  6356. EXPECT_FALSE(res);
  6357. } else {
  6358. EXPECT_TRUE(res);
  6359. EXPECT_EQ("hi...", res->body);
  6360. }
  6361. }
  6362. svr.stop();
  6363. t.join();
  6364. // Server is down...
  6365. {
  6366. Client cli(HOST, PORT);
  6367. auto res = cli.Get("/hi");
  6368. EXPECT_FALSE(res);
  6369. }
  6370. }
  6371. }
  6372. #endif
  6373. // Helper function for string body upload progress tests
  6374. template <typename SetupHandler, typename ClientCall>
  6375. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6376. ClientCall &&client_call,
  6377. const string &body) {
  6378. Server svr;
  6379. setup_handler(svr);
  6380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6381. auto se = detail::scope_exit([&] {
  6382. svr.stop();
  6383. t.join();
  6384. });
  6385. svr.wait_until_ready();
  6386. Client cli(HOST, PORT);
  6387. vector<uint64_t> progress_values;
  6388. bool progress_called = false;
  6389. auto res =
  6390. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6391. progress_values.push_back(current);
  6392. progress_called = true;
  6393. return true;
  6394. });
  6395. ASSERT_TRUE(res);
  6396. EXPECT_EQ(200, res->status);
  6397. EXPECT_TRUE(progress_called);
  6398. }
  6399. TEST(UploadProgressTest, PostStringBodyBasic) {
  6400. TestStringBodyUploadProgress(
  6401. [](Server &svr) {
  6402. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6403. res.set_content("received", "text/plain");
  6404. });
  6405. },
  6406. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6407. return cli.Post("/test", body, "text/plain", progress_callback);
  6408. },
  6409. "test data for upload progress");
  6410. }
  6411. TEST(UploadProgressTest, PutStringBodyBasic) {
  6412. TestStringBodyUploadProgress(
  6413. [](Server &svr) {
  6414. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6415. res.set_content("put received", "text/plain");
  6416. });
  6417. },
  6418. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6419. return cli.Put("/test", body, "text/plain", progress_callback);
  6420. },
  6421. "put test data for upload progress");
  6422. }
  6423. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6424. TestStringBodyUploadProgress(
  6425. [](Server &svr) {
  6426. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6427. res.set_content("patch received", "text/plain");
  6428. });
  6429. },
  6430. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6431. return cli.Patch("/test", body, "text/plain", progress_callback);
  6432. },
  6433. "patch test data for upload progress");
  6434. }
  6435. // Helper function for content provider upload progress tests
  6436. template <typename SetupHandler, typename ClientCall>
  6437. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6438. ClientCall &&client_call) {
  6439. Server svr;
  6440. setup_handler(svr);
  6441. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6442. auto se = detail::scope_exit([&] {
  6443. svr.stop();
  6444. t.join();
  6445. });
  6446. svr.wait_until_ready();
  6447. Client cli(HOST, PORT);
  6448. vector<uint64_t> progress_values;
  6449. auto res =
  6450. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6451. progress_values.push_back(current);
  6452. return true;
  6453. });
  6454. ASSERT_TRUE(res);
  6455. EXPECT_EQ(200, res->status);
  6456. EXPECT_FALSE(progress_values.empty());
  6457. }
  6458. TEST(UploadProgressTest, PostContentProviderProgress) {
  6459. TestContentProviderUploadProgress(
  6460. [](Server &svr) {
  6461. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6462. res.set_content("provider received", "text/plain");
  6463. });
  6464. },
  6465. [](Client &cli, UploadProgress progress_callback) {
  6466. return cli.Post(
  6467. "/test", 10,
  6468. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6469. sink.os << "test data";
  6470. return true;
  6471. },
  6472. "text/plain", progress_callback);
  6473. });
  6474. }
  6475. // Helper function for multipart upload progress tests
  6476. template <typename SetupHandler, typename ClientCall>
  6477. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6478. ClientCall &&client_call,
  6479. const string &endpoint) {
  6480. Server svr;
  6481. setup_handler(svr);
  6482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6483. auto se = detail::scope_exit([&] {
  6484. svr.stop();
  6485. t.join();
  6486. });
  6487. svr.wait_until_ready();
  6488. Client cli(HOST, PORT);
  6489. vector<uint64_t> progress_values;
  6490. UploadFormDataItems items = {
  6491. {"field1", "value1", "", ""},
  6492. {"field2", "longer value for progress tracking test", "", ""},
  6493. {"file1", "file content data for upload progress", "test.txt",
  6494. "text/plain"}};
  6495. auto res = client_call(cli, endpoint, items,
  6496. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6497. progress_values.push_back(current);
  6498. return true;
  6499. });
  6500. ASSERT_TRUE(res);
  6501. EXPECT_EQ(200, res->status);
  6502. EXPECT_FALSE(progress_values.empty());
  6503. }
  6504. TEST(UploadProgressTest, PostMultipartProgress) {
  6505. TestMultipartUploadProgress(
  6506. [](Server &svr) {
  6507. svr.Post("/multipart", [](const Request &req, Response &res) {
  6508. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6509. res.set_content("multipart received", "text/plain");
  6510. });
  6511. },
  6512. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6513. UploadProgress progress_callback) {
  6514. return cli.Post(endpoint, items, progress_callback);
  6515. },
  6516. "/multipart");
  6517. }
  6518. // Helper function for basic download progress tests
  6519. template <typename SetupHandler, typename ClientCall>
  6520. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6521. ClientCall &&client_call, const string &endpoint,
  6522. size_t expected_content_size) {
  6523. Server svr;
  6524. setup_handler(svr);
  6525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6526. auto se = detail::scope_exit([&] {
  6527. svr.stop();
  6528. t.join();
  6529. });
  6530. svr.wait_until_ready();
  6531. Client cli(HOST, PORT);
  6532. vector<uint64_t> progress_values;
  6533. auto res = client_call(cli, endpoint,
  6534. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6535. progress_values.push_back(current);
  6536. return true;
  6537. });
  6538. ASSERT_TRUE(res);
  6539. EXPECT_EQ(200, res->status);
  6540. EXPECT_FALSE(progress_values.empty());
  6541. EXPECT_EQ(expected_content_size, res->body.size());
  6542. }
  6543. TEST(DownloadProgressTest, GetBasic) {
  6544. TestBasicDownloadProgress(
  6545. [](Server &svr) {
  6546. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6547. string content(1000, 'D');
  6548. res.set_content(content, "text/plain");
  6549. });
  6550. },
  6551. [](Client &cli, const string &endpoint,
  6552. DownloadProgress progress_callback) {
  6553. return cli.Get(endpoint, progress_callback);
  6554. },
  6555. "/download", 1000u);
  6556. }
  6557. // Helper function for content receiver download progress tests
  6558. template <typename SetupHandler, typename ClientCall>
  6559. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6560. ClientCall &&client_call,
  6561. const string &endpoint,
  6562. size_t expected_content_size) {
  6563. Server svr;
  6564. setup_handler(svr);
  6565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. });
  6570. svr.wait_until_ready();
  6571. Client cli(HOST, PORT);
  6572. vector<uint64_t> progress_values;
  6573. string received_body;
  6574. auto res = client_call(
  6575. cli, endpoint,
  6576. [&](const char *data, size_t data_length) -> bool {
  6577. received_body.append(data, data_length);
  6578. return true;
  6579. },
  6580. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6581. progress_values.push_back(current);
  6582. return true;
  6583. });
  6584. ASSERT_TRUE(res);
  6585. EXPECT_EQ(200, res->status);
  6586. EXPECT_FALSE(progress_values.empty());
  6587. EXPECT_EQ(expected_content_size, received_body.size());
  6588. EXPECT_TRUE(res->body.empty());
  6589. }
  6590. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6591. TestContentReceiverDownloadProgress(
  6592. [](Server &svr) {
  6593. svr.Get("/download-receiver",
  6594. [](const Request & /*req*/, Response &res) {
  6595. string content(2000, 'R');
  6596. res.set_content(content, "text/plain");
  6597. });
  6598. },
  6599. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6600. DownloadProgress progress_callback) {
  6601. return cli.Get(endpoint, content_receiver, progress_callback);
  6602. },
  6603. "/download-receiver", 2000u);
  6604. }
  6605. TEST(StreamingTest, NoContentLengthStreaming) {
  6606. Server svr;
  6607. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6608. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6609. if (offset < 6) {
  6610. sink.os << (offset < 3 ? "a" : "b");
  6611. } else {
  6612. sink.done();
  6613. }
  6614. return true;
  6615. });
  6616. });
  6617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6618. auto listen_se = detail::scope_exit([&] {
  6619. svr.stop();
  6620. listen_thread.join();
  6621. ASSERT_FALSE(svr.is_running());
  6622. });
  6623. svr.wait_until_ready();
  6624. Client client(HOST, PORT);
  6625. auto get_thread = std::thread([&client]() {
  6626. std::string s;
  6627. auto res =
  6628. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6629. s += std::string(data, len);
  6630. return true;
  6631. });
  6632. ASSERT_TRUE(res);
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("aaabbb", s);
  6635. });
  6636. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6637. // Give GET time to get a few messages.
  6638. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6639. }
  6640. TEST(MountTest, Unmount) {
  6641. Server svr;
  6642. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6643. auto se = detail::scope_exit([&] {
  6644. svr.stop();
  6645. listen_thread.join();
  6646. ASSERT_FALSE(svr.is_running());
  6647. });
  6648. svr.wait_until_ready();
  6649. Client cli("localhost", PORT);
  6650. svr.set_mount_point("/mount2", "./www2");
  6651. auto res = cli.Get("/");
  6652. ASSERT_TRUE(res);
  6653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6654. res = cli.Get("/mount2/dir/test.html");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. svr.set_mount_point("/", "./www");
  6658. res = cli.Get("/dir/");
  6659. ASSERT_TRUE(res);
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. svr.remove_mount_point("/");
  6662. res = cli.Get("/dir/");
  6663. ASSERT_TRUE(res);
  6664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6665. svr.remove_mount_point("/mount2");
  6666. res = cli.Get("/mount2/dir/test.html");
  6667. ASSERT_TRUE(res);
  6668. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6669. }
  6670. TEST(MountTest, Redicect) {
  6671. Server svr;
  6672. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6673. auto se = detail::scope_exit([&] {
  6674. svr.stop();
  6675. listen_thread.join();
  6676. ASSERT_FALSE(svr.is_running());
  6677. });
  6678. svr.set_mount_point("/", "./www");
  6679. svr.wait_until_ready();
  6680. Client cli("localhost", PORT);
  6681. auto res = cli.Get("/dir/");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. res = cli.Get("/dir");
  6685. ASSERT_TRUE(res);
  6686. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6687. res = cli.Get("/file");
  6688. ASSERT_TRUE(res);
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. res = cli.Get("/file/");
  6691. ASSERT_TRUE(res);
  6692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6693. cli.set_follow_location(true);
  6694. res = cli.Get("/dir");
  6695. ASSERT_TRUE(res);
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. }
  6698. TEST(MountTest, MultibytesPathName) {
  6699. Server svr;
  6700. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6701. auto se = detail::scope_exit([&] {
  6702. svr.stop();
  6703. listen_thread.join();
  6704. ASSERT_FALSE(svr.is_running());
  6705. });
  6706. svr.set_mount_point("/", "./www");
  6707. svr.wait_until_ready();
  6708. Client cli("localhost", PORT);
  6709. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6710. ASSERT_TRUE(res);
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6713. }
  6714. TEST(KeepAliveTest, ReadTimeout) {
  6715. Server svr;
  6716. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6717. std::this_thread::sleep_for(std::chrono::seconds(2));
  6718. res.set_content("a", "text/plain");
  6719. });
  6720. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6721. res.set_content("b", "text/plain");
  6722. });
  6723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6724. auto se = detail::scope_exit([&] {
  6725. svr.stop();
  6726. listen_thread.join();
  6727. ASSERT_FALSE(svr.is_running());
  6728. });
  6729. svr.wait_until_ready();
  6730. Client cli("localhost", PORT);
  6731. cli.set_keep_alive(true);
  6732. cli.set_read_timeout(std::chrono::seconds(1));
  6733. auto resa = cli.Get("/a");
  6734. ASSERT_FALSE(resa);
  6735. EXPECT_EQ(Error::Read, resa.error());
  6736. auto resb = cli.Get("/b");
  6737. ASSERT_TRUE(resb);
  6738. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6739. EXPECT_EQ("b", resb->body);
  6740. }
  6741. TEST(KeepAliveTest, MaxCount) {
  6742. size_t keep_alive_max_count = 3;
  6743. Server svr;
  6744. svr.set_keep_alive_max_count(keep_alive_max_count);
  6745. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6746. res.set_content("Hello World!", "text/plain");
  6747. });
  6748. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6749. auto se = detail::scope_exit([&] {
  6750. svr.stop();
  6751. listen_thread.join();
  6752. ASSERT_FALSE(svr.is_running());
  6753. });
  6754. svr.wait_until_ready();
  6755. Client cli(HOST, PORT);
  6756. cli.set_keep_alive(true);
  6757. for (size_t i = 0; i < 5; i++) {
  6758. auto result = cli.Get("/hi");
  6759. ASSERT_TRUE(result);
  6760. EXPECT_EQ(StatusCode::OK_200, result->status);
  6761. if (i == keep_alive_max_count - 1) {
  6762. EXPECT_EQ("close", result->get_header_value("Connection"));
  6763. } else {
  6764. EXPECT_FALSE(result->has_header("Connection"));
  6765. }
  6766. }
  6767. }
  6768. TEST(KeepAliveTest, Issue1041) {
  6769. Server svr;
  6770. svr.set_keep_alive_timeout(3);
  6771. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6772. res.set_content("Hello World!", "text/plain");
  6773. });
  6774. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6775. auto se = detail::scope_exit([&] {
  6776. svr.stop();
  6777. listen_thread.join();
  6778. ASSERT_FALSE(svr.is_running());
  6779. });
  6780. svr.wait_until_ready();
  6781. Client cli(HOST, PORT);
  6782. cli.set_keep_alive(true);
  6783. auto result = cli.Get("/hi");
  6784. ASSERT_TRUE(result);
  6785. EXPECT_EQ(StatusCode::OK_200, result->status);
  6786. std::this_thread::sleep_for(std::chrono::seconds(5));
  6787. result = cli.Get("/hi");
  6788. ASSERT_TRUE(result);
  6789. EXPECT_EQ(StatusCode::OK_200, result->status);
  6790. }
  6791. TEST(KeepAliveTest, Issue1959) {
  6792. Server svr;
  6793. svr.set_keep_alive_timeout(5);
  6794. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6795. res.set_content("a", "text/plain");
  6796. });
  6797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6798. auto se = detail::scope_exit([&] {
  6799. if (!svr.is_running()) return;
  6800. svr.stop();
  6801. listen_thread.join();
  6802. ASSERT_FALSE(svr.is_running());
  6803. });
  6804. svr.wait_until_ready();
  6805. Client cli("localhost", PORT);
  6806. cli.set_keep_alive(true);
  6807. using namespace std::chrono;
  6808. auto start = steady_clock::now();
  6809. cli.Get("/a");
  6810. svr.stop();
  6811. listen_thread.join();
  6812. auto end = steady_clock::now();
  6813. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6814. EXPECT_LT(elapsed, 5000);
  6815. }
  6816. #ifdef CPPHTTPLIB_SSL_ENABLED
  6817. TEST(KeepAliveTest, SSLClientReconnection) {
  6818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6819. ASSERT_TRUE(svr.is_valid());
  6820. svr.set_keep_alive_timeout(1);
  6821. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6822. res.set_content("Hello World!", "text/plain");
  6823. });
  6824. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.wait_until_ready();
  6831. SSLClient cli(HOST, PORT);
  6832. cli.enable_server_certificate_verification(false);
  6833. cli.set_keep_alive(true);
  6834. auto result = cli.Get("/hi");
  6835. ASSERT_TRUE(result);
  6836. EXPECT_EQ(StatusCode::OK_200, result->status);
  6837. result = cli.Get("/hi");
  6838. ASSERT_TRUE(result);
  6839. EXPECT_EQ(StatusCode::OK_200, result->status);
  6840. std::this_thread::sleep_for(std::chrono::seconds(2));
  6841. // Recoonect
  6842. result = cli.Get("/hi");
  6843. ASSERT_TRUE(result);
  6844. EXPECT_EQ(StatusCode::OK_200, result->status);
  6845. result = cli.Get("/hi");
  6846. ASSERT_TRUE(result);
  6847. EXPECT_EQ(StatusCode::OK_200, result->status);
  6848. }
  6849. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6851. ASSERT_TRUE(svr.is_valid());
  6852. svr.set_keep_alive_timeout(1);
  6853. std::string content = "reconnect";
  6854. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6855. res.set_content("Hello World!", "text/plain");
  6856. });
  6857. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6858. auto se = detail::scope_exit([&] {
  6859. svr.stop();
  6860. listen_thread.join();
  6861. ASSERT_FALSE(svr.is_running());
  6862. });
  6863. svr.wait_until_ready();
  6864. SSLClient cli(HOST, PORT);
  6865. cli.enable_server_certificate_verification(false);
  6866. cli.set_keep_alive(true);
  6867. auto result = cli.Post(
  6868. "/hi", content.size(),
  6869. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6870. sink.write(content.c_str(), content.size());
  6871. return true;
  6872. },
  6873. "text/plain");
  6874. ASSERT_TRUE(result);
  6875. EXPECT_EQ(200, result->status);
  6876. std::this_thread::sleep_for(std::chrono::seconds(2));
  6877. // Recoonect
  6878. result = cli.Post(
  6879. "/hi", content.size(),
  6880. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6881. sink.write(content.c_str(), content.size());
  6882. return true;
  6883. },
  6884. "text/plain");
  6885. ASSERT_TRUE(result);
  6886. EXPECT_EQ(200, result->status);
  6887. result = cli.Post(
  6888. "/hi", content.size(),
  6889. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6890. sink.write(content.c_str(), content.size());
  6891. return true;
  6892. },
  6893. "text/plain");
  6894. ASSERT_TRUE(result);
  6895. EXPECT_EQ(200, result->status);
  6896. }
  6897. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6898. using namespace httplib::tls;
  6899. {
  6900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6901. ASSERT_TRUE(svr.is_valid());
  6902. svr.Get("/sni", [&](const Request &req, Response &res) {
  6903. std::string expected = req.sni();
  6904. EXPECT_EQ(expected, req.get_param_value("expected"));
  6905. res.set_content("ok", "text/plain");
  6906. });
  6907. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6908. auto se = detail::scope_exit([&] {
  6909. svr.stop();
  6910. listen_thread.join();
  6911. ASSERT_FALSE(svr.is_running());
  6912. });
  6913. svr.wait_until_ready();
  6914. {
  6915. SSLClient cli("localhost", PORT);
  6916. cli.enable_server_certificate_verification(false);
  6917. auto res = cli.Get("/sni?expected=localhost");
  6918. ASSERT_TRUE(res);
  6919. }
  6920. {
  6921. SSLClient cli("::1", PORT);
  6922. cli.enable_server_certificate_verification(false);
  6923. auto res = cli.Get("/sni?expected=");
  6924. // NOTE: This may fail if the server is listening on IPv4 only
  6925. // (e.g., when localhost resolves to 127.0.0.1 only)
  6926. if (res) {
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. } else {
  6929. EXPECT_EQ(Error::Connection, res.error());
  6930. }
  6931. }
  6932. }
  6933. }
  6934. #endif
  6935. TEST(ClientProblemDetectionTest, ContentProvider) {
  6936. Server svr;
  6937. size_t content_length = 1024 * 1024;
  6938. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6939. res.set_content_provider(
  6940. content_length, "text/plain",
  6941. [&](size_t offset, size_t length, DataSink &sink) {
  6942. auto out_len = std::min(length, static_cast<size_t>(1024));
  6943. std::string out(out_len, '@');
  6944. sink.write(out.data(), out_len);
  6945. return offset < 4096;
  6946. },
  6947. [](bool success) { ASSERT_FALSE(success); });
  6948. });
  6949. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6950. res.set_content_provider(
  6951. 0, "text/plain",
  6952. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6953. EXPECT_TRUE(false);
  6954. return true;
  6955. },
  6956. [](bool success) { ASSERT_FALSE(success); });
  6957. });
  6958. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6959. auto se = detail::scope_exit([&] {
  6960. svr.stop();
  6961. listen_thread.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. Client cli("localhost", PORT);
  6966. {
  6967. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6968. size_t /*data_length*/) { return false; });
  6969. ASSERT_FALSE(res);
  6970. }
  6971. {
  6972. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6973. size_t /*data_length*/) { return false; });
  6974. ASSERT_TRUE(res);
  6975. }
  6976. }
  6977. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6978. Server svr;
  6979. svr.set_error_handler([](Request const &, Response &res) -> void {
  6980. res.set_chunked_content_provider(
  6981. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6982. sink.os << "hello";
  6983. sink.os << "world";
  6984. sink.done();
  6985. return true;
  6986. });
  6987. });
  6988. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6989. auto se = detail::scope_exit([&] {
  6990. svr.stop();
  6991. listen_thread.join();
  6992. ASSERT_FALSE(svr.is_running());
  6993. });
  6994. svr.wait_until_ready();
  6995. Client cli("localhost", PORT);
  6996. auto res = cli.Get("/");
  6997. ASSERT_TRUE(res);
  6998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6999. EXPECT_EQ("helloworld", res->body);
  7000. }
  7001. TEST(LongPollingTest, ClientCloseDetection) {
  7002. Server svr;
  7003. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7004. res.set_chunked_content_provider(
  7005. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7006. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7007. sink.os << "hello";
  7008. auto count = 10;
  7009. while (count > 0 && sink.is_writable()) {
  7010. this_thread::sleep_for(chrono::milliseconds(10));
  7011. count--;
  7012. }
  7013. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7014. return true;
  7015. });
  7016. });
  7017. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7018. auto se = detail::scope_exit([&] {
  7019. svr.stop();
  7020. listen_thread.join();
  7021. ASSERT_FALSE(svr.is_running());
  7022. });
  7023. svr.wait_until_ready();
  7024. Client cli("localhost", PORT);
  7025. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7026. EXPECT_EQ("hello", string(data, data_length));
  7027. return false; // close the socket immediately.
  7028. });
  7029. ASSERT_FALSE(res);
  7030. }
  7031. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7032. Server svr;
  7033. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7034. res.set_chunked_content_provider(
  7035. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7036. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7037. sink.os << "hello";
  7038. EXPECT_TRUE(sink.os.good());
  7039. // Wait for the client to close the connection
  7040. auto count = 10;
  7041. while (count > 0 && sink.is_writable()) {
  7042. this_thread::sleep_for(chrono::milliseconds(10));
  7043. count--;
  7044. }
  7045. // After client disconnect, write repeatedly until the socket
  7046. // write actually fails (small writes may be absorbed by the
  7047. // kernel buffer)
  7048. std::string chunk(1024, 'x');
  7049. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7050. sink.os << chunk;
  7051. }
  7052. EXPECT_TRUE(sink.os.fail());
  7053. return true;
  7054. });
  7055. });
  7056. auto port = svr.bind_to_any_port("localhost");
  7057. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7058. auto se = detail::scope_exit([&] {
  7059. svr.stop();
  7060. listen_thread.join();
  7061. ASSERT_FALSE(svr.is_running());
  7062. });
  7063. svr.wait_until_ready();
  7064. Client cli("localhost", port);
  7065. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7066. EXPECT_EQ("hello", string(data, data_length));
  7067. return false; // close the socket immediately.
  7068. });
  7069. ASSERT_FALSE(res);
  7070. }
  7071. TEST(GetWithParametersTest, GetWithParameters) {
  7072. Server svr;
  7073. svr.Get("/", [&](const Request &req, Response &) {
  7074. EXPECT_EQ("world", req.get_param_value("hello"));
  7075. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7076. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7077. });
  7078. svr.Get("/params", [&](const Request &req, Response &) {
  7079. EXPECT_EQ("world", req.get_param_value("hello"));
  7080. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7081. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7082. });
  7083. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7084. EXPECT_EQ("resource-id", req.matches[1]);
  7085. EXPECT_EQ("foo", req.get_param_value("param1"));
  7086. EXPECT_EQ("bar", req.get_param_value("param2"));
  7087. });
  7088. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7089. EXPECT_EQ("user-id", req.path_params.at("id"));
  7090. EXPECT_EQ("foo", req.get_param_value("param1"));
  7091. EXPECT_EQ("bar", req.get_param_value("param2"));
  7092. });
  7093. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7094. auto se = detail::scope_exit([&] {
  7095. svr.stop();
  7096. listen_thread.join();
  7097. ASSERT_FALSE(svr.is_running());
  7098. });
  7099. svr.wait_until_ready();
  7100. {
  7101. Client cli(HOST, PORT);
  7102. Params params;
  7103. params.emplace("hello", "world");
  7104. params.emplace("hello2", "world2");
  7105. params.emplace("hello3", "world3");
  7106. auto res = cli.Get("/", params, Headers{});
  7107. ASSERT_TRUE(res);
  7108. EXPECT_EQ(StatusCode::OK_200, res->status);
  7109. }
  7110. {
  7111. Client cli(HOST, PORT);
  7112. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7113. ASSERT_TRUE(res);
  7114. EXPECT_EQ(StatusCode::OK_200, res->status);
  7115. }
  7116. {
  7117. Client cli(HOST, PORT);
  7118. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7119. ASSERT_TRUE(res);
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. }
  7122. {
  7123. Client cli(HOST, PORT);
  7124. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7125. ASSERT_TRUE(res);
  7126. EXPECT_EQ(StatusCode::OK_200, res->status);
  7127. }
  7128. }
  7129. TEST(GetWithParametersTest, GetWithParameters2) {
  7130. Server svr;
  7131. svr.Get("/", [&](const Request &req, Response &res) {
  7132. auto text = req.get_param_value("hello");
  7133. res.set_content(text, "text/plain");
  7134. });
  7135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7136. auto se = detail::scope_exit([&] {
  7137. svr.stop();
  7138. listen_thread.join();
  7139. ASSERT_FALSE(svr.is_running());
  7140. });
  7141. svr.wait_until_ready();
  7142. Client cli("localhost", PORT);
  7143. Params params;
  7144. params.emplace("hello", "world");
  7145. std::string body;
  7146. auto res = cli.Get("/", params, Headers{},
  7147. [&](const char *data, size_t data_length) {
  7148. body.append(data, data_length);
  7149. return true;
  7150. });
  7151. ASSERT_TRUE(res);
  7152. EXPECT_EQ(StatusCode::OK_200, res->status);
  7153. EXPECT_EQ("world", body);
  7154. }
  7155. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7156. auto host = "httpbingo.org";
  7157. auto path = std::string{"/range/32"};
  7158. #ifdef CPPHTTPLIB_SSL_ENABLED
  7159. SSLClient cli(host);
  7160. #else
  7161. Client cli(host);
  7162. #endif
  7163. cli.set_default_headers({make_range_header({{1, 10}})});
  7164. cli.set_connection_timeout(5);
  7165. {
  7166. auto res = cli.Get(path);
  7167. ASSERT_TRUE(res);
  7168. EXPECT_EQ("bcdefghijk", res->body);
  7169. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7170. }
  7171. {
  7172. auto res = cli.Get(path);
  7173. ASSERT_TRUE(res);
  7174. EXPECT_EQ("bcdefghijk", res->body);
  7175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7176. }
  7177. }
  7178. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7179. Server svr;
  7180. svr.set_default_headers({{"Hello", "World"}});
  7181. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7182. res.set_content("ok", "text/plain");
  7183. });
  7184. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7185. auto se = detail::scope_exit([&] {
  7186. svr.stop();
  7187. listen_thread.join();
  7188. ASSERT_FALSE(svr.is_running());
  7189. });
  7190. svr.wait_until_ready();
  7191. Client cli("localhost", PORT);
  7192. auto res = cli.Get("/");
  7193. ASSERT_TRUE(res);
  7194. EXPECT_EQ(StatusCode::OK_200, res->status);
  7195. EXPECT_EQ("ok", res->body);
  7196. EXPECT_EQ("World", res->get_header_value("Hello"));
  7197. }
  7198. #ifdef CPPHTTPLIB_SSL_ENABLED
  7199. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7200. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7201. ASSERT_TRUE(svr.is_valid());
  7202. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7203. std::this_thread::sleep_for(std::chrono::seconds(2));
  7204. res.set_content("a", "text/plain");
  7205. });
  7206. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7207. res.set_content("b", "text/plain");
  7208. });
  7209. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7210. auto se = detail::scope_exit([&] {
  7211. svr.stop();
  7212. listen_thread.join();
  7213. ASSERT_FALSE(svr.is_running());
  7214. });
  7215. svr.wait_until_ready();
  7216. SSLClient cli("localhost", PORT);
  7217. cli.enable_server_certificate_verification(false);
  7218. cli.set_keep_alive(true);
  7219. cli.set_read_timeout(std::chrono::seconds(1));
  7220. auto resa = cli.Get("/a");
  7221. ASSERT_TRUE(!resa);
  7222. EXPECT_EQ(Error::Read, resa.error());
  7223. auto resb = cli.Get("/b");
  7224. ASSERT_TRUE(resb);
  7225. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7226. EXPECT_EQ("b", resb->body);
  7227. }
  7228. #endif
  7229. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7230. protected:
  7231. ServerTestWithAI_PASSIVE()
  7232. : cli_(HOST, PORT)
  7233. #ifdef CPPHTTPLIB_SSL_ENABLED
  7234. ,
  7235. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7236. #endif
  7237. {
  7238. #ifdef CPPHTTPLIB_SSL_ENABLED
  7239. cli_.enable_server_certificate_verification(false);
  7240. #endif
  7241. }
  7242. virtual void SetUp() {
  7243. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7244. res.set_content("Hello World!", "text/plain");
  7245. });
  7246. t_ = thread(
  7247. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7248. svr_.wait_until_ready();
  7249. }
  7250. virtual void TearDown() {
  7251. svr_.stop();
  7252. t_.join();
  7253. }
  7254. #ifdef CPPHTTPLIB_SSL_ENABLED
  7255. SSLClient cli_;
  7256. SSLServer svr_;
  7257. #else
  7258. Client cli_;
  7259. Server svr_;
  7260. #endif
  7261. thread t_;
  7262. };
  7263. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7264. auto res = cli_.Get("/hi");
  7265. ASSERT_TRUE(res);
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7268. EXPECT_EQ("Hello World!", res->body);
  7269. }
  7270. class ServerUpDownTest : public ::testing::Test {
  7271. protected:
  7272. ServerUpDownTest() : cli_(HOST, PORT) {}
  7273. virtual void SetUp() {
  7274. t_ = thread([&]() {
  7275. svr_.bind_to_any_port(HOST);
  7276. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7277. ASSERT_TRUE(svr_.listen_after_bind());
  7278. });
  7279. svr_.wait_until_ready();
  7280. }
  7281. virtual void TearDown() {
  7282. svr_.stop();
  7283. t_.join();
  7284. }
  7285. Client cli_;
  7286. Server svr_;
  7287. thread t_;
  7288. };
  7289. TEST_F(ServerUpDownTest, QuickStartStop) {
  7290. // Should not crash, especially when run with
  7291. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7292. }
  7293. class PayloadMaxLengthTest : public ::testing::Test {
  7294. protected:
  7295. PayloadMaxLengthTest()
  7296. : cli_(HOST, PORT)
  7297. #ifdef CPPHTTPLIB_SSL_ENABLED
  7298. ,
  7299. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7300. #endif
  7301. {
  7302. #ifdef CPPHTTPLIB_SSL_ENABLED
  7303. cli_.enable_server_certificate_verification(false);
  7304. #endif
  7305. }
  7306. virtual void SetUp() {
  7307. svr_.set_payload_max_length(8);
  7308. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7309. res.set_content("test", "text/plain");
  7310. });
  7311. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7312. svr_.wait_until_ready();
  7313. }
  7314. virtual void TearDown() {
  7315. svr_.stop();
  7316. t_.join();
  7317. }
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. SSLClient cli_;
  7320. SSLServer svr_;
  7321. #else
  7322. Client cli_;
  7323. Server svr_;
  7324. #endif
  7325. thread t_;
  7326. };
  7327. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7328. auto res = cli_.Post("/test", "123456789", "text/plain");
  7329. ASSERT_TRUE(res);
  7330. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7331. res = cli_.Post("/test", "12345678", "text/plain");
  7332. ASSERT_TRUE(res);
  7333. EXPECT_EQ(StatusCode::OK_200, res->status);
  7334. }
  7335. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7336. // Test chunked encoding with payload exceeding the 8-byte limit
  7337. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7338. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7339. ASSERT_TRUE(res);
  7340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7341. }
  7342. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7343. // Test chunked encoding with payload within the 8-byte limit
  7344. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7345. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7346. ASSERT_TRUE(res);
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. }
  7349. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7350. // Test using send_request to send chunked data exceeding payload limit
  7351. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7352. "Host: " +
  7353. std::string(HOST) + ":" + std::to_string(PORT) +
  7354. "\r\n"
  7355. "Transfer-Encoding: chunked\r\n"
  7356. "Connection: close\r\n"
  7357. "\r\n"
  7358. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7359. "0123456789\r\n"
  7360. "0\r\n" // End chunk
  7361. "\r\n";
  7362. std::string response;
  7363. bool result = send_request(1, chunked_request, &response);
  7364. if (!result) {
  7365. // If send_request fails, it might be because the server closed the
  7366. // connection due to payload limit enforcement, which is acceptable
  7367. SUCCEED()
  7368. << "Server rejected oversized chunked request (connection closed)";
  7369. } else {
  7370. // If we got a response, check if it's an error response or connection was
  7371. // closed early Short response length indicates connection was closed due to
  7372. // payload limit
  7373. if (response.length() <= 10) {
  7374. SUCCEED() << "Server closed connection for oversized chunked request";
  7375. } else {
  7376. // Check for error status codes
  7377. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7378. response.find("Payload Too Large") != std::string::npos ||
  7379. response.find("400") != std::string::npos);
  7380. }
  7381. }
  7382. }
  7383. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7384. // Test request without Content-Length header exceeding payload limit
  7385. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7386. "Host: " +
  7387. std::string(HOST) + ":" +
  7388. std::to_string(PORT) +
  7389. "\r\n"
  7390. "Connection: close\r\n"
  7391. "\r\n";
  7392. // Add payload exceeding the 8-byte limit
  7393. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7394. request_without_content_length += large_payload;
  7395. std::string response;
  7396. bool result = send_request(1, request_without_content_length, &response);
  7397. if (!result) {
  7398. // If send_request fails, server likely closed connection due to payload
  7399. // limit
  7400. SUCCEED() << "Server rejected oversized request without Content-Length "
  7401. "(connection closed)";
  7402. } else {
  7403. // Check if server responded with error or closed connection early
  7404. if (response.length() <= 10) {
  7405. SUCCEED() << "Server closed connection for oversized request without "
  7406. "Content-Length";
  7407. } else {
  7408. // Check for error status codes
  7409. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7410. response.find("Payload Too Large") != std::string::npos ||
  7411. response.find("400") != std::string::npos);
  7412. }
  7413. }
  7414. }
  7415. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7416. // Test request without Content-Length header within payload limit
  7417. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7418. "Host: " +
  7419. std::string(HOST) + ":" +
  7420. std::to_string(PORT) +
  7421. "\r\n"
  7422. "Connection: close\r\n"
  7423. "\r\n";
  7424. // Add payload within the 8-byte limit
  7425. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7426. request_without_content_length += small_payload;
  7427. std::string response;
  7428. bool result = send_request(1, request_without_content_length, &response);
  7429. // For requests without Content-Length, the server may have different behavior
  7430. // The key is that it should not reject due to payload limit for small
  7431. // payloads
  7432. if (result) {
  7433. // Check for any HTTP response (success or error, but not connection closed)
  7434. if (response.length() > 10) {
  7435. SUCCEED()
  7436. << "Server processed request without Content-Length within limit";
  7437. } else {
  7438. // Short response might indicate connection closed, which is acceptable
  7439. SUCCEED() << "Server closed connection for request without "
  7440. "Content-Length (acceptable behavior)";
  7441. }
  7442. } else {
  7443. // Connection failure might be due to protocol requirements
  7444. SUCCEED() << "Connection issue with request without Content-Length "
  7445. "(environment-specific)";
  7446. }
  7447. }
  7448. class LargePayloadMaxLengthTest : public ::testing::Test {
  7449. protected:
  7450. LargePayloadMaxLengthTest()
  7451. : cli_(HOST, PORT)
  7452. #ifdef CPPHTTPLIB_SSL_ENABLED
  7453. ,
  7454. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7455. #endif
  7456. {
  7457. #ifdef CPPHTTPLIB_SSL_ENABLED
  7458. cli_.enable_server_certificate_verification(false);
  7459. #endif
  7460. }
  7461. virtual void SetUp() {
  7462. // Set 10MB payload limit
  7463. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7464. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7465. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7466. res.set_content("Large payload test", "text/plain");
  7467. });
  7468. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7469. svr_.wait_until_ready();
  7470. }
  7471. virtual void TearDown() {
  7472. svr_.stop();
  7473. t_.join();
  7474. }
  7475. #ifdef CPPHTTPLIB_SSL_ENABLED
  7476. SSLClient cli_;
  7477. SSLServer svr_;
  7478. #else
  7479. Client cli_;
  7480. Server svr_;
  7481. #endif
  7482. thread t_;
  7483. };
  7484. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7485. // Test chunked encoding with payload within 10MB limit
  7486. std::string medium_payload(5 * 1024 * 1024,
  7487. 'A'); // 5MB payload, within 10MB limit
  7488. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7489. ASSERT_TRUE(res);
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. }
  7492. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7493. // Test chunked encoding with payload exceeding 10MB limit
  7494. std::string large_payload(12 * 1024 * 1024,
  7495. 'B'); // 12MB payload, exceeds 10MB limit
  7496. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7497. // Server may either return 413 or close the connection
  7498. if (res) {
  7499. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7500. } else {
  7501. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7502. }
  7503. }
  7504. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7505. // Test request without Content-Length header within 10MB limit
  7506. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7507. "Host: " +
  7508. std::string(HOST) + ":" +
  7509. std::to_string(PORT) +
  7510. "\r\n"
  7511. "Connection: close\r\n"
  7512. "\r\n";
  7513. // Add 1MB payload (within 10MB limit)
  7514. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7515. request_without_content_length += medium_payload;
  7516. std::string response;
  7517. bool result = send_request(5, request_without_content_length, &response);
  7518. if (result) {
  7519. // Should get a proper HTTP response for payloads within limit
  7520. if (response.length() > 10) {
  7521. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7522. "10MB limit";
  7523. } else {
  7524. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7525. "Content-Length)";
  7526. }
  7527. } else {
  7528. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7529. }
  7530. }
  7531. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7532. // Test request without Content-Length header exceeding 10MB limit
  7533. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7534. "Host: " +
  7535. std::string(HOST) + ":" +
  7536. std::to_string(PORT) +
  7537. "\r\n"
  7538. "Connection: close\r\n"
  7539. "\r\n";
  7540. // Add 12MB payload (exceeds 10MB limit)
  7541. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7542. request_without_content_length += large_payload;
  7543. std::string response;
  7544. bool result = send_request(10, request_without_content_length, &response);
  7545. if (!result) {
  7546. // Server should close connection due to payload limit
  7547. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7548. "(connection closed)";
  7549. } else {
  7550. // Check for error response
  7551. if (response.length() <= 10) {
  7552. SUCCEED()
  7553. << "Server closed connection for 12MB request exceeding 10MB limit";
  7554. } else {
  7555. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7556. response.find("Payload Too Large") != std::string::npos ||
  7557. response.find("400") != std::string::npos);
  7558. }
  7559. }
  7560. }
  7561. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7562. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7563. // path.
  7564. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7565. Server svr;
  7566. const size_t LIMIT = 64 * 1024; // 64KB
  7567. svr.set_payload_max_length(LIMIT);
  7568. size_t total = 0;
  7569. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7570. const ContentReader &content_reader) {
  7571. content_reader([&](const char * /*data*/, size_t len) {
  7572. total += len;
  7573. return true;
  7574. });
  7575. res.status = 200;
  7576. res.set_content("stream_ok", "text/plain");
  7577. });
  7578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7579. auto se = detail::scope_exit([&] {
  7580. svr.stop();
  7581. thread.join();
  7582. ASSERT_FALSE(svr.is_running());
  7583. });
  7584. svr.wait_until_ready();
  7585. // Prepare 256KB raw data and gzip-compress it
  7586. std::string raw(256 * 1024, 'A');
  7587. std::string gz;
  7588. {
  7589. z_stream zs{};
  7590. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7591. Z_DEFAULT_STRATEGY);
  7592. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7593. zs.avail_in = static_cast<uInt>(raw.size());
  7594. char outbuf[4096];
  7595. int ret;
  7596. do {
  7597. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7598. zs.avail_out = sizeof(outbuf);
  7599. ret = deflate(&zs, Z_FINISH);
  7600. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7601. } while (ret != Z_STREAM_END);
  7602. deflateEnd(&zs);
  7603. }
  7604. Client cli(HOST, PORT);
  7605. cli.set_connection_timeout(std::chrono::seconds(5));
  7606. Headers headers = {{"Content-Encoding", "gzip"}};
  7607. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7608. "application/octet-stream");
  7609. ASSERT_TRUE(res);
  7610. // Server must reject oversized decompressed payloads with 413.
  7611. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7612. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7613. EXPECT_LE(total, LIMIT);
  7614. }
  7615. #endif
  7616. // Regression test for DoS vulnerability: a malicious server sending a response
  7617. // without Content-Length header must not cause unbounded memory consumption on
  7618. // the client side. The client should stop reading after a reasonable limit,
  7619. // similar to the server-side set_payload_max_length protection.
  7620. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7621. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7622. #ifndef _WIN32
  7623. signal(SIGPIPE, SIG_IGN);
  7624. #endif
  7625. auto server_thread = std::thread([] {
  7626. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7627. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7628. default_socket_options(srv);
  7629. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7630. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7631. sockaddr_in addr{};
  7632. addr.sin_family = AF_INET;
  7633. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7634. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7635. int opt = 1;
  7636. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7637. #ifdef _WIN32
  7638. reinterpret_cast<const char *>(&opt),
  7639. #else
  7640. &opt,
  7641. #endif
  7642. sizeof(opt));
  7643. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7644. ::listen(srv, 1);
  7645. sockaddr_in cli_addr{};
  7646. socklen_t cli_len = sizeof(cli_addr);
  7647. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7648. if (cli != INVALID_SOCKET) {
  7649. char buf[4096];
  7650. ::recv(cli, buf, sizeof(buf), 0);
  7651. // Malicious response: no Content-Length, no chunked encoding
  7652. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7653. "Connection: close\r\n"
  7654. "\r\n";
  7655. ::send(cli,
  7656. #ifdef _WIN32
  7657. static_cast<const char *>(response_header.c_str()),
  7658. static_cast<int>(response_header.size()),
  7659. #else
  7660. response_header.c_str(), response_header.size(),
  7661. #endif
  7662. 0);
  7663. // Send 10MB of data
  7664. std::string chunk(64 * 1024, 'A');
  7665. size_t total_sent = 0;
  7666. while (total_sent < MALICIOUS_DATA_SIZE) {
  7667. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7668. auto sent = ::send(cli,
  7669. #ifdef _WIN32
  7670. static_cast<const char *>(chunk.c_str()),
  7671. static_cast<int>(to_send),
  7672. #else
  7673. chunk.c_str(), to_send,
  7674. #endif
  7675. 0);
  7676. if (sent <= 0) break;
  7677. total_sent += static_cast<size_t>(sent);
  7678. }
  7679. detail::close_socket(cli);
  7680. }
  7681. detail::close_socket(srv);
  7682. });
  7683. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7684. size_t total_read = 0;
  7685. {
  7686. Client cli("127.0.0.1", PORT + 2);
  7687. cli.set_read_timeout(5, 0);
  7688. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7689. auto stream = cli.open_stream("GET", "/malicious");
  7690. ASSERT_TRUE(stream.is_valid());
  7691. char buffer[64 * 1024];
  7692. ssize_t n;
  7693. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7694. total_read += static_cast<size_t>(n);
  7695. }
  7696. } // StreamHandle and Client destroyed here, closing the socket
  7697. server_thread.join();
  7698. // With set_payload_max_length, the client must stop reading before consuming
  7699. // all 10MB. The read loop should be cut off at or near the configured limit.
  7700. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7701. << "Client read " << total_read << " bytes, exceeding the configured "
  7702. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7703. }
  7704. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7705. // the entire response body without truncation.
  7706. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7707. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7708. #ifndef _WIN32
  7709. signal(SIGPIPE, SIG_IGN);
  7710. #endif
  7711. auto server_thread = std::thread([] {
  7712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7713. default_socket_options(srv);
  7714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7716. sockaddr_in addr{};
  7717. addr.sin_family = AF_INET;
  7718. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7720. int opt = 1;
  7721. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7722. #ifdef _WIN32
  7723. reinterpret_cast<const char *>(&opt),
  7724. #else
  7725. &opt,
  7726. #endif
  7727. sizeof(opt));
  7728. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7729. ::listen(srv, 1);
  7730. sockaddr_in cli_addr{};
  7731. socklen_t cli_len = sizeof(cli_addr);
  7732. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7733. if (cli != INVALID_SOCKET) {
  7734. char buf[4096];
  7735. ::recv(cli, buf, sizeof(buf), 0);
  7736. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7737. "Connection: close\r\n"
  7738. "\r\n";
  7739. ::send(cli,
  7740. #ifdef _WIN32
  7741. static_cast<const char *>(response_header.c_str()),
  7742. static_cast<int>(response_header.size()),
  7743. #else
  7744. response_header.c_str(), response_header.size(),
  7745. #endif
  7746. 0);
  7747. std::string chunk(64 * 1024, 'A');
  7748. size_t total_sent = 0;
  7749. while (total_sent < DATA_SIZE) {
  7750. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7751. auto sent = ::send(cli,
  7752. #ifdef _WIN32
  7753. static_cast<const char *>(chunk.c_str()),
  7754. static_cast<int>(to_send),
  7755. #else
  7756. chunk.c_str(), to_send,
  7757. #endif
  7758. 0);
  7759. if (sent <= 0) break;
  7760. total_sent += static_cast<size_t>(sent);
  7761. }
  7762. #ifdef _WIN32
  7763. ::shutdown(cli, SD_SEND);
  7764. #else
  7765. ::shutdown(cli, SHUT_WR);
  7766. #endif
  7767. // Drain until the client closes its end, ensuring all data is delivered
  7768. char drain[1024];
  7769. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7770. detail::close_socket(cli);
  7771. }
  7772. detail::close_socket(srv);
  7773. });
  7774. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7775. size_t total_read = 0;
  7776. {
  7777. Client cli("127.0.0.1", PORT + 2);
  7778. cli.set_read_timeout(5, 0);
  7779. cli.set_payload_max_length(0); // 0 means no limit
  7780. auto stream = cli.open_stream("GET", "/data");
  7781. ASSERT_TRUE(stream.is_valid());
  7782. char buffer[64 * 1024];
  7783. ssize_t n;
  7784. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7785. total_read += static_cast<size_t>(n);
  7786. }
  7787. }
  7788. server_thread.join();
  7789. EXPECT_EQ(total_read, DATA_SIZE)
  7790. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7791. << " bytes without truncation, but only read " << total_read << " bytes.";
  7792. }
  7793. // Verify that content_receiver bypasses the default payload_max_length,
  7794. // allowing streaming downloads larger than 100MB without requiring an explicit
  7795. // set_payload_max_length call.
  7796. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7797. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7798. #ifndef _WIN32
  7799. signal(SIGPIPE, SIG_IGN);
  7800. #endif
  7801. auto server_thread = std::thread([] {
  7802. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7803. default_socket_options(srv);
  7804. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7805. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7806. sockaddr_in addr{};
  7807. addr.sin_family = AF_INET;
  7808. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7809. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7810. int opt = 1;
  7811. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7812. #ifdef _WIN32
  7813. reinterpret_cast<const char *>(&opt),
  7814. #else
  7815. &opt,
  7816. #endif
  7817. sizeof(opt));
  7818. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7819. ::listen(srv, 1);
  7820. sockaddr_in cli_addr{};
  7821. socklen_t cli_len = sizeof(cli_addr);
  7822. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7823. if (cli != INVALID_SOCKET) {
  7824. char buf[4096];
  7825. ::recv(cli, buf, sizeof(buf), 0);
  7826. // Response with Content-Length larger than default 100MB limit
  7827. auto content_length = std::to_string(DATA_SIZE);
  7828. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7829. "Content-Length: " +
  7830. content_length +
  7831. "\r\n"
  7832. "Connection: close\r\n"
  7833. "\r\n";
  7834. ::send(cli,
  7835. #ifdef _WIN32
  7836. static_cast<const char *>(response_header.c_str()),
  7837. static_cast<int>(response_header.size()),
  7838. #else
  7839. response_header.c_str(), response_header.size(),
  7840. #endif
  7841. 0);
  7842. std::string chunk(64 * 1024, 'A');
  7843. size_t total_sent = 0;
  7844. while (total_sent < DATA_SIZE) {
  7845. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7846. auto sent = ::send(cli,
  7847. #ifdef _WIN32
  7848. static_cast<const char *>(chunk.c_str()),
  7849. static_cast<int>(to_send),
  7850. #else
  7851. chunk.c_str(), to_send,
  7852. #endif
  7853. 0);
  7854. if (sent <= 0) break;
  7855. total_sent += static_cast<size_t>(sent);
  7856. }
  7857. detail::close_socket(cli);
  7858. }
  7859. detail::close_socket(srv);
  7860. });
  7861. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7862. size_t total_received = 0;
  7863. {
  7864. Client cli("127.0.0.1", PORT + 2);
  7865. cli.set_read_timeout(10, 0);
  7866. // Do NOT call set_payload_max_length — use the default 100MB limit
  7867. auto res =
  7868. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7869. total_received += data_length;
  7870. return true;
  7871. });
  7872. ASSERT_TRUE(res);
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. }
  7875. server_thread.join();
  7876. EXPECT_EQ(total_received, DATA_SIZE)
  7877. << "With content_receiver, the client should read all " << DATA_SIZE
  7878. << " bytes despite the default 100MB payload_max_length, but only read "
  7879. << total_received << " bytes.";
  7880. }
  7881. // Verify that an explicit set_payload_max_length smaller than the response is
  7882. // enforced even when a content_receiver is used.
  7883. TEST(ClientVulnerabilityTest,
  7884. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7885. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7886. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7887. #ifndef _WIN32
  7888. signal(SIGPIPE, SIG_IGN);
  7889. #endif
  7890. auto server_thread = std::thread([] {
  7891. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7892. default_socket_options(srv);
  7893. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7894. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7895. sockaddr_in addr{};
  7896. addr.sin_family = AF_INET;
  7897. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7898. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7899. int opt = 1;
  7900. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7901. #ifdef _WIN32
  7902. reinterpret_cast<const char *>(&opt),
  7903. #else
  7904. &opt,
  7905. #endif
  7906. sizeof(opt));
  7907. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7908. ::listen(srv, 1);
  7909. sockaddr_in cli_addr{};
  7910. socklen_t cli_len = sizeof(cli_addr);
  7911. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7912. if (cli != INVALID_SOCKET) {
  7913. char buf[4096];
  7914. ::recv(cli, buf, sizeof(buf), 0);
  7915. auto content_length = std::to_string(DATA_SIZE);
  7916. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7917. "Content-Length: " +
  7918. content_length +
  7919. "\r\n"
  7920. "Connection: close\r\n"
  7921. "\r\n";
  7922. ::send(cli,
  7923. #ifdef _WIN32
  7924. static_cast<const char *>(response_header.c_str()),
  7925. static_cast<int>(response_header.size()),
  7926. #else
  7927. response_header.c_str(), response_header.size(),
  7928. #endif
  7929. 0);
  7930. std::string chunk(64 * 1024, 'A');
  7931. size_t total_sent = 0;
  7932. while (total_sent < DATA_SIZE) {
  7933. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7934. auto sent = ::send(cli,
  7935. #ifdef _WIN32
  7936. static_cast<const char *>(chunk.c_str()),
  7937. static_cast<int>(to_send),
  7938. #else
  7939. chunk.c_str(), to_send,
  7940. #endif
  7941. 0);
  7942. if (sent <= 0) break;
  7943. total_sent += static_cast<size_t>(sent);
  7944. }
  7945. detail::close_socket(cli);
  7946. }
  7947. detail::close_socket(srv);
  7948. });
  7949. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7950. size_t total_received = 0;
  7951. {
  7952. Client cli("127.0.0.1", PORT + 2);
  7953. cli.set_read_timeout(10, 0);
  7954. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7955. auto res =
  7956. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7957. total_received += data_length;
  7958. return true;
  7959. });
  7960. // Should fail because 200MB exceeds the explicit 150MB limit
  7961. EXPECT_FALSE(res);
  7962. }
  7963. server_thread.join();
  7964. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7965. << "Client with content_receiver should respect the explicit "
  7966. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7967. << total_received << " bytes.";
  7968. }
  7969. // Verify that an explicit set_payload_max_length larger than the response
  7970. // allows the content_receiver to read all data successfully.
  7971. TEST(ClientVulnerabilityTest,
  7972. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7973. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7974. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7975. #ifndef _WIN32
  7976. signal(SIGPIPE, SIG_IGN);
  7977. #endif
  7978. auto server_thread = std::thread([] {
  7979. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7980. default_socket_options(srv);
  7981. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7983. sockaddr_in addr{};
  7984. addr.sin_family = AF_INET;
  7985. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7986. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7987. int opt = 1;
  7988. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7989. #ifdef _WIN32
  7990. reinterpret_cast<const char *>(&opt),
  7991. #else
  7992. &opt,
  7993. #endif
  7994. sizeof(opt));
  7995. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7996. ::listen(srv, 1);
  7997. sockaddr_in cli_addr{};
  7998. socklen_t cli_len = sizeof(cli_addr);
  7999. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8000. if (cli != INVALID_SOCKET) {
  8001. char buf[4096];
  8002. ::recv(cli, buf, sizeof(buf), 0);
  8003. auto content_length = std::to_string(DATA_SIZE);
  8004. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8005. "Content-Length: " +
  8006. content_length +
  8007. "\r\n"
  8008. "Connection: close\r\n"
  8009. "\r\n";
  8010. ::send(cli,
  8011. #ifdef _WIN32
  8012. static_cast<const char *>(response_header.c_str()),
  8013. static_cast<int>(response_header.size()),
  8014. #else
  8015. response_header.c_str(), response_header.size(),
  8016. #endif
  8017. 0);
  8018. std::string chunk(64 * 1024, 'A');
  8019. size_t total_sent = 0;
  8020. while (total_sent < DATA_SIZE) {
  8021. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8022. auto sent = ::send(cli,
  8023. #ifdef _WIN32
  8024. static_cast<const char *>(chunk.c_str()),
  8025. static_cast<int>(to_send),
  8026. #else
  8027. chunk.c_str(), to_send,
  8028. #endif
  8029. 0);
  8030. if (sent <= 0) break;
  8031. total_sent += static_cast<size_t>(sent);
  8032. }
  8033. #ifdef _WIN32
  8034. ::shutdown(cli, SD_SEND);
  8035. #else
  8036. ::shutdown(cli, SHUT_WR);
  8037. #endif
  8038. char drain[1024];
  8039. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8040. detail::close_socket(cli);
  8041. }
  8042. detail::close_socket(srv);
  8043. });
  8044. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8045. size_t total_received = 0;
  8046. {
  8047. Client cli("127.0.0.1", PORT + 2);
  8048. cli.set_read_timeout(10, 0);
  8049. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8050. auto res =
  8051. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8052. total_received += data_length;
  8053. return true;
  8054. });
  8055. ASSERT_TRUE(res);
  8056. EXPECT_EQ(StatusCode::OK_200, res->status);
  8057. }
  8058. server_thread.join();
  8059. EXPECT_EQ(total_received, DATA_SIZE)
  8060. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8061. << " bytes (larger than " << DATA_SIZE
  8062. << " bytes response), content_receiver should read all data, but only "
  8063. "read "
  8064. << total_received << " bytes.";
  8065. }
  8066. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8067. // Regression test for "zip bomb" attack on the client side: a malicious server
  8068. // sends a small gzip-compressed response that decompresses to a huge payload.
  8069. // The client must enforce payload_max_length on the decompressed size.
  8070. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8071. constexpr size_t DECOMPRESSED_SIZE =
  8072. 10 * 1024 * 1024; // 10MB after decompression
  8073. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8074. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8075. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8076. std::string compressed;
  8077. {
  8078. httplib::detail::gzip_compressor compressor;
  8079. bool ok =
  8080. compressor.compress(uncompressed.data(), uncompressed.size(),
  8081. /*last=*/true, [&](const char *buf, size_t len) {
  8082. compressed.append(buf, len);
  8083. return true;
  8084. });
  8085. ASSERT_TRUE(ok);
  8086. }
  8087. // Sanity: compressed data should be much smaller than the decompressed size
  8088. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8089. #ifndef _WIN32
  8090. signal(SIGPIPE, SIG_IGN);
  8091. #endif
  8092. // Set up the listening socket in the main thread so the server is guaranteed
  8093. // to be ready before the client connects (eliminates race condition).
  8094. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8095. default_socket_options(srv);
  8096. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8097. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8098. sockaddr_in addr{};
  8099. addr.sin_family = AF_INET;
  8100. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8101. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8102. int opt = 1;
  8103. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8104. #ifdef _WIN32
  8105. reinterpret_cast<const char *>(&opt),
  8106. #else
  8107. &opt,
  8108. #endif
  8109. sizeof(opt));
  8110. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8111. ASSERT_EQ(0, ::listen(srv, 1));
  8112. auto server_thread = std::thread([&compressed, srv] {
  8113. sockaddr_in cli_addr{};
  8114. socklen_t cli_len = sizeof(cli_addr);
  8115. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8116. if (cli != INVALID_SOCKET) {
  8117. // Read the full HTTP request (until \r\n\r\n)
  8118. char buf[4096];
  8119. size_t total = 0;
  8120. while (total < sizeof(buf)) {
  8121. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8122. if (n <= 0) break;
  8123. total += static_cast<size_t>(n);
  8124. // Check for end of headers
  8125. if (total >= 4) {
  8126. std::string req(buf, total);
  8127. if (req.find("\r\n\r\n") != std::string::npos) break;
  8128. }
  8129. }
  8130. // Malicious response: gzip-compressed body, no Content-Length
  8131. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8132. "Content-Encoding: gzip\r\n"
  8133. "Connection: close\r\n"
  8134. "\r\n";
  8135. ::send(cli,
  8136. #ifdef _WIN32
  8137. static_cast<const char *>(response_header.c_str()),
  8138. static_cast<int>(response_header.size()),
  8139. #else
  8140. response_header.c_str(), response_header.size(),
  8141. #endif
  8142. 0);
  8143. // Send the compressed payload (small on the wire, huge when decompressed)
  8144. size_t total_sent = 0;
  8145. while (total_sent < compressed.size()) {
  8146. auto to_send = std::min(compressed.size() - total_sent,
  8147. static_cast<size_t>(64 * 1024));
  8148. auto sent =
  8149. ::send(cli,
  8150. #ifdef _WIN32
  8151. static_cast<const char *>(compressed.c_str() + total_sent),
  8152. static_cast<int>(to_send),
  8153. #else
  8154. compressed.c_str() + total_sent, to_send,
  8155. #endif
  8156. 0);
  8157. if (sent <= 0) break;
  8158. total_sent += static_cast<size_t>(sent);
  8159. }
  8160. detail::close_socket(cli);
  8161. }
  8162. });
  8163. auto se = detail::scope_exit([&] {
  8164. detail::close_socket(srv);
  8165. server_thread.join();
  8166. });
  8167. size_t total_decompressed = 0;
  8168. {
  8169. Client cli("127.0.0.1", PORT + 3);
  8170. cli.set_read_timeout(5, 0);
  8171. cli.set_decompress(true);
  8172. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8173. auto stream = cli.open_stream("GET", "/zipbomb");
  8174. ASSERT_TRUE(stream.is_valid());
  8175. char buffer[64 * 1024];
  8176. ssize_t n;
  8177. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8178. total_decompressed += static_cast<size_t>(n);
  8179. }
  8180. }
  8181. // The decompressed size must be capped by payload_max_length. Without
  8182. // protection, the client would decompress the full 10MB from a tiny
  8183. // compressed payload, enabling a zip bomb DoS attack.
  8184. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8185. << "Client decompressed " << total_decompressed
  8186. << " bytes from a gzip response. The decompressed size should be "
  8187. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8188. }
  8189. #endif
  8190. TEST(HostAndPortPropertiesTest, NoSSL) {
  8191. httplib::Client cli("www.google.com", 1234);
  8192. ASSERT_EQ("www.google.com", cli.host());
  8193. ASSERT_EQ(1234, cli.port());
  8194. }
  8195. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8196. httplib::Client cli("www.google.com:1234");
  8197. ASSERT_EQ("www.google.com", cli.host());
  8198. ASSERT_EQ(1234, cli.port());
  8199. }
  8200. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8201. // Port number that overflows int — should not crash, client becomes invalid
  8202. httplib::Client cli("http://www.google.com:99999999999999999999");
  8203. ASSERT_FALSE(cli.is_valid());
  8204. }
  8205. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8206. // Port 99999 exceeds valid range (1-65535) — should not crash
  8207. httplib::Client cli("http://www.google.com:99999");
  8208. ASSERT_FALSE(cli.is_valid());
  8209. }
  8210. #ifdef CPPHTTPLIB_SSL_ENABLED
  8211. TEST(HostAndPortPropertiesTest, SSL) {
  8212. httplib::SSLClient cli("www.google.com");
  8213. ASSERT_EQ("www.google.com", cli.host());
  8214. ASSERT_EQ(443, cli.port());
  8215. }
  8216. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8217. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8218. std::string cert;
  8219. read_file(CA_CERT_FILE, cert);
  8220. httplib::SSLClient httplib_client("www.google.com");
  8221. // Load CA store first time
  8222. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8223. // Load CA store second time (update)
  8224. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8225. // Verify client is still valid and can make connections
  8226. httplib_client.enable_server_certificate_verification(true);
  8227. auto res = httplib_client.Get("/");
  8228. ASSERT_TRUE(res);
  8229. // Google may return 200 or 301 depending on various factors
  8230. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8231. res->status == StatusCode::MovedPermanently_301);
  8232. }
  8233. TEST(SSLClientTest, ServerNameIndication_Online) {
  8234. auto host = "httpbingo.org";
  8235. auto path = std::string{"/get"};
  8236. SSLClient cli(host, 443);
  8237. auto res = cli.Get(path);
  8238. ASSERT_TRUE(res);
  8239. ASSERT_EQ(StatusCode::OK_200, res->status);
  8240. }
  8241. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8242. // Use a site that will cause SSL verification failure due to self-signed cert
  8243. SSLClient cli("self-signed.badssl.com", 443);
  8244. cli.enable_server_certificate_verification(true);
  8245. auto res = cli.Get("/");
  8246. ASSERT_TRUE(!res);
  8247. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8248. // Verify backend error is captured for SSLServerVerification
  8249. // This occurs when certificate verification fails
  8250. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8251. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8252. EXPECT_NE(0UL, res.ssl_backend_error());
  8253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8254. // For OpenSSL, ssl_error is 0 for verification errors
  8255. EXPECT_EQ(0, res.ssl_error());
  8256. #if !defined(_WIN32) || \
  8257. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8258. // On non-Windows or when Windows Schannel is disabled, the error comes
  8259. // from OpenSSL's verification
  8260. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8261. res.ssl_backend_error());
  8262. #endif
  8263. #endif
  8264. }
  8265. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8266. // Use a site where hostname doesn't match the certificate
  8267. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8268. SSLClient cli("wrong.host.badssl.com", 443);
  8269. cli.enable_server_certificate_verification(true);
  8270. cli.enable_server_hostname_verification(true);
  8271. auto res = cli.Get("/");
  8272. ASSERT_TRUE(!res);
  8273. // The error type depends on when hostname verification occurs:
  8274. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8275. // - Mbed TLS: SSLServerVerification (during handshake)
  8276. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8277. res.error() == Error::SSLServerVerification);
  8278. // Verify backend error is captured for hostname verification failure
  8279. EXPECT_NE(0UL, res.ssl_backend_error());
  8280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8281. // For OpenSSL, ssl_error is 0 for verification errors
  8282. EXPECT_EQ(0, res.ssl_error());
  8283. #if !defined(_WIN32) || \
  8284. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8285. // On non-Windows or when Windows Schannel is disabled, the error comes
  8286. // from OpenSSL's hostname verification
  8287. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8288. res.ssl_backend_error());
  8289. #endif
  8290. #endif
  8291. }
  8292. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8293. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8294. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8295. SSLClient cli("www.google.com", 443);
  8296. cli.enable_server_certificate_verification(true);
  8297. auto res = cli.Get("/");
  8298. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8299. }
  8300. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8301. SSLClient cli("www.google.com", 443);
  8302. cli.enable_server_certificate_verification(true);
  8303. cli.enable_windows_certificate_verification(false);
  8304. auto res = cli.Get("/");
  8305. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8306. }
  8307. #endif
  8308. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8309. Client cli("https://google.com");
  8310. auto res = cli.Get("/");
  8311. ASSERT_TRUE(res);
  8312. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8313. }
  8314. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8315. SSLClient cli("google.com");
  8316. cli.set_ca_cert_path(CA_CERT_FILE);
  8317. auto res = cli.Get("/");
  8318. ASSERT_TRUE(res);
  8319. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8320. }
  8321. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8322. SSLClient cli("google.com");
  8323. cli.enable_server_certificate_verification(true);
  8324. cli.set_ca_cert_path("hello");
  8325. auto res = cli.Get("/");
  8326. ASSERT_TRUE(!res);
  8327. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8328. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8329. // should be set
  8330. EXPECT_EQ(0, res.ssl_error());
  8331. // Verify backend error is captured for SSLLoadingCerts
  8332. // This error occurs when loading CA certificates fails
  8333. EXPECT_NE(0UL, res.ssl_backend_error());
  8334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8335. // OpenSSL specific error codes:
  8336. // > openssl errstr 0x80000002
  8337. // error:80000002:system library::No such file or directory
  8338. // > openssl errstr 0xA000126
  8339. // error:0A000126:SSL routines::unexpected eof while reading
  8340. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8341. res.ssl_backend_error() == 0xA000126);
  8342. #endif
  8343. }
  8344. TEST(SSLClientTest, ServerCertificateVerification4) {
  8345. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8346. ASSERT_TRUE(svr.is_valid());
  8347. svr.Get("/test", [&](const Request &, Response &res) {
  8348. res.set_content("test", "text/plain");
  8349. svr.stop();
  8350. ASSERT_TRUE(true);
  8351. });
  8352. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8353. auto se = detail::scope_exit([&] {
  8354. t.join();
  8355. ASSERT_FALSE(svr.is_running());
  8356. });
  8357. svr.wait_until_ready();
  8358. SSLClient cli("127.0.0.1", PORT);
  8359. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8360. cli.enable_server_certificate_verification(true);
  8361. cli.set_connection_timeout(30);
  8362. auto res = cli.Get("/test");
  8363. ASSERT_TRUE(res);
  8364. ASSERT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8367. std::string cert;
  8368. read_file(CA_CERT_FILE, cert);
  8369. SSLClient cli("google.com");
  8370. cli.load_ca_cert_store(cert.data(), cert.size());
  8371. const auto res = cli.Get("/");
  8372. ASSERT_TRUE(res);
  8373. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8374. }
  8375. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8376. // clang-format off
  8377. static constexpr char cert[] =
  8378. "GlobalSign Root CA\n"
  8379. "==================\n"
  8380. "-----BEGIN CERTIFICATE-----\n"
  8381. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8382. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8383. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8384. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8385. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8386. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8387. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8388. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8389. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8390. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8391. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8392. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8393. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8394. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8395. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8396. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8397. "-----END CERTIFICATE-----\n";
  8398. // clang-format on
  8399. SSLClient cli("google.com");
  8400. cli.load_ca_cert_store(cert, sizeof(cert));
  8401. const auto res = cli.Get("/");
  8402. ASSERT_TRUE(res);
  8403. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8404. }
  8405. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8406. SSLClient cli("www.youtube.com");
  8407. cli.set_ca_cert_path(CA_CERT_FILE);
  8408. cli.enable_server_certificate_verification(true);
  8409. cli.set_follow_location(true);
  8410. auto res = cli.Get("/");
  8411. ASSERT_TRUE(res);
  8412. ASSERT_EQ(StatusCode::OK_200, res->status);
  8413. }
  8414. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8415. SSLClient cli("wWw.YouTube.Com");
  8416. cli.set_ca_cert_path(CA_CERT_FILE);
  8417. cli.enable_server_certificate_verification(true);
  8418. cli.enable_server_hostname_verification(true);
  8419. cli.set_follow_location(true);
  8420. auto res = cli.Get("/");
  8421. ASSERT_TRUE(res);
  8422. ASSERT_EQ(StatusCode::OK_200, res->status);
  8423. }
  8424. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8425. SSLClient cli("gOoGlE.COm");
  8426. cli.enable_server_certificate_verification(true);
  8427. cli.enable_server_hostname_verification(true);
  8428. cli.set_follow_location(true);
  8429. auto res = cli.Get("/");
  8430. ASSERT_TRUE(res);
  8431. ASSERT_EQ(StatusCode::OK_200, res->status);
  8432. }
  8433. TEST(SSLClientTest, Issue2004_Online) {
  8434. Client client("https://google.com");
  8435. client.set_follow_location(true);
  8436. auto res = client.Get("/");
  8437. ASSERT_TRUE(res);
  8438. ASSERT_EQ(StatusCode::OK_200, res->status);
  8439. auto body = res->body;
  8440. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8441. }
  8442. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8443. // Create SSLClient with invalid cert/key to make is_valid() return false
  8444. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8445. "nonexistent_key.pem");
  8446. // is_valid() should be false due to cert loading failure
  8447. ASSERT_FALSE(cli.is_valid());
  8448. auto res = cli.Get("/");
  8449. ASSERT_FALSE(res);
  8450. EXPECT_EQ(Error::SSLConnection, res.error());
  8451. }
  8452. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8453. // Test for Issue #2251: SSL error not properly reported when client cert
  8454. // and key paths are swapped or mismatched
  8455. // This simulates the scenario where user accidentally swaps the cert and key
  8456. // files
  8457. // Using client cert file as private key and vice versa (completely wrong)
  8458. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8459. // Should fail validation due to cert/key mismatch
  8460. ASSERT_FALSE(cli.is_valid());
  8461. // Attempt to make a request should fail with proper error
  8462. auto res = cli.Get("/");
  8463. ASSERT_FALSE(res);
  8464. EXPECT_EQ(Error::SSLConnection, res.error());
  8465. // SSL error should be recorded in the Result object (this is the key fix for
  8466. // Issue #2251)
  8467. auto backend_error = res.ssl_backend_error();
  8468. EXPECT_NE(0u, backend_error);
  8469. }
  8470. // Tests cert/key mismatch detection at the TLS context level
  8471. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8472. // Test that using mismatched cert/key causes connection failure.
  8473. // We verify this at the SSLClient level rather than through internal
  8474. // TLS API functions.
  8475. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8476. cli.enable_server_certificate_verification(false);
  8477. cli.set_connection_timeout(2);
  8478. // The mismatch should cause a connection or handshake error
  8479. auto res = cli.Get("/test");
  8480. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8481. // Either way, the request should fail
  8482. EXPECT_FALSE(res);
  8483. }
  8484. #endif
  8485. #if 0
  8486. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8487. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8488. ASSERT_TRUE(cli != nullptr);
  8489. cli->set_address_family(AF_INET6);
  8490. cli->set_interface("en0");
  8491. auto res = cli->Get("/get");
  8492. ASSERT_TRUE(res);
  8493. ASSERT_EQ(StatusCode::OK_200, res->status);
  8494. }
  8495. #endif
  8496. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8497. #ifdef CPPHTTPLIB_SSL_ENABLED
  8498. void ClientCertPresent(
  8499. const std::string &client_cert_file,
  8500. const std::string &client_private_key_file,
  8501. const std::string &client_encrypted_private_key_pass = std::string()) {
  8502. using namespace httplib::tls;
  8503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8504. CLIENT_CA_CERT_DIR);
  8505. ASSERT_TRUE(svr.is_valid());
  8506. svr.Get("/test", [&](const Request &req, Response &res) {
  8507. res.set_content("test", "text/plain");
  8508. auto cert = req.peer_cert();
  8509. ASSERT_TRUE(static_cast<bool>(cert));
  8510. std::string common_name = cert.subject_cn();
  8511. EXPECT_EQ("Common Name", common_name);
  8512. });
  8513. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8514. auto se = detail::scope_exit([&] {
  8515. svr.stop();
  8516. t.join();
  8517. ASSERT_FALSE(svr.is_running());
  8518. });
  8519. svr.wait_until_ready();
  8520. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8521. client_encrypted_private_key_pass);
  8522. cli.enable_server_certificate_verification(false);
  8523. cli.set_connection_timeout(30);
  8524. auto res = cli.Get("/test");
  8525. ASSERT_TRUE(res);
  8526. ASSERT_EQ(StatusCode::OK_200, res->status);
  8527. }
  8528. TEST(SSLClientServerTest, ClientCertPresent) {
  8529. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8530. }
  8531. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8532. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8533. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8534. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8535. }
  8536. // PEM memory-based constructor tests (works with all TLS backends)
  8537. void PemMemoryClientCertPresent(
  8538. const std::string &client_cert_file,
  8539. const std::string &client_private_key_file,
  8540. const std::string &client_encrypted_private_key_pass = std::string()) {
  8541. // Read PEM files into memory
  8542. std::string server_cert_pem, server_key_pem;
  8543. std::string client_ca_pem;
  8544. std::string client_cert_pem, client_key_pem;
  8545. read_file(SERVER_CERT_FILE, server_cert_pem);
  8546. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8547. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8548. read_file(client_cert_file, client_cert_pem);
  8549. read_file(client_private_key_file, client_key_pem);
  8550. // Create server with PEM memory
  8551. SSLServer::PemMemory server_pem = {
  8552. server_cert_pem.c_str(),
  8553. server_cert_pem.size(),
  8554. server_key_pem.c_str(),
  8555. server_key_pem.size(),
  8556. client_ca_pem.c_str(),
  8557. client_ca_pem.size(),
  8558. nullptr // no password for server key
  8559. };
  8560. SSLServer svr(server_pem);
  8561. ASSERT_TRUE(svr.is_valid());
  8562. svr.Get("/test", [&](const Request &, Response &res) {
  8563. res.set_content("test", "text/plain");
  8564. });
  8565. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8566. auto se = detail::scope_exit([&] {
  8567. svr.stop();
  8568. t.join();
  8569. ASSERT_FALSE(svr.is_running());
  8570. });
  8571. svr.wait_until_ready();
  8572. // Create client with PEM memory
  8573. const char *password = client_encrypted_private_key_pass.empty()
  8574. ? nullptr
  8575. : client_encrypted_private_key_pass.c_str();
  8576. SSLClient::PemMemory client_pem = {
  8577. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8578. client_key_pem.size(), password};
  8579. SSLClient cli(HOST, PORT, client_pem);
  8580. cli.enable_server_certificate_verification(false);
  8581. cli.set_connection_timeout(30);
  8582. auto res = cli.Get("/test");
  8583. ASSERT_TRUE(res);
  8584. ASSERT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8587. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8588. }
  8589. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8590. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8591. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8592. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8593. }
  8594. TEST(SSLClientServerTest, ClientCertMissing) {
  8595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8596. CLIENT_CA_CERT_DIR);
  8597. ASSERT_TRUE(svr.is_valid());
  8598. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8600. auto se = detail::scope_exit([&] {
  8601. svr.stop();
  8602. t.join();
  8603. ASSERT_FALSE(svr.is_running());
  8604. });
  8605. svr.wait_until_ready();
  8606. SSLClient cli(HOST, PORT);
  8607. cli.set_connection_timeout(30);
  8608. auto res = cli.Get("/test");
  8609. ASSERT_TRUE(!res);
  8610. // When client cert is missing and server requires it, connection fails
  8611. // Error type depends on backend implementation
  8612. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8613. res.error() == Error::SSLConnection);
  8614. // Verify backend error is captured
  8615. // Note: This test may have different error codes depending on the exact
  8616. // verification failure
  8617. EXPECT_NE(0UL, res.ssl_backend_error());
  8618. }
  8619. TEST(SSLClientServerTest, TrustDirOptional) {
  8620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8621. ASSERT_TRUE(svr.is_valid());
  8622. svr.Get("/test", [&](const Request &, Response &res) {
  8623. res.set_content("test", "text/plain");
  8624. });
  8625. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8626. auto se = detail::scope_exit([&] {
  8627. svr.stop();
  8628. t.join();
  8629. ASSERT_FALSE(svr.is_running());
  8630. });
  8631. svr.wait_until_ready();
  8632. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8633. cli.enable_server_certificate_verification(false);
  8634. cli.set_connection_timeout(30);
  8635. auto res = cli.Get("/test");
  8636. ASSERT_TRUE(res);
  8637. ASSERT_EQ(StatusCode::OK_200, res->status);
  8638. }
  8639. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8640. class NoListenSSLServer : public SSLServer {
  8641. public:
  8642. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8643. const char *client_ca_cert_file_path,
  8644. const char *client_ca_cert_dir_path = nullptr)
  8645. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8646. client_ca_cert_dir_path),
  8647. stop_(false) {}
  8648. std::atomic_bool stop_;
  8649. private:
  8650. bool process_and_close_socket(socket_t /*sock*/) override {
  8651. // Don't create SSL context
  8652. while (!stop_.load()) {
  8653. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8654. }
  8655. return true;
  8656. }
  8657. };
  8658. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8659. CLIENT_CA_CERT_FILE);
  8660. ASSERT_TRUE(svr.is_valid());
  8661. svr.Get("/test", [&](const Request &, Response &res) {
  8662. res.set_content("test", "text/plain");
  8663. });
  8664. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8665. auto se = detail::scope_exit([&] {
  8666. svr.stop_ = true;
  8667. svr.stop();
  8668. t.join();
  8669. ASSERT_FALSE(svr.is_running());
  8670. });
  8671. svr.wait_until_ready();
  8672. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8673. cli.enable_server_certificate_verification(false);
  8674. cli.set_connection_timeout(1);
  8675. auto res = cli.Get("/test");
  8676. ASSERT_TRUE(!res);
  8677. EXPECT_EQ(Error::SSLConnection, res.error());
  8678. // Timeout results in WantRead error code (maps to backend-specific value)
  8679. EXPECT_NE(0, res.ssl_error());
  8680. }
  8681. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8682. // Test SSLServer with client certificate verification using the standard
  8683. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8685. CLIENT_CA_CERT_DIR);
  8686. ASSERT_TRUE(svr.is_valid());
  8687. svr.Get("/test", [&](const Request &req, Response &res) {
  8688. res.set_content("test", "text/plain");
  8689. auto cert = req.peer_cert();
  8690. ASSERT_TRUE(static_cast<bool>(cert));
  8691. auto common_name = cert.subject_cn();
  8692. EXPECT_EQ("Common Name", common_name);
  8693. });
  8694. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8695. auto se = detail::scope_exit([&] {
  8696. svr.stop();
  8697. t.join();
  8698. ASSERT_FALSE(svr.is_running());
  8699. });
  8700. svr.wait_until_ready();
  8701. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8702. cli.enable_server_certificate_verification(false);
  8703. cli.set_connection_timeout(30);
  8704. auto res = cli.Get("/test");
  8705. ASSERT_TRUE(res);
  8706. ASSERT_EQ(StatusCode::OK_200, res->status);
  8707. }
  8708. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8709. // Verifies that wildcard matching and exact matching work consistently
  8710. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8711. using namespace httplib::tls;
  8712. // We need a running server to test against
  8713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8714. ASSERT_TRUE(svr.is_valid());
  8715. svr.Get("/test", [](const Request &, Response &res) {
  8716. res.set_content("ok", "text/plain");
  8717. });
  8718. thread t([&]() { svr.listen(HOST, PORT); });
  8719. auto se = detail::scope_exit([&] {
  8720. svr.stop();
  8721. t.join();
  8722. });
  8723. svr.wait_until_ready();
  8724. bool verify_callback_called = false;
  8725. bool verify_result_wrong = false;
  8726. SSLClient cli(HOST, PORT);
  8727. cli.enable_server_certificate_verification(true);
  8728. cli.set_ca_cert_path(CA_CERT_FILE);
  8729. cli.set_connection_timeout(5);
  8730. // Note: Test certificate has CN="Common Name", not "localhost"
  8731. bool verify_result_cn = false;
  8732. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8733. verify_callback_called = true;
  8734. if (!ctx.cert) return false;
  8735. // Test 1: "Common Name" should match (our test server cert CN)
  8736. verify_result_cn = ctx.check_hostname("Common Name");
  8737. // Test 2: wrong hostname should not match
  8738. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8739. return true; // Accept for the purpose of this test
  8740. });
  8741. auto res = cli.Get("/test");
  8742. // The request may succeed or fail depending on cert configuration
  8743. // but the callback should have been called
  8744. ASSERT_TRUE(verify_callback_called)
  8745. << "Verify callback should have been called";
  8746. // CN="Common Name" should match our test certificate
  8747. EXPECT_TRUE(verify_result_cn)
  8748. << "verify_hostname should match 'Common Name' (certificate CN)";
  8749. // Wrong hostname should not match
  8750. EXPECT_FALSE(verify_result_wrong)
  8751. << "verify_hostname should not match 'wronghost.example.com'";
  8752. }
  8753. #endif
  8754. // mbedTLS-specific callback constructor test
  8755. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8756. #ifdef CPPHTTPLIB_SSL_ENABLED
  8757. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8759. ASSERT_TRUE(svr.is_valid());
  8760. // Set up a handler to verify client certificate is present
  8761. bool client_cert_verified = false;
  8762. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8763. // Verify that client certificate was provided
  8764. client_cert_verified = true;
  8765. res.set_content("success", "text/plain");
  8766. });
  8767. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8768. auto se = detail::scope_exit([&] {
  8769. svr.stop();
  8770. t.join();
  8771. ASSERT_FALSE(svr.is_running());
  8772. });
  8773. svr.wait_until_ready();
  8774. // Client with certificate
  8775. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8776. cli.enable_server_certificate_verification(false);
  8777. cli.set_connection_timeout(30);
  8778. auto res = cli.Get("/test");
  8779. ASSERT_TRUE(res);
  8780. ASSERT_EQ(StatusCode::OK_200, res->status);
  8781. ASSERT_TRUE(client_cert_verified);
  8782. EXPECT_EQ("success", res->body);
  8783. }
  8784. #endif
  8785. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8786. // backends
  8787. #ifdef CPPHTTPLIB_SSL_ENABLED
  8788. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8789. using namespace httplib::tls;
  8790. // Test that when client CA cert file is provided,
  8791. // the server properly requests and validates client certificates
  8792. // Create a server with client authentication
  8793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8794. ASSERT_TRUE(svr.is_valid());
  8795. bool handler_called = false;
  8796. svr.Get("/test", [&](const Request &req, Response &res) {
  8797. handler_called = true;
  8798. // Verify that a client certificate was provided
  8799. auto cert = req.peer_cert();
  8800. ASSERT_TRUE(static_cast<bool>(cert));
  8801. // Get the issuer name
  8802. std::string issuer_str = cert.issuer_name();
  8803. ASSERT_FALSE(issuer_str.empty());
  8804. // The client certificate should be issued by our test CA
  8805. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8806. res.set_content("authenticated", "text/plain");
  8807. });
  8808. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8809. auto se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. t.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. // Connect with a client certificate issued by the CA
  8816. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8817. cli.enable_server_certificate_verification(false);
  8818. cli.set_connection_timeout(30);
  8819. auto res = cli.Get("/test");
  8820. ASSERT_TRUE(res);
  8821. ASSERT_EQ(StatusCode::OK_200, res->status);
  8822. ASSERT_TRUE(handler_called);
  8823. EXPECT_EQ("authenticated", res->body);
  8824. }
  8825. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8826. using namespace httplib::tls;
  8827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8828. ASSERT_TRUE(svr.is_valid());
  8829. svr.Get("/test", [](const Request &, Response &res) {
  8830. res.set_content("ok", "text/plain");
  8831. });
  8832. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8833. auto se = detail::scope_exit([&] {
  8834. svr.stop();
  8835. t.join();
  8836. });
  8837. svr.wait_until_ready();
  8838. SSLClient cli(HOST, PORT);
  8839. cli.enable_server_certificate_verification(false);
  8840. cli.set_connection_timeout(30);
  8841. bool cert_checked = false;
  8842. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8843. if (ctx.cert) {
  8844. auto sans = ctx.sans();
  8845. // Test certificate may or may not have SANs - just verify the API
  8846. // works If SANs exist, verify the types are valid
  8847. for (const auto &san : sans) {
  8848. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8849. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8850. san.type == SanType::OTHER);
  8851. EXPECT_FALSE(san.value.empty());
  8852. }
  8853. cert_checked = true;
  8854. }
  8855. return true;
  8856. });
  8857. auto res = cli.Get("/test");
  8858. ASSERT_TRUE(res);
  8859. EXPECT_TRUE(cert_checked);
  8860. }
  8861. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8862. using namespace httplib::tls;
  8863. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8864. ASSERT_TRUE(svr.is_valid());
  8865. svr.Get("/test", [](const Request &, Response &res) {
  8866. res.set_content("ok", "text/plain");
  8867. });
  8868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8869. auto se = detail::scope_exit([&] {
  8870. svr.stop();
  8871. t.join();
  8872. });
  8873. svr.wait_until_ready();
  8874. SSLClient cli(HOST, PORT);
  8875. cli.enable_server_certificate_verification(false);
  8876. cli.set_connection_timeout(30);
  8877. bool validity_checked = false;
  8878. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8879. if (ctx.cert) {
  8880. time_t not_before = 0, not_after = 0;
  8881. bool result = ctx.validity(not_before, not_after);
  8882. EXPECT_TRUE(result);
  8883. // Verify that not_before < now < not_after for a valid cert
  8884. time_t now = time(nullptr);
  8885. EXPECT_LT(not_before, now);
  8886. EXPECT_GT(not_after, now);
  8887. validity_checked = true;
  8888. }
  8889. return true;
  8890. });
  8891. auto res = cli.Get("/test");
  8892. ASSERT_TRUE(res);
  8893. EXPECT_TRUE(validity_checked);
  8894. }
  8895. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8896. using namespace httplib::tls;
  8897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8898. ASSERT_TRUE(svr.is_valid());
  8899. svr.Get("/test", [](const Request &, Response &res) {
  8900. res.set_content("ok", "text/plain");
  8901. });
  8902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. });
  8907. svr.wait_until_ready();
  8908. SSLClient cli(HOST, PORT);
  8909. cli.enable_server_certificate_verification(false);
  8910. cli.set_connection_timeout(30);
  8911. bool serial_checked = false;
  8912. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8913. if (ctx.cert) {
  8914. std::string serial = ctx.serial();
  8915. EXPECT_FALSE(serial.empty());
  8916. // Serial should be a hex string
  8917. for (char c : serial) {
  8918. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8919. (c >= 'a' && c <= 'f'));
  8920. }
  8921. serial_checked = true;
  8922. }
  8923. return true;
  8924. });
  8925. auto res = cli.Get("/test");
  8926. ASSERT_TRUE(res);
  8927. EXPECT_TRUE(serial_checked);
  8928. }
  8929. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8930. // Test 1: Valid CA file - no error should be recorded
  8931. {
  8932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8933. CLIENT_CA_CERT_FILE);
  8934. ASSERT_TRUE(svr.is_valid());
  8935. // With valid setup, last_ssl_error should be 0
  8936. EXPECT_EQ(0, svr.ssl_last_error());
  8937. }
  8938. // Test 2: Invalid CA file content
  8939. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8940. {
  8941. // Create a temporary file with completely invalid content
  8942. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8943. {
  8944. std::ofstream ofs(temp_invalid_ca);
  8945. ofs << "This is not a certificate file at all\n";
  8946. ofs << "Just plain text content\n";
  8947. }
  8948. // Create server with invalid CA file
  8949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8950. // Clean up temporary file
  8951. std::remove(temp_invalid_ca);
  8952. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8953. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8954. // Note: SSL_CTX_load_verify_locations typically fails first,
  8955. // but our error handling code path is still exercised
  8956. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8957. }
  8958. }
  8959. TEST(VerifyCallbackTest, VerifyContextFields) {
  8960. using namespace httplib::tls;
  8961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8962. ASSERT_TRUE(svr.is_valid());
  8963. svr.Get("/test", [](const Request &, Response &res) {
  8964. res.set_content("ok", "text/plain");
  8965. });
  8966. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8967. auto se = detail::scope_exit([&] {
  8968. svr.stop();
  8969. t.join();
  8970. });
  8971. svr.wait_until_ready();
  8972. SSLClient cli(HOST, PORT);
  8973. cli.enable_server_certificate_verification(false);
  8974. cli.set_connection_timeout(30);
  8975. int callback_count = 0;
  8976. bool saw_leaf_cert = false;
  8977. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8978. if (ctx.cert) {
  8979. callback_count++;
  8980. // We should see at least one certificate (the leaf)
  8981. std::string cn = ctx.subject_cn();
  8982. if (!cn.empty()) { saw_leaf_cert = true; }
  8983. // Verify context fields are populated
  8984. EXPECT_NE(ctx.session, nullptr);
  8985. EXPECT_GE(ctx.depth, 0);
  8986. }
  8987. return true;
  8988. });
  8989. auto res = cli.Get("/test");
  8990. ASSERT_TRUE(res);
  8991. EXPECT_GT(callback_count, 0);
  8992. EXPECT_TRUE(saw_leaf_cert);
  8993. }
  8994. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8995. using httplib::tls::TlsError;
  8996. // Test that verify_error_to_string returns empty for success
  8997. std::string success_str = TlsError::verify_error_to_string(0);
  8998. EXPECT_TRUE(success_str.empty());
  8999. // Test that verify_error_to_string returns non-empty for error codes
  9000. // Using a common error code (certificate expired)
  9001. std::string error_str =
  9002. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9003. EXPECT_FALSE(error_str.empty());
  9004. }
  9005. TEST(SessionVerifierTest, CertificateAccepted) {
  9006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9007. ASSERT_TRUE(svr.is_valid());
  9008. svr.Get("/test", [](const Request &, Response &res) {
  9009. res.set_content("ok", "text/plain");
  9010. });
  9011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9012. auto se = detail::scope_exit([&] {
  9013. svr.stop();
  9014. t.join();
  9015. });
  9016. svr.wait_until_ready();
  9017. SSLClient cli(HOST, PORT);
  9018. cli.enable_server_certificate_verification(false);
  9019. cli.set_connection_timeout(30);
  9020. bool callback_called = false;
  9021. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9022. EXPECT_NE(session, nullptr);
  9023. callback_called = true;
  9024. return SSLVerifierResponse::CertificateAccepted;
  9025. });
  9026. auto res = cli.Get("/test");
  9027. ASSERT_TRUE(res);
  9028. EXPECT_EQ(200, res->status);
  9029. EXPECT_TRUE(callback_called);
  9030. }
  9031. TEST(SessionVerifierTest, CertificateRejected) {
  9032. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9033. ASSERT_TRUE(svr.is_valid());
  9034. svr.Get("/test", [](const Request &, Response &res) {
  9035. res.set_content("ok", "text/plain");
  9036. });
  9037. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9038. auto se = detail::scope_exit([&] {
  9039. svr.stop();
  9040. t.join();
  9041. });
  9042. svr.wait_until_ready();
  9043. SSLClient cli(HOST, PORT);
  9044. cli.enable_server_certificate_verification(false);
  9045. cli.set_connection_timeout(30);
  9046. bool callback_called = false;
  9047. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9048. EXPECT_NE(session, nullptr);
  9049. callback_called = true;
  9050. return SSLVerifierResponse::CertificateRejected;
  9051. });
  9052. auto res = cli.Get("/test");
  9053. EXPECT_FALSE(res);
  9054. EXPECT_TRUE(callback_called);
  9055. }
  9056. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9058. ASSERT_TRUE(svr.is_valid());
  9059. svr.Get("/test", [](const Request &, Response &res) {
  9060. res.set_content("ok", "text/plain");
  9061. });
  9062. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9063. auto se = detail::scope_exit([&] {
  9064. svr.stop();
  9065. t.join();
  9066. });
  9067. svr.wait_until_ready();
  9068. // NoDecisionMade with verification disabled should succeed (no default check)
  9069. SSLClient cli(HOST, PORT);
  9070. cli.enable_server_certificate_verification(false);
  9071. cli.set_connection_timeout(30);
  9072. bool callback_called = false;
  9073. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9074. EXPECT_NE(session, nullptr);
  9075. callback_called = true;
  9076. return SSLVerifierResponse::NoDecisionMade;
  9077. });
  9078. auto res = cli.Get("/test");
  9079. ASSERT_TRUE(res);
  9080. EXPECT_EQ(200, res->status);
  9081. EXPECT_TRUE(callback_called);
  9082. }
  9083. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9085. ASSERT_TRUE(svr.is_valid());
  9086. svr.Get("/test", [](const Request &, Response &res) {
  9087. res.set_content("ok", "text/plain");
  9088. });
  9089. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9090. auto se = detail::scope_exit([&] {
  9091. svr.stop();
  9092. t.join();
  9093. });
  9094. svr.wait_until_ready();
  9095. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9096. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9097. // so we only check that the request fails, not whether the callback was
  9098. // called.
  9099. SSLClient cli(HOST, PORT);
  9100. cli.enable_server_certificate_verification(true);
  9101. cli.set_connection_timeout(30);
  9102. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9103. EXPECT_NE(session, nullptr);
  9104. return SSLVerifierResponse::NoDecisionMade;
  9105. });
  9106. auto res = cli.Get("/test");
  9107. EXPECT_FALSE(res);
  9108. }
  9109. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9110. // Test SSL server using PemMemory constructor with client CA certificates
  9111. // Read PEM files
  9112. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9113. read_file(SERVER_CERT_FILE, server_cert_pem);
  9114. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9115. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9116. // Create SSLServer with PemMemory constructor including client CA
  9117. SSLServer::PemMemory server_pem = {
  9118. server_cert_pem.c_str(),
  9119. server_cert_pem.size(),
  9120. server_key_pem.c_str(),
  9121. server_key_pem.size(),
  9122. client_ca_pem.c_str(),
  9123. client_ca_pem.size(),
  9124. nullptr // no password for server key
  9125. };
  9126. SSLServer svr(server_pem);
  9127. ASSERT_TRUE(svr.is_valid());
  9128. // No SSL error should be recorded for valid setup
  9129. EXPECT_EQ(0, svr.ssl_last_error());
  9130. // Set up server endpoints
  9131. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9132. res.set_content("ok", "text/plain");
  9133. });
  9134. // Start server in a thread
  9135. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9136. svr.wait_until_ready();
  9137. // Connect with client certificate (using constructor with paths)
  9138. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9139. cli.enable_server_certificate_verification(false);
  9140. auto res = cli.Get("/test-pem-ca");
  9141. ASSERT_TRUE(res);
  9142. EXPECT_EQ(200, res->status);
  9143. EXPECT_EQ("ok", res->body);
  9144. svr.stop();
  9145. server_thread.join();
  9146. }
  9147. #endif
  9148. #ifdef _WIN32
  9149. TEST(CleanupTest, WSACleanup) {
  9150. int ret = WSACleanup();
  9151. ASSERT_EQ(0, ret);
  9152. }
  9153. #endif
  9154. #ifndef CPPHTTPLIB_SSL_ENABLED
  9155. TEST(NoSSLSupport, SimpleInterface) {
  9156. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9157. }
  9158. #endif
  9159. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9160. TEST(InvalidScheme, SimpleInterface) {
  9161. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9162. }
  9163. #endif
  9164. TEST(NoScheme, SimpleInterface) {
  9165. Client cli("yahoo.com:80");
  9166. ASSERT_TRUE(cli.is_valid());
  9167. }
  9168. TEST(SendAPI, SimpleInterface_Online) {
  9169. Client cli("http://yahoo.com");
  9170. Request req;
  9171. req.method = "GET";
  9172. req.path = "/";
  9173. auto res = cli.send(req);
  9174. ASSERT_TRUE(res);
  9175. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9176. }
  9177. TEST(SendAPI, WithParamsInRequest) {
  9178. Server svr;
  9179. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9180. EXPECT_TRUE(req.has_param("test"));
  9181. EXPECT_EQ("test_value", req.get_param_value("test"));
  9182. });
  9183. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9184. auto se = detail::scope_exit([&] {
  9185. svr.stop();
  9186. t.join();
  9187. ASSERT_FALSE(svr.is_running());
  9188. });
  9189. svr.wait_until_ready();
  9190. Client cli(HOST, PORT);
  9191. {
  9192. Request req;
  9193. req.method = "GET";
  9194. req.path = "/";
  9195. req.params.emplace("test", "test_value");
  9196. auto res = cli.send(req);
  9197. ASSERT_TRUE(res);
  9198. }
  9199. {
  9200. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9201. ASSERT_TRUE(res);
  9202. }
  9203. }
  9204. TEST(ClientImplMethods, GetSocketTest) {
  9205. httplib::Server svr;
  9206. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9207. res.status = StatusCode::OK_200;
  9208. });
  9209. auto port = svr.bind_to_any_port("127.0.0.1");
  9210. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9211. auto se = detail::scope_exit([&] {
  9212. svr.stop();
  9213. thread.join();
  9214. ASSERT_FALSE(svr.is_running());
  9215. });
  9216. svr.wait_until_ready();
  9217. {
  9218. httplib::Client cli("127.0.0.1", port);
  9219. cli.set_keep_alive(true);
  9220. // Use the behavior of cpp-httplib of opening the connection
  9221. // only when the first request happens. If that changes,
  9222. // this test would be obsolete.
  9223. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9224. // This also implicitly tests the server. But other tests would fail much
  9225. // earlier than this one to be considered.
  9226. auto res = cli.Get("/");
  9227. ASSERT_TRUE(res);
  9228. EXPECT_EQ(StatusCode::OK_200, res->status);
  9229. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9230. }
  9231. }
  9232. #ifdef CPPHTTPLIB_SSL_ENABLED
  9233. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9234. Client cli("http://yahoo.com");
  9235. auto res = cli.Get("/");
  9236. ASSERT_TRUE(res);
  9237. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9238. cli.set_follow_location(true);
  9239. res = cli.Get("/");
  9240. ASSERT_TRUE(res);
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9243. }
  9244. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9245. Client cli("https://yahoo.com");
  9246. auto res = cli.Get("/");
  9247. ASSERT_TRUE(res);
  9248. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9249. cli.set_follow_location(true);
  9250. res = cli.Get("/");
  9251. ASSERT_TRUE(res);
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9254. }
  9255. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9256. Client cli("https://yahoo.com");
  9257. auto res = cli.Get("/");
  9258. ASSERT_TRUE(res);
  9259. ASSERT_FALSE(!res);
  9260. ASSERT_TRUE(res);
  9261. ASSERT_FALSE(res == nullptr);
  9262. ASSERT_TRUE(res != nullptr);
  9263. EXPECT_EQ(Error::Success, res.error());
  9264. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9265. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9266. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9267. cli.set_follow_location(true);
  9268. res = cli.Get("/");
  9269. ASSERT_TRUE(res);
  9270. EXPECT_EQ(Error::Success, res.error());
  9271. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9272. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9273. EXPECT_EQ(StatusCode::OK_200, res->status);
  9274. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9275. }
  9276. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9277. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9278. Client cli("https://cdnjs.cloudflare.com");
  9279. auto res =
  9280. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9281. ASSERT_TRUE(res);
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. EXPECT_EQ(287630U, res->body.size());
  9284. EXPECT_EQ("application/javascript; charset=utf-8",
  9285. res->get_header_value("Content-Type"));
  9286. }
  9287. #endif
  9288. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9289. #undef REDIR_HOST // Silence compiler warning
  9290. #define REDIR_HOST "https://httpbingo.org"
  9291. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9292. Client cli(REDIR_HOST);
  9293. cli.set_follow_location(true);
  9294. auto res =
  9295. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9296. ASSERT_TRUE(res);
  9297. EXPECT_EQ(StatusCode::OK_200, res->status);
  9298. }
  9299. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9300. Client cli(REDIR_HOST);
  9301. cli.set_follow_location(true);
  9302. Params params;
  9303. params.emplace("url", "http://example.com");
  9304. params.emplace("status_code", "302");
  9305. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9306. ASSERT_TRUE(res);
  9307. EXPECT_EQ(StatusCode::OK_200, res->status);
  9308. }
  9309. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9310. Client cli(REDIR_HOST);
  9311. cli.set_follow_location(true);
  9312. Params params;
  9313. params.emplace("url", "http://example.com");
  9314. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9315. ASSERT_TRUE(res);
  9316. EXPECT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST(HttpToHttpsRedirectTest, CertFile) {
  9319. auto ssl_port = PORT + 1;
  9320. Server svr;
  9321. ASSERT_TRUE(svr.is_valid());
  9322. svr.Get("/index", [&](const Request &, Response &res) {
  9323. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9324. "/index");
  9325. svr.stop();
  9326. });
  9327. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9328. ASSERT_TRUE(ssl_svr.is_valid());
  9329. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9330. res.set_content("test", "text/plain");
  9331. ssl_svr.stop();
  9332. });
  9333. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9334. thread t2 =
  9335. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9336. auto se = detail::scope_exit([&] {
  9337. t2.join();
  9338. t.join();
  9339. ASSERT_FALSE(svr.is_running());
  9340. });
  9341. svr.wait_until_ready();
  9342. ssl_svr.wait_until_ready();
  9343. Client cli("127.0.0.1", PORT);
  9344. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9345. cli.enable_server_certificate_verification(true);
  9346. cli.set_follow_location(true);
  9347. cli.set_connection_timeout(30);
  9348. auto res = cli.Get("/index");
  9349. ASSERT_TRUE(res);
  9350. ASSERT_EQ(StatusCode::OK_200, res->status);
  9351. }
  9352. TEST(SSLClientRedirectTest, CertFile) {
  9353. auto ssl_port = PORT + 1;
  9354. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9355. ASSERT_TRUE(ssl_svr1.is_valid());
  9356. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9357. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9358. "/index");
  9359. ssl_svr1.stop();
  9360. });
  9361. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9362. ASSERT_TRUE(ssl_svr2.is_valid());
  9363. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9364. res.set_content("test", "text/plain");
  9365. ssl_svr2.stop();
  9366. });
  9367. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9368. thread t2 =
  9369. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9370. auto se = detail::scope_exit([&] {
  9371. t2.join();
  9372. t.join();
  9373. ASSERT_FALSE(ssl_svr1.is_running());
  9374. });
  9375. ssl_svr1.wait_until_ready();
  9376. ssl_svr2.wait_until_ready();
  9377. SSLClient cli("127.0.0.1", PORT);
  9378. std::string cert;
  9379. read_file(SERVER_CERT2_FILE, cert);
  9380. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9381. cli.enable_server_certificate_verification(true);
  9382. cli.set_follow_location(true);
  9383. cli.set_connection_timeout(30);
  9384. auto res = cli.Get("/index");
  9385. ASSERT_TRUE(res);
  9386. ASSERT_EQ(StatusCode::OK_200, res->status);
  9387. }
  9388. #endif
  9389. #ifdef CPPHTTPLIB_SSL_ENABLED
  9390. // Test that set_ca_cert_store() skips system certs (consistent with
  9391. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9392. // should be trusted - system certs should NOT be loaded.
  9393. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9394. // Load a specific cert that is NOT a system CA cert
  9395. std::string cert;
  9396. read_file(SERVER_CERT2_FILE, cert);
  9397. SSLClient cli("google.com");
  9398. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9399. cli.enable_server_certificate_verification(true);
  9400. // This should FAIL because:
  9401. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9402. // 2. System certs should NOT be loaded when custom store is set
  9403. // If system certs WERE loaded, this would succeed
  9404. auto res = cli.Get("/");
  9405. ASSERT_FALSE(res);
  9406. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9407. }
  9408. TEST(MultipartFormDataTest, LargeData) {
  9409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9410. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9411. const ContentReader &content_reader) {
  9412. if (req.is_multipart_form_data()) {
  9413. std::vector<FormData> items;
  9414. content_reader(
  9415. [&](const FormData &file) {
  9416. items.push_back(file);
  9417. return true;
  9418. },
  9419. [&](const char *data, size_t data_length) {
  9420. items.back().content.append(data, data_length);
  9421. return true;
  9422. });
  9423. EXPECT_TRUE(std::string(items[0].name) == "document");
  9424. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9425. EXPECT_TRUE(items[0].filename == "2MB_data");
  9426. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9427. EXPECT_TRUE(items[1].name == "hello");
  9428. EXPECT_TRUE(items[1].content == "world");
  9429. EXPECT_TRUE(items[1].filename == "");
  9430. EXPECT_TRUE(items[1].content_type == "");
  9431. } else {
  9432. std::string body;
  9433. content_reader([&](const char *data, size_t data_length) {
  9434. body.append(data, data_length);
  9435. return true;
  9436. });
  9437. }
  9438. });
  9439. auto port = svr.bind_to_any_port(HOST);
  9440. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9441. auto se = detail::scope_exit([&] {
  9442. svr.stop();
  9443. t.join();
  9444. ASSERT_FALSE(svr.is_running());
  9445. });
  9446. svr.wait_until_ready();
  9447. {
  9448. std::string data(1024 * 1024 * 2, '.');
  9449. std::stringstream buffer;
  9450. buffer << data;
  9451. SSLClient cli(HOST, port);
  9452. cli.enable_server_certificate_verification(false);
  9453. UploadFormDataItems items{
  9454. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9455. {"hello", "world", "", ""},
  9456. };
  9457. auto res = cli.Post("/post", items);
  9458. ASSERT_TRUE(res);
  9459. ASSERT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. }
  9462. TEST(MultipartFormDataTest, DataProviderItems) {
  9463. std::random_device seed_gen;
  9464. std::mt19937 random(seed_gen());
  9465. std::string rand1;
  9466. rand1.resize(1000);
  9467. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9468. std::string rand2;
  9469. rand2.resize(3000);
  9470. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9472. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9473. const ContentReader &content_reader) {
  9474. ASSERT_FALSE(req.is_multipart_form_data());
  9475. std::string body;
  9476. content_reader([&](const char *data, size_t data_length) {
  9477. body.append(data, data_length);
  9478. return true;
  9479. });
  9480. EXPECT_EQ(body, "");
  9481. });
  9482. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9483. const ContentReader &content_reader) {
  9484. ASSERT_TRUE(req.is_multipart_form_data());
  9485. std::vector<FormData> items;
  9486. content_reader(
  9487. [&](const FormData &file) {
  9488. items.push_back(file);
  9489. return true;
  9490. },
  9491. [&](const char *data, size_t data_length) {
  9492. items.back().content.append(data, data_length);
  9493. return true;
  9494. });
  9495. ASSERT_TRUE(items.size() == 2);
  9496. EXPECT_EQ(std::string(items[0].name), "name1");
  9497. EXPECT_EQ(items[0].content, "Testing123");
  9498. EXPECT_EQ(items[0].filename, "filename1");
  9499. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9500. EXPECT_EQ(items[1].name, "name2");
  9501. EXPECT_EQ(items[1].content, "Testing456");
  9502. EXPECT_EQ(items[1].filename, "");
  9503. EXPECT_EQ(items[1].content_type, "");
  9504. });
  9505. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9506. const ContentReader &content_reader) {
  9507. ASSERT_TRUE(req.is_multipart_form_data());
  9508. std::vector<FormData> items;
  9509. content_reader(
  9510. [&](const FormData &file) {
  9511. items.push_back(file);
  9512. return true;
  9513. },
  9514. [&](const char *data, size_t data_length) {
  9515. items.back().content.append(data, data_length);
  9516. return true;
  9517. });
  9518. ASSERT_TRUE(items.size() == 2);
  9519. EXPECT_EQ(items[0].name, "name3");
  9520. EXPECT_EQ(items[0].content, rand1);
  9521. EXPECT_EQ(items[0].filename, "filename3");
  9522. EXPECT_EQ(items[0].content_type, "");
  9523. EXPECT_EQ(items[1].name, "name4");
  9524. EXPECT_EQ(items[1].content, rand2);
  9525. EXPECT_EQ(items[1].filename, "filename4");
  9526. EXPECT_EQ(items[1].content_type, "");
  9527. });
  9528. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9529. const ContentReader &content_reader) {
  9530. ASSERT_TRUE(req.is_multipart_form_data());
  9531. std::vector<FormData> items;
  9532. content_reader(
  9533. [&](const FormData &file) {
  9534. items.push_back(file);
  9535. return true;
  9536. },
  9537. [&](const char *data, size_t data_length) {
  9538. items.back().content.append(data, data_length);
  9539. return true;
  9540. });
  9541. ASSERT_TRUE(items.size() == 4);
  9542. EXPECT_EQ(std::string(items[0].name), "name1");
  9543. EXPECT_EQ(items[0].content, "Testing123");
  9544. EXPECT_EQ(items[0].filename, "filename1");
  9545. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9546. EXPECT_EQ(items[1].name, "name2");
  9547. EXPECT_EQ(items[1].content, "Testing456");
  9548. EXPECT_EQ(items[1].filename, "");
  9549. EXPECT_EQ(items[1].content_type, "");
  9550. EXPECT_EQ(items[2].name, "name3");
  9551. EXPECT_EQ(items[2].content, rand1);
  9552. EXPECT_EQ(items[2].filename, "filename3");
  9553. EXPECT_EQ(items[2].content_type, "");
  9554. EXPECT_EQ(items[3].name, "name4");
  9555. EXPECT_EQ(items[3].content, rand2);
  9556. EXPECT_EQ(items[3].filename, "filename4");
  9557. EXPECT_EQ(items[3].content_type, "");
  9558. });
  9559. auto port = svr.bind_to_any_port("localhost");
  9560. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9561. auto se = detail::scope_exit([&] {
  9562. svr.stop();
  9563. t.join();
  9564. ASSERT_FALSE(svr.is_running());
  9565. });
  9566. svr.wait_until_ready();
  9567. {
  9568. SSLClient cli("localhost", port);
  9569. cli.enable_server_certificate_verification(false);
  9570. UploadFormDataItems items{
  9571. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9572. {"name2", "Testing456", "", ""}, // not a file
  9573. };
  9574. {
  9575. auto res = cli.Post("/post-none", {}, {}, {});
  9576. ASSERT_TRUE(res);
  9577. ASSERT_EQ(StatusCode::OK_200, res->status);
  9578. }
  9579. FormDataProviderItems providers;
  9580. {
  9581. auto res =
  9582. cli.Post("/post-items", {}, items, providers); // empty providers
  9583. ASSERT_TRUE(res);
  9584. ASSERT_EQ(StatusCode::OK_200, res->status);
  9585. }
  9586. providers.push_back({"name3",
  9587. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9588. // test the offset is given correctly at each step
  9589. if (!offset)
  9590. sink.os.write(rand1.data(), 30);
  9591. else if (offset == 30)
  9592. sink.os.write(rand1.data() + 30, 300);
  9593. else if (offset == 330)
  9594. sink.os.write(rand1.data() + 330, 670);
  9595. else if (offset == rand1.size())
  9596. sink.done();
  9597. return true;
  9598. },
  9599. "filename3",
  9600. {}});
  9601. providers.push_back({"name4",
  9602. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9603. // test the offset is given correctly at each step
  9604. if (!offset)
  9605. sink.os.write(rand2.data(), 2000);
  9606. else if (offset == 2000)
  9607. sink.os.write(rand2.data() + 2000, 1);
  9608. else if (offset == 2001)
  9609. sink.os.write(rand2.data() + 2001, 999);
  9610. else if (offset == rand2.size())
  9611. sink.done();
  9612. return true;
  9613. },
  9614. "filename4",
  9615. {}});
  9616. {
  9617. auto res = cli.Post("/post-providers", {}, {}, providers);
  9618. ASSERT_TRUE(res);
  9619. ASSERT_EQ(StatusCode::OK_200, res->status);
  9620. }
  9621. {
  9622. auto res = cli.Post("/post-both", {}, items, providers);
  9623. ASSERT_TRUE(res);
  9624. ASSERT_EQ(StatusCode::OK_200, res->status);
  9625. }
  9626. }
  9627. }
  9628. TEST(MultipartFormDataTest, BadHeader) {
  9629. Server svr;
  9630. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9631. res.set_content("ok", "text/plain");
  9632. });
  9633. thread t = thread([&] { svr.listen(HOST, PORT); });
  9634. auto se = detail::scope_exit([&] {
  9635. svr.stop();
  9636. t.join();
  9637. ASSERT_FALSE(svr.is_running());
  9638. });
  9639. svr.wait_until_ready();
  9640. const std::string body =
  9641. "This is the preamble. It is to be ignored, though it\r\n"
  9642. "is a handy place for composition agents to include an\r\n"
  9643. "explanatory note to non-MIME conformant readers.\r\n"
  9644. "\r\n"
  9645. "\r\n"
  9646. "--simple boundary\r\n"
  9647. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9648. ": BAD...\r\n"
  9649. "\r\n"
  9650. "value1\r\n"
  9651. "--simple boundary\r\n"
  9652. "Content-Disposition: form-data; name=\"field2\"; "
  9653. "filename=\"example.txt\"\r\n"
  9654. "\r\n"
  9655. "value2\r\n"
  9656. "--simple boundary--\r\n"
  9657. "This is the epilogue. It is also to be ignored.\r\n";
  9658. std::string content_type =
  9659. R"(multipart/form-data; boundary="simple boundary")";
  9660. Client cli(HOST, PORT);
  9661. auto res = cli.Post("/post", body, content_type.c_str());
  9662. ASSERT_TRUE(res);
  9663. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9664. }
  9665. TEST(MultipartFormDataTest, WithPreamble) {
  9666. Server svr;
  9667. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9668. res.set_content("ok", "text/plain");
  9669. });
  9670. thread t = thread([&] { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. t.join();
  9674. ASSERT_FALSE(svr.is_running());
  9675. });
  9676. svr.wait_until_ready();
  9677. const std::string body =
  9678. "This is the preamble. It is to be ignored, though it\r\n"
  9679. "is a handy place for composition agents to include an\r\n"
  9680. "explanatory note to non-MIME conformant readers.\r\n"
  9681. "\r\n"
  9682. "\r\n"
  9683. "--simple boundary\r\n"
  9684. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9685. "\r\n"
  9686. "value1\r\n"
  9687. "--simple boundary\r\n"
  9688. "Content-Disposition: form-data; name=\"field2\"; "
  9689. "filename=\"example.txt\"\r\n"
  9690. "\r\n"
  9691. "value2\r\n"
  9692. "--simple boundary--\r\n"
  9693. "This is the epilogue. It is also to be ignored.\r\n";
  9694. std::string content_type =
  9695. R"(multipart/form-data; boundary="simple boundary")";
  9696. Client cli(HOST, PORT);
  9697. auto res = cli.Post("/post", body, content_type.c_str());
  9698. ASSERT_TRUE(res);
  9699. EXPECT_EQ(StatusCode::OK_200, res->status);
  9700. }
  9701. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9703. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9704. const ContentReader &content_reader) {
  9705. if (req.is_multipart_form_data()) {
  9706. std::vector<FormData> items;
  9707. content_reader(
  9708. [&](const FormData &file) {
  9709. items.push_back(file);
  9710. return true;
  9711. },
  9712. [&](const char *data, size_t data_length) {
  9713. items.back().content.append(data, data_length);
  9714. return true;
  9715. });
  9716. EXPECT_TRUE(std::string(items[0].name) == "document");
  9717. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9718. EXPECT_TRUE(items[0].filename == "2MB_data");
  9719. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9720. EXPECT_TRUE(items[1].name == "hello");
  9721. EXPECT_TRUE(items[1].content == "world");
  9722. EXPECT_TRUE(items[1].filename == "");
  9723. EXPECT_TRUE(items[1].content_type == "");
  9724. } else {
  9725. std::string body;
  9726. content_reader([&](const char *data, size_t data_length) {
  9727. body.append(data, data_length);
  9728. return true;
  9729. });
  9730. }
  9731. });
  9732. auto port = svr.bind_to_any_port("localhost");
  9733. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9734. auto se = detail::scope_exit([&] {
  9735. svr.stop();
  9736. t.join();
  9737. ASSERT_FALSE(svr.is_running());
  9738. });
  9739. svr.wait_until_ready();
  9740. {
  9741. std::string data(1024 * 1024 * 2, '.');
  9742. std::stringstream buffer;
  9743. buffer << data;
  9744. SSLClient cli("localhost", port);
  9745. cli.enable_server_certificate_verification(false);
  9746. UploadFormDataItems items{
  9747. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9748. {"hello", "world", "", ""},
  9749. };
  9750. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9751. ASSERT_TRUE(res);
  9752. ASSERT_EQ(StatusCode::OK_200, res->status);
  9753. }
  9754. }
  9755. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9756. std::string data(1024 * 1024 * 2, '&');
  9757. std::stringstream buffer;
  9758. buffer << data;
  9759. Client cli("https://localhost:8080");
  9760. UploadFormDataItems items{
  9761. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9762. {"hello", "world", "", ""},
  9763. };
  9764. for (const char &c : " \t\r\n") {
  9765. auto res =
  9766. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9767. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9768. ASSERT_FALSE(res);
  9769. }
  9770. }
  9771. TEST(MultipartFormDataTest, PutFormData) {
  9772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9773. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9774. const ContentReader &content_reader) {
  9775. if (req.is_multipart_form_data()) {
  9776. std::vector<FormData> items;
  9777. content_reader(
  9778. [&](const FormData &file) {
  9779. items.push_back(file);
  9780. return true;
  9781. },
  9782. [&](const char *data, size_t data_length) {
  9783. items.back().content.append(data, data_length);
  9784. return true;
  9785. });
  9786. EXPECT_TRUE(std::string(items[0].name) == "document");
  9787. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9788. EXPECT_TRUE(items[0].filename == "2MB_data");
  9789. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9790. EXPECT_TRUE(items[1].name == "hello");
  9791. EXPECT_TRUE(items[1].content == "world");
  9792. EXPECT_TRUE(items[1].filename == "");
  9793. EXPECT_TRUE(items[1].content_type == "");
  9794. } else {
  9795. std::string body;
  9796. content_reader([&](const char *data, size_t data_length) {
  9797. body.append(data, data_length);
  9798. return true;
  9799. });
  9800. }
  9801. });
  9802. auto port = svr.bind_to_any_port("localhost");
  9803. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9804. auto se = detail::scope_exit([&] {
  9805. svr.stop();
  9806. t.join();
  9807. ASSERT_FALSE(svr.is_running());
  9808. });
  9809. svr.wait_until_ready();
  9810. {
  9811. std::string data(1024 * 1024 * 2, '&');
  9812. std::stringstream buffer;
  9813. buffer << data;
  9814. SSLClient cli("localhost", port);
  9815. cli.enable_server_certificate_verification(false);
  9816. UploadFormDataItems items{
  9817. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9818. {"hello", "world", "", ""},
  9819. };
  9820. auto res = cli.Put("/put", items);
  9821. ASSERT_TRUE(res);
  9822. ASSERT_EQ(StatusCode::OK_200, res->status);
  9823. }
  9824. }
  9825. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9827. svr.Put("/put_customboundary",
  9828. [&](const Request &req, const Response & /*res*/,
  9829. const ContentReader &content_reader) {
  9830. if (req.is_multipart_form_data()) {
  9831. std::vector<FormData> items;
  9832. content_reader(
  9833. [&](const FormData &file) {
  9834. items.push_back(file);
  9835. return true;
  9836. },
  9837. [&](const char *data, size_t data_length) {
  9838. items.back().content.append(data, data_length);
  9839. return true;
  9840. });
  9841. EXPECT_TRUE(std::string(items[0].name) == "document");
  9842. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9843. EXPECT_TRUE(items[0].filename == "2MB_data");
  9844. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9845. EXPECT_TRUE(items[1].name == "hello");
  9846. EXPECT_TRUE(items[1].content == "world");
  9847. EXPECT_TRUE(items[1].filename == "");
  9848. EXPECT_TRUE(items[1].content_type == "");
  9849. } else {
  9850. std::string body;
  9851. content_reader([&](const char *data, size_t data_length) {
  9852. body.append(data, data_length);
  9853. return true;
  9854. });
  9855. }
  9856. });
  9857. auto port = svr.bind_to_any_port("localhost");
  9858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9859. auto se = detail::scope_exit([&] {
  9860. svr.stop();
  9861. t.join();
  9862. ASSERT_FALSE(svr.is_running());
  9863. });
  9864. svr.wait_until_ready();
  9865. {
  9866. std::string data(1024 * 1024 * 2, '&');
  9867. std::stringstream buffer;
  9868. buffer << data;
  9869. SSLClient cli("localhost", port);
  9870. cli.enable_server_certificate_verification(false);
  9871. UploadFormDataItems items{
  9872. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9873. {"hello", "world", "", ""},
  9874. };
  9875. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9876. ASSERT_TRUE(res);
  9877. ASSERT_EQ(StatusCode::OK_200, res->status);
  9878. }
  9879. }
  9880. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9881. std::string data(1024 * 1024 * 2, '&');
  9882. std::stringstream buffer;
  9883. buffer << data;
  9884. Client cli("https://localhost:8080");
  9885. cli.enable_server_certificate_verification(false);
  9886. UploadFormDataItems items{
  9887. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9888. {"hello", "world", "", ""},
  9889. };
  9890. for (const char &c : " \t\r\n") {
  9891. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9892. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9893. ASSERT_FALSE(res);
  9894. }
  9895. }
  9896. TEST(MultipartFormDataTest, AlternateFilename) {
  9897. auto handled = false;
  9898. Server svr;
  9899. svr.Post("/test", [&](const Request &req, Response &res) {
  9900. ASSERT_EQ(2u, req.form.files.size());
  9901. ASSERT_EQ(1u, req.form.fields.size());
  9902. // Test files
  9903. const auto &file1 = req.form.get_file("file1");
  9904. ASSERT_EQ("file1", file1.name);
  9905. ASSERT_EQ("A.txt", file1.filename);
  9906. ASSERT_EQ("text/plain", file1.content_type);
  9907. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9908. const auto &file2 = req.form.get_file("file2");
  9909. ASSERT_EQ("file2", file2.name);
  9910. ASSERT_EQ("a.html", file2.filename);
  9911. ASSERT_EQ("text/html", file2.content_type);
  9912. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9913. file2.content);
  9914. // Test text field
  9915. const auto &text = req.form.get_field("text");
  9916. ASSERT_EQ("text default", text);
  9917. res.set_content("ok", "text/plain");
  9918. handled = true;
  9919. });
  9920. thread t = thread([&] { svr.listen(HOST, PORT); });
  9921. auto se = detail::scope_exit([&] {
  9922. svr.stop();
  9923. t.join();
  9924. ASSERT_FALSE(svr.is_running());
  9925. ASSERT_TRUE(handled);
  9926. });
  9927. svr.wait_until_ready();
  9928. auto req = "POST /test HTTP/1.1\r\n"
  9929. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9930. "Content-Length: 399\r\n"
  9931. "\r\n"
  9932. "----------\r\n"
  9933. "Content-Disposition: form-data; name=\"text\"\r\n"
  9934. "\r\n"
  9935. "text default\r\n"
  9936. "----------\r\n"
  9937. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9938. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9939. "Content-Type: text/plain\r\n"
  9940. "\r\n"
  9941. "Content of a.txt.\r\n"
  9942. "\r\n"
  9943. "----------\r\n"
  9944. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9945. "\"a.html\"\r\n"
  9946. "Content-Type: text/html\r\n"
  9947. "\r\n"
  9948. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9949. "\r\n"
  9950. "------------\r\n";
  9951. ASSERT_TRUE(send_request(1, req));
  9952. }
  9953. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9954. auto handled = false;
  9955. Server svr;
  9956. svr.Post("/test", [&](const Request &req, Response &res) {
  9957. // Case-insensitive "utf-8''" prefix with a long value
  9958. const auto &file = req.form.get_file("file1");
  9959. ASSERT_EQ("file1", file.name);
  9960. // 8000 chars exercises both the Content-Disposition parser and the
  9961. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9962. // Prior to the fix, std::regex_match on this header would cause O(N)
  9963. // stack recursion in libstdc++, leading to SIGSEGV.
  9964. std::string expected_filename(8000, 'A');
  9965. ASSERT_EQ(expected_filename, file.filename);
  9966. res.set_content("ok", "text/plain");
  9967. handled = true;
  9968. });
  9969. thread t = thread([&] { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. ASSERT_TRUE(handled);
  9975. });
  9976. svr.wait_until_ready();
  9977. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9978. // Regression test for GHSA-qq6v-r583-3h69
  9979. std::string long_filename(8000, 'A');
  9980. std::string body = "----------\r\n"
  9981. "Content-Disposition: form-data; name=\"file1\"; "
  9982. "filename*=\"Utf-8''" +
  9983. long_filename +
  9984. "\"\r\n"
  9985. "\r\n"
  9986. "hello\r\n"
  9987. "------------\r\n";
  9988. auto req = "POST /test HTTP/1.1\r\n"
  9989. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9990. "Content-Length: " +
  9991. std::to_string(body.size()) + "\r\n\r\n" + body;
  9992. ASSERT_TRUE(send_request(1, req));
  9993. }
  9994. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9995. auto handled = false;
  9996. Server svr;
  9997. svr.Post("/test", [&](const Request &req, Response &) {
  9998. ASSERT_EQ(2u, req.form.fields.size());
  9999. const auto &text1 = req.form.get_field("text1");
  10000. ASSERT_EQ("text1", text1);
  10001. const auto &text2 = req.form.get_field("text2");
  10002. ASSERT_EQ("text2", text2);
  10003. handled = true;
  10004. });
  10005. thread t = thread([&] { svr.listen(HOST, PORT); });
  10006. auto se = detail::scope_exit([&] {
  10007. svr.stop();
  10008. t.join();
  10009. ASSERT_FALSE(svr.is_running());
  10010. ASSERT_TRUE(handled);
  10011. });
  10012. svr.wait_until_ready();
  10013. auto req = "POST /test HTTP/1.1\r\n"
  10014. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10015. "Content-Length: 146\r\n"
  10016. "\r\n----------\r\n"
  10017. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10018. "\r\n"
  10019. "text1"
  10020. "\r\n----------\r\n"
  10021. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10022. "\r\n"
  10023. "text2"
  10024. "\r\n------------";
  10025. std::string response;
  10026. ASSERT_TRUE(send_request(1, req, &response));
  10027. ASSERT_EQ("200", response.substr(9, 3));
  10028. }
  10029. TEST(MultipartFormDataTest, ContentLength) {
  10030. auto handled = false;
  10031. Server svr;
  10032. svr.Post("/test", [&](const Request &req, Response &) {
  10033. ASSERT_EQ(2u, req.form.fields.size());
  10034. const auto &text1 = req.form.get_field("text1");
  10035. ASSERT_EQ("text1", text1);
  10036. const auto &text2 = req.form.get_field("text2");
  10037. ASSERT_EQ("text2", text2);
  10038. handled = true;
  10039. });
  10040. thread t = thread([&] { svr.listen(HOST, PORT); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. ASSERT_FALSE(svr.is_running());
  10045. ASSERT_TRUE(handled);
  10046. });
  10047. svr.wait_until_ready();
  10048. auto req = "POST /test HTTP/1.1\r\n"
  10049. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10050. "Content-Length: 167\r\n"
  10051. "\r\n----------\r\n"
  10052. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10053. "Content-Length: 5\r\n"
  10054. "\r\n"
  10055. "text1"
  10056. "\r\n----------\r\n"
  10057. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10058. "\r\n"
  10059. "text2"
  10060. "\r\n------------\r\n";
  10061. std::string response;
  10062. ASSERT_TRUE(send_request(1, req, &response));
  10063. ASSERT_EQ("200", response.substr(9, 3));
  10064. }
  10065. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10066. auto handled = false;
  10067. Server svr;
  10068. svr.Post("/test", [&](const Request &req, Response &) {
  10069. ASSERT_EQ(2u, req.form.fields.size());
  10070. const auto &text1 = req.form.get_field("text1");
  10071. ASSERT_EQ("text1", text1);
  10072. // TODO: Add header access for text fields if needed
  10073. const auto &text2 = req.form.get_field("text2");
  10074. ASSERT_EQ("text2", text2);
  10075. // TODO: Header access for text fields needs to be implemented
  10076. // auto &headers = it->second.headers;
  10077. // ASSERT_EQ(3U, headers.size());
  10078. // auto custom_header = headers.find("x-whatever");
  10079. // ASSERT_TRUE(custom_header != headers.end());
  10080. // ASSERT_NE("customvalue", custom_header->second);
  10081. // ASSERT_EQ("CustomValue", custom_header->second);
  10082. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10083. handled = true;
  10084. });
  10085. thread t = thread([&] { svr.listen(HOST, PORT); });
  10086. auto se = detail::scope_exit([&] {
  10087. svr.stop();
  10088. t.join();
  10089. ASSERT_FALSE(svr.is_running());
  10090. ASSERT_TRUE(handled);
  10091. });
  10092. svr.wait_until_ready();
  10093. auto req = "POST /test HTTP/1.1\r\n"
  10094. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10095. "Content-Length: 232\r\n"
  10096. "\r\n----------\r\n"
  10097. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10098. "Content-Length: 5\r\n"
  10099. "X-Test: 1\r\n"
  10100. "\r\n"
  10101. "text1"
  10102. "\r\n----------\r\n"
  10103. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10104. "Content-Type: text/plain\r\n"
  10105. "X-Whatever: CustomValue\r\n"
  10106. "\r\n"
  10107. "text2"
  10108. "\r\n------------\r\n"
  10109. "That should be disregarded. Not even read";
  10110. std::string response;
  10111. ASSERT_TRUE(send_request(1, req, &response));
  10112. ASSERT_EQ("200", response.substr(9, 3));
  10113. }
  10114. TEST(MultipartFormDataTest, LargeHeader) {
  10115. auto handled = false;
  10116. Server svr;
  10117. svr.Post("/test", [&](const Request &req, Response &) {
  10118. ASSERT_EQ(1u, req.form.fields.size());
  10119. const auto &text = req.form.get_field("name1");
  10120. ASSERT_EQ("text1", text);
  10121. handled = true;
  10122. });
  10123. thread t = thread([&] { svr.listen(HOST, PORT); });
  10124. auto se = detail::scope_exit([&] {
  10125. svr.stop();
  10126. t.join();
  10127. ASSERT_FALSE(svr.is_running());
  10128. ASSERT_TRUE(handled);
  10129. });
  10130. svr.wait_until_ready();
  10131. auto boundary = std::string("cpp-httplib-multipart-data");
  10132. std::string content = "--" + boundary +
  10133. "\r\n"
  10134. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10135. "\r\n"
  10136. "text1\r\n"
  10137. "--" +
  10138. boundary + "--\r\n";
  10139. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10140. "Content-Type: multipart/form-data;boundary=" +
  10141. boundary +
  10142. "\r\n"
  10143. "Content-Length: " +
  10144. std::to_string(content.size()) +
  10145. "\r\n"
  10146. "Dummy-Header: ";
  10147. std::string header_suffix = "\r\n"
  10148. "\r\n";
  10149. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10150. size_t header_dummy_size =
  10151. read_buff_size -
  10152. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10153. auto header_dummy = std::string(header_dummy_size, '@');
  10154. auto req = header_prefix + header_dummy + header_suffix + content;
  10155. std::string response;
  10156. ASSERT_TRUE(send_request(1, req, &response));
  10157. ASSERT_EQ("200", response.substr(9, 3));
  10158. }
  10159. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10160. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10161. // (not chunked Transfer-Encoding) after the streaming refactor.
  10162. auto handled = false;
  10163. Server svr;
  10164. svr.Post("/upload", [&](const Request &req, Response &res) {
  10165. auto cl_it = req.headers.find("Content-Length");
  10166. EXPECT_TRUE(cl_it != req.headers.end());
  10167. auto te_it = req.headers.find("Transfer-Encoding");
  10168. EXPECT_TRUE(te_it == req.headers.end());
  10169. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10170. res.set_content("ok", "text/plain");
  10171. handled = true;
  10172. });
  10173. auto port = svr.bind_to_any_port(HOST);
  10174. auto t = thread([&] { svr.listen_after_bind(); });
  10175. auto se = detail::scope_exit([&] {
  10176. svr.stop();
  10177. t.join();
  10178. ASSERT_FALSE(svr.is_running());
  10179. ASSERT_TRUE(handled);
  10180. });
  10181. svr.wait_until_ready();
  10182. UploadFormDataItems items = {
  10183. {"field1", "hello", "", "text/plain"},
  10184. {"file1", "world", "test.txt", "application/octet-stream"},
  10185. };
  10186. Client cli(HOST, port);
  10187. auto res = cli.Post("/upload", {}, items);
  10188. ASSERT_TRUE(res);
  10189. EXPECT_EQ(StatusCode::OK_200, res->status);
  10190. }
  10191. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10192. // Verify that make_multipart_content_provider coalesces many small segments
  10193. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10194. constexpr size_t kItemCount = 1000;
  10195. UploadFormDataItems items;
  10196. items.reserve(kItemCount);
  10197. for (size_t i = 0; i < kItemCount; i++) {
  10198. items.push_back(
  10199. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10200. }
  10201. const std::string boundary = "----test-boundary";
  10202. auto content_length = detail::get_multipart_content_length(items, boundary);
  10203. auto provider = detail::make_multipart_content_provider(items, boundary);
  10204. // Drive the provider the same way write_content_with_progress does
  10205. size_t write_count = 0;
  10206. size_t total_bytes = 0;
  10207. DataSink sink;
  10208. size_t offset = 0;
  10209. sink.write = [&](const char *d, size_t l) -> bool {
  10210. (void)d;
  10211. write_count++;
  10212. total_bytes += l;
  10213. offset += l;
  10214. return true;
  10215. };
  10216. sink.is_writable = []() -> bool { return true; };
  10217. while (offset < content_length) {
  10218. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10219. }
  10220. EXPECT_EQ(content_length, total_bytes);
  10221. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10222. // With buffering into 64KB blocks, write_count should be much smaller.
  10223. auto segment_count = 3 * kItemCount + 1;
  10224. EXPECT_LT(write_count, segment_count / 10);
  10225. }
  10226. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10227. // Integration test: send many UploadFormDataItems and verify the server
  10228. // receives all of them correctly (#2410).
  10229. constexpr size_t kItemCount = 500;
  10230. auto handled = false;
  10231. Server svr;
  10232. svr.Post("/upload", [&](const Request &req, Response &res) {
  10233. EXPECT_EQ(kItemCount, req.form.fields.size());
  10234. for (size_t i = 0; i < kItemCount; i++) {
  10235. auto key = "field" + std::to_string(i);
  10236. auto val = "value" + std::to_string(i);
  10237. auto it = req.form.fields.find(key);
  10238. if (it != req.form.fields.end()) {
  10239. EXPECT_EQ(val, it->second.content);
  10240. } else {
  10241. ADD_FAILURE() << "Missing field: " << key;
  10242. }
  10243. }
  10244. res.set_content("ok", "text/plain");
  10245. handled = true;
  10246. });
  10247. auto port = svr.bind_to_any_port(HOST);
  10248. auto t = thread([&] { svr.listen_after_bind(); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. t.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. ASSERT_TRUE(handled);
  10254. });
  10255. svr.wait_until_ready();
  10256. UploadFormDataItems items;
  10257. items.reserve(kItemCount);
  10258. for (size_t i = 0; i < kItemCount; i++) {
  10259. items.push_back(
  10260. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10261. }
  10262. Client cli(HOST, port);
  10263. auto res = cli.Post("/upload", items);
  10264. ASSERT_TRUE(res);
  10265. EXPECT_EQ(StatusCode::OK_200, res->status);
  10266. }
  10267. TEST(MultipartFormDataTest, MakeFileProvider) {
  10268. // Verify make_file_provider sends a file's contents correctly.
  10269. const std::string file_content(4096, 'Z');
  10270. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10271. {
  10272. std::ofstream ofs(tmp_path, std::ios::binary);
  10273. ofs.write(file_content.data(),
  10274. static_cast<std::streamsize>(file_content.size()));
  10275. }
  10276. auto handled = false;
  10277. Server svr;
  10278. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10279. const ContentReader &content_reader) {
  10280. ASSERT_TRUE(req.is_multipart_form_data());
  10281. std::vector<FormData> items;
  10282. content_reader(
  10283. [&](const FormData &file) {
  10284. items.push_back(file);
  10285. return true;
  10286. },
  10287. [&](const char *data, size_t data_length) {
  10288. items.back().content.append(data, data_length);
  10289. return true;
  10290. });
  10291. ASSERT_EQ(1u, items.size());
  10292. EXPECT_EQ("myfile", items[0].name);
  10293. EXPECT_EQ("data.bin", items[0].filename);
  10294. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10295. EXPECT_EQ(file_content, items[0].content);
  10296. handled = true;
  10297. });
  10298. auto port = svr.bind_to_any_port(HOST);
  10299. auto t = thread([&] { svr.listen_after_bind(); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. t.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. ASSERT_TRUE(handled);
  10305. std::remove(tmp_path.c_str());
  10306. });
  10307. svr.wait_until_ready();
  10308. FormDataProviderItems providers;
  10309. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10310. "application/octet-stream"));
  10311. Client cli(HOST, port);
  10312. auto res = cli.Post("/upload", {}, {}, providers);
  10313. ASSERT_TRUE(res);
  10314. EXPECT_EQ(StatusCode::OK_200, res->status);
  10315. }
  10316. TEST(MakeFileBodyTest, Basic) {
  10317. const std::string file_content(4096, 'Z');
  10318. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10319. {
  10320. std::ofstream ofs(tmp_path, std::ios::binary);
  10321. ofs.write(file_content.data(),
  10322. static_cast<std::streamsize>(file_content.size()));
  10323. }
  10324. auto handled = false;
  10325. Server svr;
  10326. svr.Post("/upload", [&](const Request &req, Response &res) {
  10327. EXPECT_EQ(file_content, req.body);
  10328. handled = true;
  10329. res.status = StatusCode::OK_200;
  10330. });
  10331. auto port = svr.bind_to_any_port(HOST);
  10332. auto t = thread([&] { svr.listen_after_bind(); });
  10333. auto se = detail::scope_exit([&] {
  10334. svr.stop();
  10335. t.join();
  10336. ASSERT_FALSE(svr.is_running());
  10337. ASSERT_TRUE(handled);
  10338. std::remove(tmp_path.c_str());
  10339. });
  10340. svr.wait_until_ready();
  10341. auto fb = make_file_body(tmp_path);
  10342. ASSERT_GT(fb.first, 0u);
  10343. Client cli(HOST, port);
  10344. auto res =
  10345. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10346. ASSERT_TRUE(res);
  10347. EXPECT_EQ(StatusCode::OK_200, res->status);
  10348. }
  10349. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10350. static constexpr unsigned int number_of_tasks{1000000};
  10351. std::atomic_uint count{0};
  10352. std::unique_ptr<TaskQueue> task_queue{
  10353. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10354. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10355. auto queued = task_queue->enqueue(
  10356. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10357. EXPECT_TRUE(queued);
  10358. }
  10359. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10360. task_queue->shutdown();
  10361. #else
  10362. EXPECT_NO_THROW(task_queue->shutdown());
  10363. #endif
  10364. EXPECT_EQ(number_of_tasks, count.load());
  10365. }
  10366. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10367. static constexpr unsigned int number_of_tasks{1000000};
  10368. static constexpr unsigned int qlimit{2};
  10369. unsigned int queued_count{0};
  10370. std::atomic_uint count{0};
  10371. std::unique_ptr<TaskQueue> task_queue{
  10372. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10373. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10374. if (task_queue->enqueue(
  10375. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10376. queued_count++;
  10377. }
  10378. }
  10379. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10380. task_queue->shutdown();
  10381. #else
  10382. EXPECT_NO_THROW(task_queue->shutdown());
  10383. #endif
  10384. EXPECT_EQ(queued_count, count.load());
  10385. EXPECT_TRUE(queued_count <= number_of_tasks);
  10386. EXPECT_TRUE(queued_count >= qlimit);
  10387. }
  10388. TEST(TaskQueueTest, MaxQueuedRequests) {
  10389. static constexpr unsigned int qlimit{3};
  10390. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10391. std::condition_variable sem_cv;
  10392. std::mutex sem_mtx;
  10393. int credits = 0;
  10394. bool queued;
  10395. /* Fill up the queue with tasks that will block until we give them credits to
  10396. * complete. */
  10397. for (unsigned int n = 0; n <= qlimit;) {
  10398. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10399. std::unique_lock<std::mutex> lock(sem_mtx);
  10400. while (credits <= 0) {
  10401. sem_cv.wait(lock);
  10402. }
  10403. /* Consume the credit and signal the test code if they are all gone. */
  10404. if (--credits == 0) { sem_cv.notify_one(); }
  10405. });
  10406. if (n < qlimit) {
  10407. /* The first qlimit enqueues must succeed. */
  10408. EXPECT_TRUE(queued);
  10409. } else {
  10410. /* The last one will succeed only when the worker thread
  10411. * starts and dequeues the first blocking task. Although
  10412. * not necessary for the correctness of this test, we sleep for
  10413. * a short while to avoid busy waiting. */
  10414. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10415. }
  10416. if (queued) { n++; }
  10417. }
  10418. /* Further enqueues must fail since the queue is full. */
  10419. for (auto i = 0; i < 4; i++) {
  10420. queued = task_queue->enqueue([] {});
  10421. EXPECT_FALSE(queued);
  10422. }
  10423. /* Give the credits to allow the previous tasks to complete. */
  10424. {
  10425. std::unique_lock<std::mutex> lock(sem_mtx);
  10426. credits += qlimit + 1;
  10427. }
  10428. sem_cv.notify_all();
  10429. /* Wait for all the credits to be consumed. */
  10430. {
  10431. std::unique_lock<std::mutex> lock(sem_mtx);
  10432. while (credits > 0) {
  10433. sem_cv.wait(lock);
  10434. }
  10435. }
  10436. /* Check that we are able again to enqueue at least qlimit tasks. */
  10437. for (unsigned int i = 0; i < qlimit; i++) {
  10438. queued = task_queue->enqueue([] {});
  10439. EXPECT_TRUE(queued);
  10440. }
  10441. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10442. task_queue->shutdown();
  10443. #else
  10444. EXPECT_NO_THROW(task_queue->shutdown());
  10445. #endif
  10446. }
  10447. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10448. Server svr;
  10449. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10450. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10451. });
  10452. svr.Get("/hello", [](const Request &req, Response &res) {
  10453. res.set_content(req.get_param_value("key"), "text/plain");
  10454. });
  10455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10456. auto se = detail::scope_exit([&] {
  10457. svr.stop();
  10458. thread.join();
  10459. ASSERT_FALSE(svr.is_running());
  10460. });
  10461. svr.wait_until_ready();
  10462. {
  10463. Client cli(HOST, PORT);
  10464. cli.set_follow_location(true);
  10465. auto res = cli.Get("/");
  10466. ASSERT_TRUE(res);
  10467. EXPECT_EQ(StatusCode::OK_200, res->status);
  10468. EXPECT_EQ("val&key2=val2", res->body);
  10469. }
  10470. }
  10471. #endif
  10472. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10473. Server svr;
  10474. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10475. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10476. });
  10477. svr.Get("/hello", [](const Request &req, Response &res) {
  10478. res.set_content(req.get_param_value("key"), "text/plain");
  10479. });
  10480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10481. auto se = detail::scope_exit([&] {
  10482. svr.stop();
  10483. thread.join();
  10484. ASSERT_FALSE(svr.is_running());
  10485. });
  10486. svr.wait_until_ready();
  10487. {
  10488. Client cli(HOST, PORT);
  10489. cli.set_follow_location(true);
  10490. auto res = cli.Get("/");
  10491. ASSERT_TRUE(res);
  10492. EXPECT_EQ(StatusCode::OK_200, res->status);
  10493. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10494. }
  10495. }
  10496. TEST(RedirectTest, RedirectWithPlusInPath) {
  10497. Server svr;
  10498. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10499. res.set_redirect("/a+b");
  10500. });
  10501. // Route pattern uses regex; escape + as \\+
  10502. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10503. res.set_content(req.path, "text/plain");
  10504. });
  10505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10506. auto se = detail::scope_exit([&] {
  10507. svr.stop();
  10508. thread.join();
  10509. ASSERT_FALSE(svr.is_running());
  10510. });
  10511. svr.wait_until_ready();
  10512. {
  10513. Client cli(HOST, PORT);
  10514. cli.set_follow_location(true);
  10515. auto res = cli.Get("/");
  10516. ASSERT_TRUE(res);
  10517. EXPECT_EQ(StatusCode::OK_200, res->status);
  10518. EXPECT_EQ("/a+b", res->body);
  10519. }
  10520. }
  10521. #ifdef CPPHTTPLIB_SSL_ENABLED
  10522. TEST(RedirectTest, Issue2185_Online) {
  10523. SSLClient client("github.com");
  10524. client.set_follow_location(true);
  10525. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10526. "Coollab-Windows.zip");
  10527. ASSERT_TRUE(res);
  10528. EXPECT_EQ(StatusCode::OK_200, res->status);
  10529. EXPECT_EQ(9920427U, res->body.size());
  10530. }
  10531. #endif
  10532. TEST(VulnerabilityTest, CRLFInjection) {
  10533. Server svr;
  10534. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10535. res.set_content("Hello 1", "text/plain");
  10536. });
  10537. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10538. res.set_content("Hello 2", "text/plain");
  10539. });
  10540. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10541. res.set_content("Hello 3", "text/plain");
  10542. });
  10543. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10544. res.set_content("Hello 4", "text/plain");
  10545. });
  10546. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10547. for (const auto &x : req.headers) {
  10548. auto key = x.first;
  10549. EXPECT_STRNE("evil", key.c_str());
  10550. }
  10551. });
  10552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. thread.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. });
  10558. svr.wait_until_ready();
  10559. {
  10560. Client cli(HOST, PORT);
  10561. cli.Post("/test1", "A=B",
  10562. "application/x-www-form-urlencoded\r\nevil: hello1");
  10563. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10564. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10565. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10566. }
  10567. }
  10568. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10569. auto server_thread = std::thread([] {
  10570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10571. default_socket_options(srv);
  10572. sockaddr_in addr{};
  10573. addr.sin_family = AF_INET;
  10574. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10575. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10576. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10577. ::listen(srv, 1);
  10578. sockaddr_in cli_addr{};
  10579. socklen_t cli_len = sizeof(cli_addr);
  10580. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10581. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10582. std::string buf_all;
  10583. char buf[2048];
  10584. ssize_t n;
  10585. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10586. buf_all.append(buf, static_cast<size_t>(n));
  10587. size_t pos;
  10588. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10589. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10590. auto e = request_block.find("\r\n");
  10591. if (e != std::string::npos) {
  10592. auto request_line = request_block.substr(0, e);
  10593. std::string msg =
  10594. "CRLF injection detected in request line: '" + request_line + "'";
  10595. EXPECT_FALSE(true) << msg;
  10596. }
  10597. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10598. ::send(cli,
  10599. #ifdef _WIN32
  10600. static_cast<const char *>(resp.c_str()),
  10601. static_cast<int>(resp.size()),
  10602. #else
  10603. resp.c_str(), resp.size(),
  10604. #endif
  10605. 0);
  10606. buf_all.erase(0, pos + 4);
  10607. }
  10608. }
  10609. detail::close_socket(cli);
  10610. detail::close_socket(srv);
  10611. });
  10612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10613. auto cli = Client("127.0.0.1", PORT + 1);
  10614. auto headers = Headers{
  10615. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10616. {"Connection", "keep-alive"}};
  10617. auto res = cli.Get("/hi", headers);
  10618. EXPECT_FALSE(res);
  10619. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10620. server_thread.join();
  10621. }
  10622. TEST(PathParamsTest, StaticMatch) {
  10623. const auto pattern = "/users/all";
  10624. detail::PathParamsMatcher matcher(pattern);
  10625. Request request;
  10626. request.path = "/users/all";
  10627. ASSERT_TRUE(matcher.match(request));
  10628. std::unordered_map<std::string, std::string> expected_params = {};
  10629. EXPECT_EQ(request.path_params, expected_params);
  10630. }
  10631. TEST(PathParamsTest, StaticMismatch) {
  10632. const auto pattern = "/users/all";
  10633. detail::PathParamsMatcher matcher(pattern);
  10634. Request request;
  10635. request.path = "/users/1";
  10636. ASSERT_FALSE(matcher.match(request));
  10637. }
  10638. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10639. const auto pattern = "/users/:id/subscriptions";
  10640. detail::PathParamsMatcher matcher(pattern);
  10641. Request request;
  10642. request.path = "/users/42/subscriptions";
  10643. ASSERT_TRUE(matcher.match(request));
  10644. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10645. EXPECT_EQ(request.path_params, expected_params);
  10646. }
  10647. TEST(PathParamsTest, SingleParamInTheEnd) {
  10648. const auto pattern = "/users/:id";
  10649. detail::PathParamsMatcher matcher(pattern);
  10650. Request request;
  10651. request.path = "/users/24";
  10652. ASSERT_TRUE(matcher.match(request));
  10653. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10654. EXPECT_EQ(request.path_params, expected_params);
  10655. }
  10656. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10657. const auto pattern = "/users/:id/";
  10658. detail::PathParamsMatcher matcher(pattern);
  10659. Request request;
  10660. request.path = "/users/42/";
  10661. ASSERT_TRUE(matcher.match(request));
  10662. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10663. EXPECT_EQ(request.path_params, expected_params);
  10664. }
  10665. TEST(PathParamsTest, EmptyParam) {
  10666. const auto pattern = "/users/:id/";
  10667. detail::PathParamsMatcher matcher(pattern);
  10668. Request request;
  10669. request.path = "/users//";
  10670. ASSERT_TRUE(matcher.match(request));
  10671. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10672. EXPECT_EQ(request.path_params, expected_params);
  10673. }
  10674. TEST(PathParamsTest, FragmentMismatch) {
  10675. const auto pattern = "/users/:id/";
  10676. detail::PathParamsMatcher matcher(pattern);
  10677. Request request;
  10678. request.path = "/admins/24/";
  10679. ASSERT_FALSE(matcher.match(request));
  10680. }
  10681. TEST(PathParamsTest, ExtraFragments) {
  10682. const auto pattern = "/users/:id";
  10683. detail::PathParamsMatcher matcher(pattern);
  10684. Request request;
  10685. request.path = "/users/42/subscriptions";
  10686. ASSERT_FALSE(matcher.match(request));
  10687. }
  10688. TEST(PathParamsTest, MissingTrailingParam) {
  10689. const auto pattern = "/users/:id";
  10690. detail::PathParamsMatcher matcher(pattern);
  10691. Request request;
  10692. request.path = "/users";
  10693. ASSERT_FALSE(matcher.match(request));
  10694. }
  10695. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10696. const auto pattern = "/users/:id/subscriptions";
  10697. detail::PathParamsMatcher matcher(pattern);
  10698. Request request;
  10699. request.path = "/users/subscriptions";
  10700. ASSERT_FALSE(matcher.match(request));
  10701. }
  10702. TEST(PathParamsTest, MultipleParams) {
  10703. const auto pattern = "/users/:userid/subscriptions/:subid";
  10704. detail::PathParamsMatcher matcher(pattern);
  10705. Request request;
  10706. request.path = "/users/42/subscriptions/2";
  10707. ASSERT_TRUE(matcher.match(request));
  10708. std::unordered_map<std::string, std::string> expected_params = {
  10709. {"userid", "42"}, {"subid", "2"}};
  10710. EXPECT_EQ(request.path_params, expected_params);
  10711. }
  10712. TEST(PathParamsTest, SequenceOfParams) {
  10713. const auto pattern = "/values/:x/:y/:z";
  10714. detail::PathParamsMatcher matcher(pattern);
  10715. Request request;
  10716. request.path = "/values/1/2/3";
  10717. ASSERT_TRUE(matcher.match(request));
  10718. std::unordered_map<std::string, std::string> expected_params = {
  10719. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10720. EXPECT_EQ(request.path_params, expected_params);
  10721. }
  10722. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10723. const auto pattern = "/prefix:suffix";
  10724. detail::PathParamsMatcher matcher(pattern);
  10725. Request request;
  10726. request.path = "/prefix:suffix";
  10727. ASSERT_TRUE(matcher.match(request));
  10728. const std::unordered_map<std::string, std::string> expected_params = {};
  10729. EXPECT_EQ(request.path_params, expected_params);
  10730. }
  10731. TEST(ParseUrlTest, VariousPatterns) {
  10732. {
  10733. detail::UrlComponents uc;
  10734. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10735. EXPECT_EQ("http", uc.scheme);
  10736. EXPECT_EQ("example.com", uc.host);
  10737. EXPECT_EQ("8080", uc.port);
  10738. EXPECT_EQ("/path", uc.path);
  10739. EXPECT_EQ("?q=1", uc.query);
  10740. }
  10741. {
  10742. detail::UrlComponents uc;
  10743. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10744. EXPECT_EQ("https", uc.scheme);
  10745. EXPECT_EQ("example.com", uc.host);
  10746. EXPECT_TRUE(uc.port.empty());
  10747. EXPECT_EQ("/path", uc.path);
  10748. }
  10749. {
  10750. detail::UrlComponents uc;
  10751. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10752. EXPECT_EQ("::1", uc.host);
  10753. EXPECT_EQ("8080", uc.port);
  10754. EXPECT_EQ("/path", uc.path);
  10755. }
  10756. {
  10757. detail::UrlComponents uc;
  10758. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10759. }
  10760. {
  10761. detail::UrlComponents uc;
  10762. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10763. EXPECT_TRUE(uc.scheme.empty());
  10764. EXPECT_EQ("example.com", uc.host);
  10765. EXPECT_EQ("/path", uc.path);
  10766. EXPECT_EQ("?q=1", uc.query);
  10767. }
  10768. {
  10769. detail::UrlComponents uc;
  10770. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10771. EXPECT_TRUE(uc.host.empty());
  10772. EXPECT_EQ("/path", uc.path);
  10773. EXPECT_EQ("?q=1", uc.query);
  10774. }
  10775. {
  10776. detail::UrlComponents uc;
  10777. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10778. EXPECT_EQ("example.com", uc.host);
  10779. EXPECT_EQ("8080", uc.port);
  10780. }
  10781. {
  10782. // Unix socket path — must not be parsed as host
  10783. detail::UrlComponents uc;
  10784. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10785. EXPECT_TRUE(uc.host.empty());
  10786. }
  10787. {
  10788. detail::UrlComponents uc;
  10789. ASSERT_TRUE(detail::parse_url("", uc));
  10790. EXPECT_TRUE(uc.host.empty());
  10791. EXPECT_TRUE(uc.path.empty());
  10792. }
  10793. {
  10794. detail::UrlComponents uc;
  10795. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10796. }
  10797. {
  10798. detail::UrlComponents uc;
  10799. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10800. }
  10801. {
  10802. // Accepted by parse_url; callers restrict to http/https
  10803. detail::UrlComponents uc;
  10804. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10805. EXPECT_EQ("ftp", uc.scheme);
  10806. }
  10807. {
  10808. detail::UrlComponents uc;
  10809. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10810. }
  10811. {
  10812. detail::UrlComponents uc;
  10813. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10814. }
  10815. }
  10816. TEST(ParseUrlTest, FragmentHandling) {
  10817. {
  10818. detail::UrlComponents uc;
  10819. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10820. EXPECT_EQ("/path", uc.path);
  10821. EXPECT_TRUE(uc.query.empty());
  10822. }
  10823. {
  10824. detail::UrlComponents uc;
  10825. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10826. EXPECT_TRUE(uc.path.empty());
  10827. EXPECT_TRUE(uc.query.empty());
  10828. }
  10829. }
  10830. TEST(ParseUrlTest, UserinfoHandling) {
  10831. // Userinfo with @ but no colon — host includes @
  10832. detail::UrlComponents uc;
  10833. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10834. EXPECT_EQ("user@host.com", uc.host);
  10835. EXPECT_EQ("/path", uc.path);
  10836. }
  10837. TEST(ParseUrlTest, IPv6EdgeCases) {
  10838. {
  10839. detail::UrlComponents uc;
  10840. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10841. EXPECT_TRUE(uc.scheme.empty());
  10842. EXPECT_EQ("::1", uc.host);
  10843. EXPECT_EQ("8080", uc.port);
  10844. }
  10845. {
  10846. // Zone ID '%25' is not in [a-fA-F0-9:]
  10847. detail::UrlComponents uc;
  10848. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10849. }
  10850. }
  10851. TEST(ParseUrlTest, SchemeEdgeCases) {
  10852. {
  10853. detail::UrlComponents uc;
  10854. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10855. }
  10856. {
  10857. detail::UrlComponents uc;
  10858. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10859. }
  10860. {
  10861. detail::UrlComponents uc;
  10862. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10863. }
  10864. }
  10865. TEST(ParseUrlTest, PortEdgeCases) {
  10866. {
  10867. detail::UrlComponents uc;
  10868. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10869. EXPECT_TRUE(uc.port.empty());
  10870. EXPECT_EQ("/path", uc.path);
  10871. }
  10872. {
  10873. // parse_url accepts any port string; validation is done by parse_port
  10874. detail::UrlComponents uc;
  10875. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10876. EXPECT_EQ("abc", uc.port);
  10877. }
  10878. }
  10879. TEST(ParseUrlTest, WebSocketPatterns) {
  10880. {
  10881. detail::UrlComponents uc;
  10882. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10883. EXPECT_EQ("ws", uc.scheme);
  10884. EXPECT_EQ("echo.example.com", uc.host);
  10885. EXPECT_EQ("8080", uc.port);
  10886. EXPECT_EQ("/ws", uc.path);
  10887. }
  10888. {
  10889. detail::UrlComponents uc;
  10890. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10891. EXPECT_EQ("wss", uc.scheme);
  10892. EXPECT_EQ("echo.example.com", uc.host);
  10893. EXPECT_TRUE(uc.port.empty());
  10894. EXPECT_EQ("/ws", uc.path);
  10895. }
  10896. }
  10897. TEST(ParseUrlTest, QueryOnly) {
  10898. detail::UrlComponents uc;
  10899. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10900. EXPECT_TRUE(uc.host.empty());
  10901. EXPECT_TRUE(uc.path.empty());
  10902. EXPECT_EQ("?q=1&r=2", uc.query);
  10903. }
  10904. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10905. detail::UrlComponents uc;
  10906. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10907. EXPECT_TRUE(uc.scheme.empty());
  10908. EXPECT_EQ("example.com", uc.host);
  10909. EXPECT_EQ("443", uc.port);
  10910. EXPECT_EQ("/path", uc.path);
  10911. }
  10912. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10913. // If ipv6 regex working, regex match codepath is taken.
  10914. // else port will default to 80 in Client impl
  10915. int clientImplMagicPort = 80;
  10916. int port = 4321;
  10917. // above ports must be different to avoid false negative
  10918. EXPECT_NE(clientImplMagicPort, port);
  10919. std::string ipV6TestURL = "http://[ff06::c3]";
  10920. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10921. CLIENT_PRIVATE_KEY_FILE);
  10922. EXPECT_EQ(cli.port(), port);
  10923. }
  10924. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10925. auto file_path = "./www/dir/index.html";
  10926. auto dir_path = "./www/dir";
  10927. detail::FileStat stat_file(file_path);
  10928. EXPECT_TRUE(stat_file.is_file());
  10929. EXPECT_FALSE(stat_file.is_dir());
  10930. detail::FileStat stat_dir(dir_path);
  10931. EXPECT_FALSE(stat_dir.is_file());
  10932. EXPECT_TRUE(stat_dir.is_dir());
  10933. }
  10934. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10935. // IPv4 with default HTTP port (80)
  10936. EXPECT_EQ("example.com",
  10937. detail::make_host_and_port_string("example.com", 80, false));
  10938. // IPv4 with default HTTPS port (443)
  10939. EXPECT_EQ("example.com",
  10940. detail::make_host_and_port_string("example.com", 443, true));
  10941. // IPv4 with non-default HTTP port
  10942. EXPECT_EQ("example.com:8080",
  10943. detail::make_host_and_port_string("example.com", 8080, false));
  10944. // IPv4 with non-default HTTPS port
  10945. EXPECT_EQ("example.com:8443",
  10946. detail::make_host_and_port_string("example.com", 8443, true));
  10947. // IPv6 with default HTTP port (80)
  10948. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10949. // IPv6 with default HTTPS port (443)
  10950. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10951. // IPv6 with non-default HTTP port
  10952. EXPECT_EQ("[::1]:8080",
  10953. detail::make_host_and_port_string("::1", 8080, false));
  10954. // IPv6 with non-default HTTPS port
  10955. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10956. // IPv6 full address with default port
  10957. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10958. detail::make_host_and_port_string(
  10959. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10960. // IPv6 full address with non-default port
  10961. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10962. detail::make_host_and_port_string(
  10963. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10964. // IPv6 localhost with non-default port
  10965. EXPECT_EQ("[::1]:3000",
  10966. detail::make_host_and_port_string("::1", 3000, false));
  10967. // IPv6 with zone ID (link-local address) with default port
  10968. EXPECT_EQ("[fe80::1%eth0]",
  10969. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10970. // IPv6 with zone ID (link-local address) with non-default port
  10971. EXPECT_EQ("[fe80::1%eth0]:8080",
  10972. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10973. // Edge case: Port 443 with is_ssl=false (should add port)
  10974. EXPECT_EQ("example.com:443",
  10975. detail::make_host_and_port_string("example.com", 443, false));
  10976. // Edge case: Port 80 with is_ssl=true (should add port)
  10977. EXPECT_EQ("example.com:80",
  10978. detail::make_host_and_port_string("example.com", 80, true));
  10979. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10980. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10981. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10982. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10983. // Security fix: Already bracketed IPv6 should not get double brackets
  10984. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10985. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10986. EXPECT_EQ("[::1]:8080",
  10987. detail::make_host_and_port_string("[::1]", 8080, false));
  10988. EXPECT_EQ("[2001:db8::1]:8080",
  10989. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10990. EXPECT_EQ("[fe80::1%eth0]",
  10991. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10992. EXPECT_EQ("[fe80::1%eth0]:8080",
  10993. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10994. // Edge case: Empty host (should return as-is)
  10995. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10996. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10997. // This is a known limitation but shouldn't crash
  10998. EXPECT_EQ("[host:name]",
  10999. detail::make_host_and_port_string("host:name", 80, false));
  11000. // Port number edge cases (no validation, but should not crash)
  11001. EXPECT_EQ("example.com:0",
  11002. detail::make_host_and_port_string("example.com", 0, false));
  11003. EXPECT_EQ("example.com:-1",
  11004. detail::make_host_and_port_string("example.com", -1, false));
  11005. EXPECT_EQ("example.com:65535",
  11006. detail::make_host_and_port_string("example.com", 65535, false));
  11007. EXPECT_EQ("example.com:65536",
  11008. detail::make_host_and_port_string("example.com", 65536, false));
  11009. }
  11010. #ifdef CPPHTTPLIB_SSL_ENABLED
  11011. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11012. httplib::SSLClient cli("roblox.com", 443);
  11013. cli.set_follow_location(true);
  11014. auto res = cli.Get("/");
  11015. ASSERT_TRUE(res);
  11016. EXPECT_EQ(StatusCode::OK_200, res->status);
  11017. }
  11018. #endif
  11019. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11020. Server svr;
  11021. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11022. EXPECT_EQ(res.status, 400);
  11023. });
  11024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. thread.join();
  11028. ASSERT_FALSE(svr.is_running());
  11029. });
  11030. svr.wait_until_ready();
  11031. Client cli(HOST, PORT);
  11032. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11033. }
  11034. TEST(InvalidHeaderCharsTest, is_field_name) {
  11035. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11036. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11037. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11038. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11039. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11040. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11041. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11042. EXPECT_FALSE(detail::fields::is_field_name(""));
  11043. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11044. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11045. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11046. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11047. }
  11048. TEST(InvalidHeaderCharsTest, is_field_value) {
  11049. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11050. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11051. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11052. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11053. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11054. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11055. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11056. EXPECT_TRUE(detail::fields::is_field_value(""));
  11057. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11058. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11059. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11060. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11061. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11062. }
  11063. TEST(InvalidHeaderCharsTest, OnServer) {
  11064. Server svr;
  11065. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11066. std::string header = "Not Set";
  11067. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11068. res.set_header(header, "value");
  11069. res.set_content("Page Content Page Content", "text/plain");
  11070. });
  11071. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11072. std::string header = "Not Set";
  11073. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11074. res.set_header("X-Test", header);
  11075. res.set_content("Page Content Page Content", "text/plain");
  11076. });
  11077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11078. auto se = detail::scope_exit([&] {
  11079. svr.stop();
  11080. thread.join();
  11081. ASSERT_FALSE(svr.is_running());
  11082. });
  11083. svr.wait_until_ready();
  11084. Client cli(HOST, PORT);
  11085. {
  11086. auto res = cli.Get(
  11087. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11088. ASSERT_TRUE(res);
  11089. EXPECT_EQ("Page Content Page Content", res->body);
  11090. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11091. }
  11092. {
  11093. auto res = cli.Get(
  11094. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11095. ASSERT_TRUE(res);
  11096. EXPECT_EQ("Page Content Page Content", res->body);
  11097. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11098. }
  11099. }
  11100. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11101. auto handled = false;
  11102. Server svr;
  11103. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11104. thread t = thread([&] { svr.listen(HOST, PORT); });
  11105. auto se = detail::scope_exit([&] {
  11106. svr.stop();
  11107. t.join();
  11108. ASSERT_FALSE(svr.is_running());
  11109. ASSERT_FALSE(handled);
  11110. });
  11111. svr.wait_until_ready();
  11112. auto req = "POST /test HTTP/1.1\r\n"
  11113. "Content-Length: x\r\n"
  11114. "\r\n";
  11115. std::string response;
  11116. ASSERT_TRUE(send_request(1, req, &response));
  11117. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11118. response.substr(0, response.find("\r\n")));
  11119. }
  11120. #ifndef _WIN32
  11121. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11122. static constexpr char reject[] = "Unauthorized";
  11123. static constexpr char accept[] = "Upload accepted";
  11124. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11125. Server svr;
  11126. svr.set_expect_100_continue_handler(
  11127. [](const Request & /*req*/, Response &res) {
  11128. res.status = StatusCode::Unauthorized_401;
  11129. res.set_content(reject, "text/plain");
  11130. return res.status;
  11131. });
  11132. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11133. res.set_content(accept, "text/plain");
  11134. });
  11135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. {
  11143. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11144. curl_easy_init(), &curl_easy_cleanup};
  11145. ASSERT_NE(curl, nullptr);
  11146. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11147. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11148. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11149. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11150. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11151. &curl_slist_free_all};
  11152. ASSERT_NE(list, nullptr);
  11153. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11154. struct read_data {
  11155. size_t read_size;
  11156. size_t total_size;
  11157. } data = {0, total_size};
  11158. using read_callback_t =
  11159. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11160. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11161. void *userdata) -> size_t {
  11162. read_data *d = (read_data *)userdata;
  11163. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11164. std::fill_n(ptr, size * nmemb, 'A');
  11165. d->read_size += size * nmemb;
  11166. return size * nmemb;
  11167. };
  11168. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11169. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11170. std::vector<char> buffer;
  11171. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11172. using write_callback_t =
  11173. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11174. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11175. void *userdata) -> size_t {
  11176. std::vector<char> *buf = (std::vector<char> *)userdata;
  11177. buf->reserve(buf->size() + size * nmemb + 1);
  11178. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11179. return size * nmemb;
  11180. };
  11181. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11182. {
  11183. const auto res = curl_easy_perform(curl.get());
  11184. ASSERT_EQ(res, CURLE_OK);
  11185. }
  11186. {
  11187. auto response_code = long{};
  11188. const auto res =
  11189. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11190. ASSERT_EQ(res, CURLE_OK);
  11191. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11192. }
  11193. {
  11194. auto dl = curl_off_t{};
  11195. const auto res =
  11196. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11197. ASSERT_EQ(res, CURLE_OK);
  11198. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11199. }
  11200. {
  11201. buffer.push_back('\0');
  11202. ASSERT_STRCASEEQ(buffer.data(), reject);
  11203. }
  11204. }
  11205. }
  11206. #endif
  11207. template <typename S, typename C>
  11208. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11209. svr.Get("/stream", [&](const Request &, Response &res) {
  11210. auto data = new std::string("01234567890123456789");
  11211. res.set_content_provider(
  11212. data->size(), "text/plain",
  11213. [&, data](size_t offset, size_t length, DataSink &sink) {
  11214. const size_t DATA_CHUNK_SIZE = 4;
  11215. const auto &d = *data;
  11216. std::this_thread::sleep_for(std::chrono::seconds(1));
  11217. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11218. return true;
  11219. },
  11220. [data](bool success) {
  11221. EXPECT_FALSE(success);
  11222. delete data;
  11223. });
  11224. });
  11225. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11226. auto i = new size_t(0);
  11227. res.set_content_provider(
  11228. "text/plain",
  11229. [i](size_t, DataSink &sink) {
  11230. if (*i < 5) {
  11231. std::this_thread::sleep_for(std::chrono::seconds(1));
  11232. sink.write("abcd", 4);
  11233. (*i)++;
  11234. } else {
  11235. sink.done();
  11236. }
  11237. return true;
  11238. },
  11239. [i](bool success) {
  11240. EXPECT_FALSE(success);
  11241. delete i;
  11242. });
  11243. });
  11244. svr.Get("/chunked", [&](const Request &, Response &res) {
  11245. auto i = new size_t(0);
  11246. res.set_chunked_content_provider(
  11247. "text/plain",
  11248. [i](size_t, DataSink &sink) {
  11249. if (*i < 5) {
  11250. std::this_thread::sleep_for(std::chrono::seconds(1));
  11251. sink.os << "abcd";
  11252. (*i)++;
  11253. } else {
  11254. sink.done();
  11255. }
  11256. return true;
  11257. },
  11258. [i](bool success) {
  11259. EXPECT_FALSE(success);
  11260. delete i;
  11261. });
  11262. });
  11263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11264. auto se = detail::scope_exit([&] {
  11265. svr.stop();
  11266. listen_thread.join();
  11267. ASSERT_FALSE(svr.is_running());
  11268. });
  11269. svr.wait_until_ready();
  11270. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11271. {
  11272. auto start = std::chrono::steady_clock::now();
  11273. auto res = cli.Get("/stream");
  11274. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11275. std::chrono::steady_clock::now() - start)
  11276. .count();
  11277. ASSERT_FALSE(res);
  11278. EXPECT_EQ(Error::Read, res.error());
  11279. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11280. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11281. }
  11282. {
  11283. auto start = std::chrono::steady_clock::now();
  11284. auto res = cli.Get("/stream_without_length");
  11285. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11286. std::chrono::steady_clock::now() - start)
  11287. .count();
  11288. ASSERT_FALSE(res);
  11289. EXPECT_EQ(Error::Read, res.error());
  11290. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11291. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11292. }
  11293. {
  11294. auto start = std::chrono::steady_clock::now();
  11295. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11296. EXPECT_EQ("abcd", string(data, data_length));
  11297. return true;
  11298. });
  11299. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11300. std::chrono::steady_clock::now() - start)
  11301. .count();
  11302. ASSERT_FALSE(res);
  11303. EXPECT_EQ(Error::Read, res.error());
  11304. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11305. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11306. }
  11307. }
  11308. TEST(MaxTimeoutTest, ContentStream) {
  11309. time_t timeout = 2000;
  11310. time_t threshold = 200;
  11311. Server svr;
  11312. Client cli("localhost", PORT);
  11313. max_timeout_test(svr, cli, timeout, threshold);
  11314. }
  11315. #ifdef CPPHTTPLIB_SSL_ENABLED
  11316. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11317. time_t timeout = 2000;
  11318. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11320. SSLClient cli("localhost", PORT);
  11321. cli.enable_server_certificate_verification(false);
  11322. max_timeout_test(svr, cli, timeout, threshold);
  11323. }
  11324. #endif
  11325. class EventDispatcher {
  11326. public:
  11327. EventDispatcher() {}
  11328. bool wait_event(DataSink *sink) {
  11329. unique_lock<mutex> lk(m_);
  11330. int id = id_;
  11331. // Wait with timeout to prevent hanging if client disconnects
  11332. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11333. [&] { return cid_ == id; })) {
  11334. return false; // Timeout occurred
  11335. }
  11336. sink->write(message_.data(), message_.size());
  11337. return true;
  11338. }
  11339. void send_event(const string &message) {
  11340. lock_guard<mutex> lk(m_);
  11341. cid_ = id_++;
  11342. message_ = message;
  11343. cv_.notify_all();
  11344. }
  11345. private:
  11346. mutex m_;
  11347. condition_variable cv_;
  11348. atomic_int id_{0};
  11349. atomic_int cid_{-1};
  11350. string message_;
  11351. };
  11352. TEST(ClientInThreadTest, Issue2068) {
  11353. EventDispatcher ed;
  11354. Server svr;
  11355. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11356. res.set_chunked_content_provider("text/event-stream",
  11357. [&](size_t /*offset*/, DataSink &sink) {
  11358. return ed.wait_event(&sink);
  11359. });
  11360. });
  11361. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11362. svr.wait_until_ready();
  11363. thread event_thread([&] {
  11364. int id = 0;
  11365. while (svr.is_running()) {
  11366. this_thread::sleep_for(chrono::milliseconds(500));
  11367. std::stringstream ss;
  11368. ss << "data: " << id << "\n\n";
  11369. ed.send_event(ss.str());
  11370. id++;
  11371. }
  11372. });
  11373. auto se = detail::scope_exit([&] {
  11374. svr.stop();
  11375. listen_thread.join();
  11376. event_thread.join();
  11377. ASSERT_FALSE(svr.is_running());
  11378. });
  11379. {
  11380. auto client = detail::make_unique<Client>(HOST, PORT);
  11381. client->set_read_timeout(std::chrono::minutes(10));
  11382. std::atomic<bool> stop{false};
  11383. std::thread t([&] {
  11384. client->Get("/event1",
  11385. [&](const char *, size_t) -> bool { return !stop; });
  11386. });
  11387. std::this_thread::sleep_for(std::chrono::seconds(2));
  11388. stop = true;
  11389. client->stop();
  11390. t.join();
  11391. // Reset client after thread has finished
  11392. client.reset();
  11393. }
  11394. }
  11395. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11396. auto handled = false;
  11397. Server svr;
  11398. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11400. auto se = detail::scope_exit([&] {
  11401. svr.stop();
  11402. t.join();
  11403. ASSERT_FALSE(svr.is_running());
  11404. ASSERT_FALSE(handled);
  11405. });
  11406. svr.wait_until_ready();
  11407. // Two Content-Length headers with different values — must be rejected
  11408. auto req = "POST /test HTTP/1.1\r\n"
  11409. "Content-Length: 5\r\n"
  11410. "Content-Length: 10\r\n"
  11411. "\r\n"
  11412. "hello";
  11413. std::string response;
  11414. ASSERT_TRUE(send_request(1, req, &response));
  11415. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11416. response.substr(0, response.find("\r\n")));
  11417. }
  11418. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11419. auto handled = false;
  11420. Server svr;
  11421. svr.Post("/test", [&](const Request &, Response &res) {
  11422. handled = true;
  11423. res.set_content("ok", "text/plain");
  11424. });
  11425. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11426. auto se = detail::scope_exit([&] {
  11427. svr.stop();
  11428. t.join();
  11429. ASSERT_FALSE(svr.is_running());
  11430. ASSERT_TRUE(handled);
  11431. });
  11432. svr.wait_until_ready();
  11433. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11434. auto req = "POST /test HTTP/1.1\r\n"
  11435. "Content-Length: 5\r\n"
  11436. "Content-Length: 5\r\n"
  11437. "\r\n"
  11438. "hello";
  11439. std::string response;
  11440. ASSERT_TRUE(send_request(1, req, &response));
  11441. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11442. }
  11443. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11444. Server svr;
  11445. svr.Get("/", [](const Request &req, Response &res) {
  11446. EXPECT_EQ(2U, req.trailers.size());
  11447. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11448. // Denied
  11449. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11450. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11451. // Accepted
  11452. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11453. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11454. EXPECT_TRUE(req.has_trailer("X-World"));
  11455. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11456. res.set_content("ok", "text/plain");
  11457. });
  11458. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11459. auto se = detail::scope_exit([&] {
  11460. svr.stop();
  11461. t.join();
  11462. ASSERT_FALSE(svr.is_running());
  11463. });
  11464. svr.wait_until_ready();
  11465. const std::string req = "GET / HTTP/1.1\r\n"
  11466. "Transfer-Encoding: chunked\r\n"
  11467. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11468. "\r\n"
  11469. "0\r\n"
  11470. "Content-Length: 10\r\n"
  11471. "Host: internal.local\r\n"
  11472. "Content-Type: malicious/content\r\n"
  11473. "Cookie: any\r\n"
  11474. "Set-Cookie: any\r\n"
  11475. "X-Forwarded-For: attacker.com\r\n"
  11476. "X-Real-Ip: 1.1.1.1\r\n"
  11477. "X-Hello: hello\r\n"
  11478. "X-World: world\r\n"
  11479. "\r\n";
  11480. std::string res;
  11481. ASSERT_TRUE(send_request(1, req, &res));
  11482. }
  11483. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11484. Server svr;
  11485. std::string observed_remote_addr;
  11486. std::string observed_xff;
  11487. svr.Get("/ip", [&](const Request &req, Response &res) {
  11488. observed_remote_addr = req.remote_addr;
  11489. observed_xff = req.get_header_value("X-Forwarded-For");
  11490. res.set_content("ok", "text/plain");
  11491. });
  11492. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11493. auto se = detail::scope_exit([&] {
  11494. svr.stop();
  11495. t.join();
  11496. ASSERT_FALSE(svr.is_running());
  11497. });
  11498. svr.wait_until_ready();
  11499. Client cli(HOST, PORT);
  11500. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11501. ASSERT_TRUE(res);
  11502. EXPECT_EQ(StatusCode::OK_200, res->status);
  11503. EXPECT_EQ(observed_xff, "203.0.113.66");
  11504. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11505. observed_remote_addr == "127.0.0.1");
  11506. }
  11507. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11508. Server svr;
  11509. svr.set_trusted_proxies({"203.0.113.66"});
  11510. std::string observed_remote_addr;
  11511. std::string observed_xff;
  11512. svr.Get("/ip", [&](const Request &req, Response &res) {
  11513. observed_remote_addr = req.remote_addr;
  11514. observed_xff = req.get_header_value("X-Forwarded-For");
  11515. res.set_content("ok", "text/plain");
  11516. });
  11517. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11518. auto se = detail::scope_exit([&] {
  11519. svr.stop();
  11520. t.join();
  11521. ASSERT_FALSE(svr.is_running());
  11522. });
  11523. svr.wait_until_ready();
  11524. Client cli(HOST, PORT);
  11525. auto res = cli.Get("/ip");
  11526. ASSERT_TRUE(res);
  11527. EXPECT_EQ(StatusCode::OK_200, res->status);
  11528. EXPECT_EQ(observed_xff, "");
  11529. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11530. observed_remote_addr == "127.0.0.1");
  11531. }
  11532. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11533. Server svr;
  11534. svr.set_trusted_proxies({"203.0.113.66"});
  11535. std::string observed_remote_addr;
  11536. std::string observed_xff;
  11537. svr.Get("/ip", [&](const Request &req, Response &res) {
  11538. observed_remote_addr = req.remote_addr;
  11539. observed_xff = req.get_header_value("X-Forwarded-For");
  11540. res.set_content("ok", "text/plain");
  11541. });
  11542. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11543. auto se = detail::scope_exit([&] {
  11544. svr.stop();
  11545. t.join();
  11546. ASSERT_FALSE(svr.is_running());
  11547. });
  11548. svr.wait_until_ready();
  11549. Client cli(HOST, PORT);
  11550. auto res =
  11551. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11552. ASSERT_TRUE(res);
  11553. EXPECT_EQ(StatusCode::OK_200, res->status);
  11554. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11555. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11556. }
  11557. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11558. Server svr;
  11559. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11560. std::string observed_remote_addr;
  11561. std::string observed_xff;
  11562. svr.Get("/ip", [&](const Request &req, Response &res) {
  11563. observed_remote_addr = req.remote_addr;
  11564. observed_xff = req.get_header_value("X-Forwarded-For");
  11565. res.set_content("ok", "text/plain");
  11566. });
  11567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11568. auto se = detail::scope_exit([&] {
  11569. svr.stop();
  11570. t.join();
  11571. ASSERT_FALSE(svr.is_running());
  11572. });
  11573. svr.wait_until_ready();
  11574. Client cli(HOST, PORT);
  11575. auto res = cli.Get(
  11576. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11577. ASSERT_TRUE(res);
  11578. EXPECT_EQ(StatusCode::OK_200, res->status);
  11579. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11580. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11581. }
  11582. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11583. Server svr;
  11584. svr.set_trusted_proxies({"192.0.2.45"});
  11585. std::string observed_remote_addr;
  11586. std::string observed_xff;
  11587. svr.Get("/ip", [&](const Request &req, Response &res) {
  11588. observed_remote_addr = req.remote_addr;
  11589. observed_xff = req.get_header_value("X-Forwarded-For");
  11590. res.set_content("ok", "text/plain");
  11591. });
  11592. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11593. auto se = detail::scope_exit([&] {
  11594. svr.stop();
  11595. t.join();
  11596. ASSERT_FALSE(svr.is_running());
  11597. });
  11598. svr.wait_until_ready();
  11599. Client cli(HOST, PORT);
  11600. auto res =
  11601. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11602. ASSERT_TRUE(res);
  11603. EXPECT_EQ(StatusCode::OK_200, res->status);
  11604. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11605. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11606. }
  11607. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11608. Server svr;
  11609. svr.set_trusted_proxies({"192.0.2.45"});
  11610. std::string observed_remote_addr;
  11611. std::string observed_xff;
  11612. svr.Get("/ip", [&](const Request &req, Response &res) {
  11613. observed_remote_addr = req.remote_addr;
  11614. observed_xff = req.get_header_value("X-Forwarded-For");
  11615. res.set_content("ok", "text/plain");
  11616. });
  11617. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11618. auto se = detail::scope_exit([&] {
  11619. svr.stop();
  11620. t.join();
  11621. ASSERT_FALSE(svr.is_running());
  11622. });
  11623. svr.wait_until_ready();
  11624. Client cli(HOST, PORT);
  11625. auto res = cli.Get(
  11626. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11627. ASSERT_TRUE(res);
  11628. EXPECT_EQ(StatusCode::OK_200, res->status);
  11629. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11630. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11631. }
  11632. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11633. Server svr;
  11634. svr.set_trusted_proxies({"192.0.2.45"});
  11635. std::string observed_remote_addr;
  11636. std::string observed_xff;
  11637. svr.Get("/ip", [&](const Request &req, Response &res) {
  11638. observed_remote_addr = req.remote_addr;
  11639. observed_xff = req.get_header_value("X-Forwarded-For");
  11640. res.set_content("ok", "text/plain");
  11641. });
  11642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11643. auto se = detail::scope_exit([&] {
  11644. svr.stop();
  11645. t.join();
  11646. ASSERT_FALSE(svr.is_running());
  11647. });
  11648. svr.wait_until_ready();
  11649. std::string raw_req =
  11650. "GET /ip HTTP/1.1\r\n"
  11651. "Host: localhost\r\n"
  11652. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11653. "Connection: close\r\n"
  11654. "\r\n";
  11655. std::string out;
  11656. ASSERT_TRUE(send_request(5, raw_req, &out));
  11657. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11658. // Header parser trims surrounding whitespace of the header value
  11659. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11660. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11661. }
  11662. #ifndef _WIN32
  11663. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11664. Server svr;
  11665. svr.Post("/post", [&](const Request &req, Response &res) {
  11666. res.set_content(req.body, "text/plain");
  11667. });
  11668. svr.Put("/put", [&](const Request &req, Response &res) {
  11669. res.set_content(req.body, "text/plain");
  11670. });
  11671. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11672. res.set_content(req.body, "text/plain");
  11673. });
  11674. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11675. res.set_content(req.body, "text/plain");
  11676. });
  11677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11678. auto se = detail::scope_exit([&] {
  11679. svr.stop();
  11680. t.join();
  11681. ASSERT_FALSE(svr.is_running());
  11682. });
  11683. svr.wait_until_ready();
  11684. std::string resp;
  11685. // POST without Content-Length
  11686. ASSERT_TRUE(send_request(5,
  11687. "POST /post HTTP/1.1\r\n"
  11688. "Host: localhost\r\n"
  11689. "Connection: close\r\n"
  11690. "\r\n",
  11691. &resp));
  11692. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11693. // PUT without Content-Length
  11694. resp.clear();
  11695. ASSERT_TRUE(send_request(5,
  11696. "PUT /put HTTP/1.1\r\n"
  11697. "Host: localhost\r\n"
  11698. "Connection: close\r\n"
  11699. "\r\n",
  11700. &resp));
  11701. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11702. // PATCH without Content-Length
  11703. resp.clear();
  11704. ASSERT_TRUE(send_request(5,
  11705. "PATCH /patch HTTP/1.1\r\n"
  11706. "Host: localhost\r\n"
  11707. "Connection: close\r\n"
  11708. "\r\n",
  11709. &resp));
  11710. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11711. // DELETE without Content-Length
  11712. resp.clear();
  11713. ASSERT_TRUE(send_request(5,
  11714. "DELETE /delete HTTP/1.1\r\n"
  11715. "Host: localhost\r\n"
  11716. "Connection: close\r\n"
  11717. "\r\n",
  11718. &resp));
  11719. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11720. }
  11721. #endif
  11722. //==============================================================================
  11723. // open_stream() Tests
  11724. //==============================================================================
  11725. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11726. std::string result;
  11727. char buf[8192];
  11728. ssize_t n;
  11729. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11730. result.append(buf, static_cast<size_t>(n));
  11731. }
  11732. return result;
  11733. }
  11734. // Mock stream for unit tests
  11735. class MockStream : public Stream {
  11736. public:
  11737. std::string data;
  11738. size_t pos = 0;
  11739. ssize_t error_after = -1; // -1 = no error
  11740. explicit MockStream(const std::string &d, ssize_t err = -1)
  11741. : data(d), error_after(err) {}
  11742. bool is_readable() const override { return true; }
  11743. bool wait_readable() const override { return true; }
  11744. bool wait_writable() const override { return true; }
  11745. ssize_t read(char *ptr, size_t size) override {
  11746. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11747. if (pos >= data.size()) return 0;
  11748. size_t limit =
  11749. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11750. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11751. std::memcpy(ptr, data.data() + pos, to_read);
  11752. pos += to_read;
  11753. return static_cast<ssize_t>(to_read);
  11754. }
  11755. ssize_t write(const char *, size_t) override { return -1; }
  11756. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11757. ip = "127.0.0.1";
  11758. port = 0;
  11759. }
  11760. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11761. ip = "127.0.0.1";
  11762. port = 0;
  11763. }
  11764. socket_t socket() const override { return INVALID_SOCKET; }
  11765. time_t duration() const override { return 0; }
  11766. };
  11767. TEST(StreamHandleTest, Basic) {
  11768. ClientImpl::StreamHandle handle;
  11769. EXPECT_FALSE(handle.is_valid());
  11770. handle.response = detail::make_unique<Response>();
  11771. handle.error = Error::Connection;
  11772. EXPECT_FALSE(handle.is_valid());
  11773. handle.error = Error::Success;
  11774. EXPECT_TRUE(handle.is_valid());
  11775. }
  11776. TEST(BodyReaderTest, Basic) {
  11777. MockStream stream("Hello, World!");
  11778. detail::BodyReader reader;
  11779. reader.stream = &stream;
  11780. reader.content_length = 13;
  11781. char buf[32];
  11782. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11783. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11784. EXPECT_TRUE(reader.eof);
  11785. }
  11786. TEST(BodyReaderTest, NoStream) {
  11787. detail::BodyReader reader;
  11788. char buf[32];
  11789. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11790. EXPECT_EQ(Error::Connection, reader.last_error);
  11791. }
  11792. TEST(BodyReaderTest, Error) {
  11793. MockStream stream("Hello, World!", 5);
  11794. detail::BodyReader reader;
  11795. reader.stream = &stream;
  11796. reader.content_length = 13;
  11797. char buf[32];
  11798. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11799. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11800. EXPECT_EQ(Error::Read, reader.last_error);
  11801. }
  11802. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11803. // Mock-based StreamHandle tests relying on private internals are removed.
  11804. class OpenStreamTest : public ::testing::Test {
  11805. protected:
  11806. void SetUp() override {
  11807. svr_.Get("/hello", [](const Request &, Response &res) {
  11808. res.set_content("Hello World!", "text/plain");
  11809. });
  11810. svr_.Get("/large", [](const Request &, Response &res) {
  11811. res.set_content(std::string(10000, 'X'), "text/plain");
  11812. });
  11813. svr_.Get("/chunked", [](const Request &, Response &res) {
  11814. res.set_chunked_content_provider("text/plain",
  11815. [](size_t offset, DataSink &sink) {
  11816. if (offset < 15) {
  11817. sink.write("chunk", 5);
  11818. return true;
  11819. }
  11820. sink.done();
  11821. return true;
  11822. });
  11823. });
  11824. svr_.Get("/compressible", [](const Request &, Response &res) {
  11825. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11826. DataSink &sink) {
  11827. if (offset < 100 * 1024) {
  11828. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11829. sink.write(chunk.data(), chunk.size());
  11830. return true;
  11831. }
  11832. sink.done();
  11833. return true;
  11834. });
  11835. });
  11836. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11837. [](const Request & /*req*/, Response &res) {
  11838. auto i = new int(0);
  11839. res.set_header("Trailer", "Content-Length, X-Allowed");
  11840. res.set_chunked_content_provider(
  11841. "text/plain",
  11842. [i](size_t /*offset*/, DataSink &sink) {
  11843. switch (*i) {
  11844. case 0: sink.os << "123"; break;
  11845. case 1: sink.os << "456"; break;
  11846. case 2: sink.os << "789"; break;
  11847. case 3: {
  11848. sink.done_with_trailer(
  11849. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11850. } break;
  11851. }
  11852. (*i)++;
  11853. return true;
  11854. },
  11855. [i](bool success) {
  11856. EXPECT_TRUE(success);
  11857. delete i;
  11858. });
  11859. });
  11860. // Echo headers endpoint for header-related tests
  11861. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11862. std::string body;
  11863. for (const auto &h : req.headers) {
  11864. body.append(h.first);
  11865. body.push_back(':');
  11866. body.append(h.second);
  11867. body.push_back('\n');
  11868. }
  11869. res.set_content(body, "text/plain");
  11870. });
  11871. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11872. std::string body;
  11873. for (const auto &h : req.headers) {
  11874. body.append(h.first);
  11875. body.push_back(':');
  11876. body.append(h.second);
  11877. body.push_back('\n');
  11878. }
  11879. res.set_content(body, "text/plain");
  11880. });
  11881. port_ = svr_.bind_to_any_port("127.0.0.1");
  11882. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11883. svr_.wait_until_ready();
  11884. }
  11885. void TearDown() override {
  11886. svr_.stop();
  11887. if (thread_.joinable()) thread_.join();
  11888. }
  11889. Server svr_;
  11890. std::thread thread_;
  11891. int port_ = 0;
  11892. };
  11893. TEST_F(OpenStreamTest, Basic) {
  11894. Client cli("127.0.0.1", port_);
  11895. auto handle = cli.open_stream("GET", "/hello");
  11896. EXPECT_TRUE(handle.is_valid());
  11897. EXPECT_EQ("Hello World!", read_all(handle));
  11898. }
  11899. TEST_F(OpenStreamTest, SmallBuffer) {
  11900. Client cli("127.0.0.1", port_);
  11901. auto handle = cli.open_stream("GET", "/hello");
  11902. std::string result;
  11903. char buf[4];
  11904. ssize_t n;
  11905. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11906. result.append(buf, static_cast<size_t>(n));
  11907. EXPECT_EQ("Hello World!", result);
  11908. }
  11909. TEST_F(OpenStreamTest, DefaultHeaders) {
  11910. Client cli("127.0.0.1", port_);
  11911. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11912. {
  11913. auto handle = cli.open_stream("GET", "/echo-headers");
  11914. ASSERT_TRUE(handle.is_valid());
  11915. auto body = read_all(handle);
  11916. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11917. std::string::npos);
  11918. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11919. std::string::npos);
  11920. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11921. }
  11922. // open_stream POST with body and no explicit content_type should NOT add
  11923. // text/plain Content-Type (behavior differs from non-streaming path), but
  11924. // should include Content-Length
  11925. {
  11926. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11927. ASSERT_TRUE(handle.is_valid());
  11928. auto body = read_all(handle);
  11929. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11930. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11931. }
  11932. // open_stream POST with explicit Content-Type should preserve it
  11933. {
  11934. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11935. {{"Content-Type", "application/custom"}},
  11936. "{}", "application/custom");
  11937. ASSERT_TRUE(handle.is_valid());
  11938. auto body = read_all(handle);
  11939. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11940. }
  11941. // User-specified User-Agent must not be overwritten for stream API
  11942. {
  11943. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11944. {{"User-Agent", "MyAgent/1.2"}});
  11945. ASSERT_TRUE(handle.is_valid());
  11946. auto body = read_all(handle);
  11947. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11948. }
  11949. }
  11950. TEST_F(OpenStreamTest, Large) {
  11951. Client cli("127.0.0.1", port_);
  11952. auto handle = cli.open_stream("GET", "/large");
  11953. EXPECT_EQ(10000u, read_all(handle).size());
  11954. }
  11955. TEST_F(OpenStreamTest, ConnectionError) {
  11956. Client cli("127.0.0.1", 9999);
  11957. auto handle = cli.open_stream("GET", "/hello");
  11958. EXPECT_FALSE(handle.is_valid());
  11959. }
  11960. TEST_F(OpenStreamTest, Chunked) {
  11961. Client cli("127.0.0.1", port_);
  11962. auto handle = cli.open_stream("GET", "/chunked");
  11963. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11964. "Transfer-Encoding") == "chunked");
  11965. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11966. }
  11967. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11968. Client cli("127.0.0.1", port_);
  11969. auto handle =
  11970. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11971. ASSERT_TRUE(handle.is_valid());
  11972. // Consume body to allow trailers to be received/parsed
  11973. auto body = read_all(handle);
  11974. // Explicitly parse trailers (ensure trailers are available for assertion)
  11975. handle.parse_trailers_if_needed();
  11976. EXPECT_EQ(std::string("123456789"), body);
  11977. // The response should include a Trailer header declaring both names
  11978. ASSERT_TRUE(handle.response);
  11979. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11980. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11981. handle.response->get_header_value("Trailer"));
  11982. // Prohibited trailer must not be present
  11983. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11984. // Allowed trailer should be present
  11985. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11986. EXPECT_EQ(std::string("yes"),
  11987. handle.response->get_trailer_value("X-Allowed"));
  11988. // Verify trailers are NOT present as regular headers
  11989. EXPECT_EQ(std::string(""),
  11990. handle.response->get_header_value("Content-Length"));
  11991. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11992. }
  11993. static std::thread serve_single_response(std::promise<int> &port_promise,
  11994. const std::string &response) {
  11995. return std::thread([&port_promise, response] {
  11996. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11997. default_socket_options(srv);
  11998. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11999. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12000. sockaddr_in addr{};
  12001. addr.sin_family = AF_INET;
  12002. addr.sin_port = htons(0); // Let OS assign a free port
  12003. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12004. int opt = 1;
  12005. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12006. #ifdef _WIN32
  12007. reinterpret_cast<const char *>(&opt),
  12008. #else
  12009. &opt,
  12010. #endif
  12011. sizeof(opt));
  12012. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12013. ::listen(srv, 1) != 0) {
  12014. port_promise.set_value(-1);
  12015. detail::close_socket(srv);
  12016. return;
  12017. }
  12018. socklen_t addr_len = sizeof(addr);
  12019. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12020. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12021. sockaddr_in cli_addr{};
  12022. socklen_t cli_len = sizeof(cli_addr);
  12023. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12024. if (cli != INVALID_SOCKET) {
  12025. // Read the complete HTTP request (until the blank line that terminates
  12026. // headers) before sending the response. If the server closes the socket
  12027. // while the client's request data is still unread in the kernel receive
  12028. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12029. // connection on both sides: it discards the client's receive buffer
  12030. // (which already holds our response) and causes any in-progress write on
  12031. // the client to fail with ECONNRESET. Reading all request data first
  12032. // ensures close() emits a graceful FIN.
  12033. {
  12034. char rbuf[256];
  12035. std::string req;
  12036. while (req.find("\r\n\r\n") == std::string::npos) {
  12037. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12038. if (n <= 0) { break; }
  12039. req.append(rbuf, static_cast<size_t>(n));
  12040. }
  12041. }
  12042. ::send(cli,
  12043. #ifdef _WIN32
  12044. static_cast<const char *>(response.c_str()),
  12045. static_cast<int>(response.size()),
  12046. #else
  12047. response.c_str(), response.size(),
  12048. #endif
  12049. 0);
  12050. detail::close_socket(cli);
  12051. }
  12052. detail::close_socket(srv);
  12053. });
  12054. }
  12055. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12056. #ifndef _WIN32
  12057. signal(SIGPIPE, SIG_IGN);
  12058. #endif
  12059. std::promise<int> port_promise;
  12060. auto port_future = port_promise.get_future();
  12061. auto server_thread =
  12062. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12063. "Content-Type: text/plain\r\n"
  12064. "Content-Length: not-a-number\r\n"
  12065. "Connection: close\r\n"
  12066. "\r\n"
  12067. "hello");
  12068. auto port = port_future.get();
  12069. ASSERT_GT(port, 0);
  12070. Client cli("127.0.0.1", port);
  12071. auto handle = cli.open_stream("GET", "/");
  12072. EXPECT_FALSE(handle.is_valid());
  12073. server_thread.join();
  12074. }
  12075. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12076. #ifndef _WIN32
  12077. signal(SIGPIPE, SIG_IGN);
  12078. #endif
  12079. std::promise<int> port_promise;
  12080. auto port_future = port_promise.get_future();
  12081. auto server_thread = serve_single_response(
  12082. port_promise, "HTTP/1.1 200 OK\r\n"
  12083. "Content-Type: text/plain\r\n"
  12084. "Content-Length: 99999999999999999999999999\r\n"
  12085. "Connection: close\r\n"
  12086. "\r\n"
  12087. "hello");
  12088. auto port = port_future.get();
  12089. ASSERT_GT(port, 0);
  12090. // Before the fix, std::stoull would throw std::out_of_range here and
  12091. // crash the process. After the fix, strtoull silently clamps to
  12092. // ULLONG_MAX so the stream opens without crashing. The important thing
  12093. // is that the process does NOT terminate.
  12094. Client cli("127.0.0.1", port);
  12095. auto handle = cli.open_stream("GET", "/");
  12096. EXPECT_TRUE(handle.is_valid());
  12097. server_thread.join();
  12098. }
  12099. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12100. TEST_F(OpenStreamTest, Gzip) {
  12101. Client cli("127.0.0.1", port_);
  12102. auto handle = cli.open_stream("GET", "/compressible", {},
  12103. {{"Accept-Encoding", "gzip"}});
  12104. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12105. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12106. }
  12107. #endif
  12108. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12109. TEST_F(OpenStreamTest, Brotli) {
  12110. Client cli("127.0.0.1", port_);
  12111. auto handle =
  12112. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12113. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12114. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12115. }
  12116. #endif
  12117. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12118. TEST_F(OpenStreamTest, Zstd) {
  12119. Client cli("127.0.0.1", port_);
  12120. auto handle = cli.open_stream("GET", "/compressible", {},
  12121. {{"Accept-Encoding", "zstd"}});
  12122. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12123. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12124. }
  12125. #endif
  12126. #ifdef CPPHTTPLIB_SSL_ENABLED
  12127. class SSLOpenStreamTest : public ::testing::Test {
  12128. protected:
  12129. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12130. void SetUp() override {
  12131. svr_.Get("/hello", [](const Request &, Response &res) {
  12132. res.set_content("Hello SSL World!", "text/plain");
  12133. });
  12134. svr_.Get("/chunked", [](const Request &, Response &res) {
  12135. res.set_chunked_content_provider("text/plain",
  12136. [](size_t offset, DataSink &sink) {
  12137. if (offset < 15) {
  12138. sink.write("chunk", 5);
  12139. return true;
  12140. }
  12141. sink.done();
  12142. return true;
  12143. });
  12144. });
  12145. svr_.Post("/echo", [](const Request &req, Response &res) {
  12146. res.set_content(req.body, req.get_header_value("Content-Type"));
  12147. });
  12148. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12149. std::string body = req.body;
  12150. res.set_chunked_content_provider(
  12151. "text/plain", [body](size_t offset, DataSink &sink) {
  12152. if (offset < body.size()) {
  12153. sink.write(body.data() + offset, body.size() - offset);
  12154. }
  12155. sink.done();
  12156. return true;
  12157. });
  12158. });
  12159. port_ = svr_.bind_to_any_port("127.0.0.1");
  12160. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12161. svr_.wait_until_ready();
  12162. }
  12163. void TearDown() override {
  12164. svr_.stop();
  12165. if (thread_.joinable()) thread_.join();
  12166. }
  12167. SSLServer svr_;
  12168. std::thread thread_;
  12169. int port_ = 0;
  12170. };
  12171. TEST_F(SSLOpenStreamTest, Basic) {
  12172. SSLClient cli("127.0.0.1", port_);
  12173. cli.enable_server_certificate_verification(false);
  12174. auto handle = cli.open_stream("GET", "/hello");
  12175. ASSERT_TRUE(handle.is_valid());
  12176. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12177. }
  12178. TEST_F(SSLOpenStreamTest, Chunked) {
  12179. SSLClient cli("127.0.0.1", port_);
  12180. cli.enable_server_certificate_verification(false);
  12181. auto handle = cli.open_stream("GET", "/chunked");
  12182. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12183. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12184. "Transfer-Encoding") == "chunked");
  12185. auto body = read_all(handle);
  12186. EXPECT_EQ("chunkchunkchunk", body);
  12187. }
  12188. TEST_F(SSLOpenStreamTest, Post) {
  12189. SSLClient cli("127.0.0.1", port_);
  12190. cli.enable_server_certificate_verification(false);
  12191. auto handle =
  12192. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12193. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12194. EXPECT_EQ(200, handle.response->status);
  12195. auto body = read_all(handle);
  12196. EXPECT_EQ("Hello SSL POST", body);
  12197. }
  12198. TEST_F(SSLOpenStreamTest, PostChunked) {
  12199. SSLClient cli("127.0.0.1", port_);
  12200. cli.enable_server_certificate_verification(false);
  12201. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12202. "Chunked SSL Data", "text/plain");
  12203. ASSERT_TRUE(handle.is_valid());
  12204. EXPECT_EQ(200, handle.response->status);
  12205. auto body = read_all(handle);
  12206. EXPECT_EQ("Chunked SSL Data", body);
  12207. }
  12208. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12209. // Content-Length is terminated by the server closing the connection. When the
  12210. // SSL peer sends a close_notify after the body, the client must treat it as a
  12211. // clean EOF and return a successful response rather than an error.
  12212. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12214. ASSERT_TRUE(svr.is_valid());
  12215. svr.set_keep_alive_max_count(1);
  12216. const std::string expected_body = "Hello from connection-close response!";
  12217. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12218. res.set_content_provider("text/plain",
  12219. [&](size_t offset, DataSink &sink) -> bool {
  12220. if (offset < expected_body.size()) {
  12221. sink.write(expected_body.data() + offset,
  12222. expected_body.size() - offset);
  12223. }
  12224. sink.done();
  12225. return true;
  12226. });
  12227. });
  12228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12229. auto se = detail::scope_exit([&] {
  12230. svr.stop();
  12231. listen_thread.join();
  12232. ASSERT_FALSE(svr.is_running());
  12233. });
  12234. svr.wait_until_ready();
  12235. SSLClient cli(HOST, PORT);
  12236. cli.enable_server_certificate_verification(false);
  12237. auto res = cli.Get("/no-content-length");
  12238. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12239. EXPECT_EQ(StatusCode::OK_200, res->status);
  12240. EXPECT_EQ(expected_body, res->body);
  12241. }
  12242. #endif // CPPHTTPLIB_SSL_ENABLED
  12243. //==============================================================================
  12244. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12245. // results for various scenarios.
  12246. //==============================================================================
  12247. TEST(ParityTest, GetVsOpenStream) {
  12248. Server svr;
  12249. const std::string path = "/parity";
  12250. const std::string content = "Parity test content: hello world";
  12251. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12252. res.set_content(content, "text/plain");
  12253. });
  12254. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12255. auto se = detail::scope_exit([&] {
  12256. svr.stop();
  12257. t.join();
  12258. ASSERT_FALSE(svr.is_running());
  12259. });
  12260. svr.wait_until_ready();
  12261. Client cli(HOST, PORT);
  12262. // Non-stream path
  12263. auto r1 = cli.Get(path);
  12264. ASSERT_TRUE(r1);
  12265. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12266. // Stream path
  12267. auto h = cli.open_stream("GET", path);
  12268. ASSERT_TRUE(h.is_valid());
  12269. EXPECT_EQ(r1->body, read_all(h));
  12270. }
  12271. // Helper to compress data with provided compressor type T
  12272. template <typename Compressor>
  12273. static std::string compress_payload_for_parity(const std::string &in) {
  12274. std::string out;
  12275. Compressor compressor;
  12276. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12277. [&](const char *data, size_t n) {
  12278. out.append(data, n);
  12279. return true;
  12280. });
  12281. EXPECT_TRUE(ok);
  12282. return out;
  12283. }
  12284. // Helper function for compression parity tests
  12285. template <typename Compressor>
  12286. static void test_compression_parity(const std::string &original,
  12287. const std::string &path,
  12288. const std::string &encoding) {
  12289. const std::string compressed =
  12290. compress_payload_for_parity<Compressor>(original);
  12291. Server svr;
  12292. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12293. res.set_content(compressed, "application/octet-stream");
  12294. res.set_header("Content-Encoding", encoding);
  12295. });
  12296. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12297. auto se = detail::scope_exit([&] {
  12298. svr.stop();
  12299. t.join();
  12300. ASSERT_FALSE(svr.is_running());
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, PORT);
  12304. // Non-streaming
  12305. {
  12306. auto res = cli.Get(path);
  12307. ASSERT_TRUE(res);
  12308. EXPECT_EQ(StatusCode::OK_200, res->status);
  12309. EXPECT_EQ(original, res->body);
  12310. }
  12311. // Streaming
  12312. {
  12313. auto h = cli.open_stream("GET", path);
  12314. ASSERT_TRUE(h.is_valid());
  12315. EXPECT_EQ(original, read_all(h));
  12316. }
  12317. }
  12318. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12319. TEST(ParityTest, Gzip) {
  12320. test_compression_parity<detail::gzip_compressor>(
  12321. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12322. }
  12323. #endif
  12324. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12325. TEST(ParityTest, Brotli) {
  12326. test_compression_parity<detail::brotli_compressor>(
  12327. "Hello, brotli parity test payload", "/parity-br", "br");
  12328. }
  12329. #endif
  12330. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12331. TEST(ParityTest, Zstd) {
  12332. test_compression_parity<detail::zstd_compressor>(
  12333. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12334. }
  12335. #endif
  12336. //==============================================================================
  12337. // New Stream API Tests
  12338. //==============================================================================
  12339. inline std::string read_body(httplib::stream::Result &result) {
  12340. std::string body;
  12341. while (result.next()) {
  12342. body.append(result.data(), result.size());
  12343. }
  12344. return body;
  12345. }
  12346. TEST(ClientConnectionTest, Basic) {
  12347. httplib::ClientConnection conn;
  12348. EXPECT_FALSE(conn.is_open());
  12349. conn.sock = 1;
  12350. EXPECT_TRUE(conn.is_open());
  12351. httplib::ClientConnection conn2(std::move(conn));
  12352. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12353. conn2.sock = INVALID_SOCKET;
  12354. }
  12355. // Unified test server for all stream::* tests
  12356. class StreamApiTest : public ::testing::Test {
  12357. protected:
  12358. void SetUp() override {
  12359. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12360. res.set_content("Hello World!", "text/plain");
  12361. });
  12362. svr_.Get("/echo-params",
  12363. [](const httplib::Request &req, httplib::Response &res) {
  12364. std::string r;
  12365. for (const auto &p : req.params) {
  12366. if (!r.empty()) r += "&";
  12367. r += p.first + "=" + p.second;
  12368. }
  12369. res.set_content(r, "text/plain");
  12370. });
  12371. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12372. res.set_content(req.body, req.get_header_value("Content-Type"));
  12373. });
  12374. svr_.Post("/echo-headers",
  12375. [](const httplib::Request &req, httplib::Response &res) {
  12376. std::string r;
  12377. for (const auto &h : req.headers)
  12378. r += h.first + ": " + h.second + "\n";
  12379. res.set_content(r, "text/plain");
  12380. });
  12381. svr_.Post("/echo-params",
  12382. [](const httplib::Request &req, httplib::Response &res) {
  12383. std::string r = "params:";
  12384. for (const auto &p : req.params)
  12385. r += p.first + "=" + p.second + ";";
  12386. res.set_content(r + " body:" + req.body, "text/plain");
  12387. });
  12388. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12389. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12390. });
  12391. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12392. res.set_content("PUT:" + req.body, "text/plain");
  12393. });
  12394. svr_.Patch("/echo",
  12395. [](const httplib::Request &req, httplib::Response &res) {
  12396. res.set_content("PATCH:" + req.body, "text/plain");
  12397. });
  12398. svr_.Delete(
  12399. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12400. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12401. "text/plain");
  12402. });
  12403. svr_.Get("/head-test",
  12404. [](const httplib::Request &, httplib::Response &res) {
  12405. res.set_content("body for HEAD", "text/plain");
  12406. });
  12407. svr_.Options("/options",
  12408. [](const httplib::Request &, httplib::Response &res) {
  12409. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12410. });
  12411. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12412. svr_.wait_until_ready();
  12413. }
  12414. void TearDown() override {
  12415. svr_.stop();
  12416. if (thread_.joinable()) thread_.join();
  12417. }
  12418. httplib::Server svr_;
  12419. std::thread thread_;
  12420. };
  12421. // stream::Get tests
  12422. TEST_F(StreamApiTest, GetBasic) {
  12423. httplib::Client cli(HOST, PORT);
  12424. auto result = httplib::stream::Get(cli, "/hello");
  12425. ASSERT_TRUE(result.is_valid());
  12426. EXPECT_EQ(200, result.status());
  12427. EXPECT_EQ("Hello World!", read_body(result));
  12428. }
  12429. TEST_F(StreamApiTest, GetWithParams) {
  12430. httplib::Client cli(HOST, PORT);
  12431. httplib::Params params{{"foo", "bar"}};
  12432. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12433. ASSERT_TRUE(result.is_valid());
  12434. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12435. }
  12436. TEST_F(StreamApiTest, GetConnectionError) {
  12437. httplib::Client cli(HOST, 9999);
  12438. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12439. }
  12440. TEST_F(StreamApiTest, Get404) {
  12441. httplib::Client cli(HOST, PORT);
  12442. auto result = httplib::stream::Get(cli, "/nonexistent");
  12443. EXPECT_TRUE(result.is_valid());
  12444. EXPECT_EQ(404, result.status());
  12445. }
  12446. // stream::Post tests
  12447. TEST_F(StreamApiTest, PostBasic) {
  12448. httplib::Client cli(HOST, PORT);
  12449. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12450. "application/json");
  12451. ASSERT_TRUE(result.is_valid());
  12452. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12453. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12454. }
  12455. TEST_F(StreamApiTest, PostWithHeaders) {
  12456. httplib::Client cli(HOST, PORT);
  12457. httplib::Headers headers{{"X-Custom", "value"}};
  12458. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12459. "text/plain");
  12460. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12461. }
  12462. TEST_F(StreamApiTest, PostWithParams) {
  12463. httplib::Client cli(HOST, PORT);
  12464. httplib::Params params{{"k", "v"}};
  12465. auto result =
  12466. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12467. auto body = read_body(result);
  12468. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12469. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12470. }
  12471. TEST_F(StreamApiTest, PostLarge) {
  12472. httplib::Client cli(HOST, PORT);
  12473. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12474. size_t total = 0;
  12475. while (result.next()) {
  12476. total += result.size();
  12477. }
  12478. EXPECT_EQ(100u * 1024u, total);
  12479. }
  12480. // stream::Put/Patch tests
  12481. TEST_F(StreamApiTest, PutAndPatch) {
  12482. httplib::Client cli(HOST, PORT);
  12483. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12484. EXPECT_EQ("PUT:test", read_body(put));
  12485. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12486. EXPECT_EQ("PATCH:test", read_body(patch));
  12487. }
  12488. // stream::Delete tests
  12489. TEST_F(StreamApiTest, Delete) {
  12490. httplib::Client cli(HOST, PORT);
  12491. auto del1 = httplib::stream::Delete(cli, "/resource");
  12492. EXPECT_EQ("Deleted", read_body(del1));
  12493. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12494. EXPECT_EQ("Deleted:data", read_body(del2));
  12495. }
  12496. // stream::Head/Options tests
  12497. TEST_F(StreamApiTest, HeadAndOptions) {
  12498. httplib::Client cli(HOST, PORT);
  12499. auto head = httplib::stream::Head(cli, "/head-test");
  12500. EXPECT_TRUE(head.is_valid());
  12501. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12502. auto opts = httplib::stream::Options(cli, "/options");
  12503. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12504. }
  12505. // SSL stream::* tests
  12506. #ifdef CPPHTTPLIB_SSL_ENABLED
  12507. class SSLStreamApiTest : public ::testing::Test {
  12508. protected:
  12509. void SetUp() override {
  12510. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12511. res.set_content("Hello SSL!", "text/plain");
  12512. });
  12513. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12514. res.set_content(req.body, "text/plain");
  12515. });
  12516. port_ = svr_.bind_to_any_port("127.0.0.1");
  12517. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12518. svr_.wait_until_ready();
  12519. }
  12520. void TearDown() override {
  12521. svr_.stop();
  12522. if (thread_.joinable()) thread_.join();
  12523. }
  12524. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12525. std::thread thread_;
  12526. int port_ = 0;
  12527. };
  12528. TEST_F(SSLStreamApiTest, GetAndPost) {
  12529. httplib::SSLClient cli("127.0.0.1", port_);
  12530. cli.enable_server_certificate_verification(false);
  12531. auto get = httplib::stream::Get(cli, "/hello");
  12532. EXPECT_EQ("Hello SSL!", read_body(get));
  12533. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12534. EXPECT_EQ("test", read_body(post));
  12535. }
  12536. #endif
  12537. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12538. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12539. // BodyReader
  12540. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12541. // Test that read timeout during streaming is detected
  12542. // Use a large content-length response where server delays mid-stream
  12543. Server svr;
  12544. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12545. // Send a large response with delay in the middle
  12546. res.set_content_provider(
  12547. 1000, // content_length
  12548. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12549. if (offset < 100) {
  12550. // Send first 100 bytes immediately
  12551. std::string data(100, 'A');
  12552. sink.write(data.c_str(), data.size());
  12553. return true;
  12554. }
  12555. // Then delay longer than client timeout
  12556. std::this_thread::sleep_for(std::chrono::seconds(3));
  12557. std::string data(900, 'B');
  12558. sink.write(data.c_str(), data.size());
  12559. return true;
  12560. });
  12561. });
  12562. auto port = 8091;
  12563. std::thread t([&]() { svr.listen("localhost", port); });
  12564. svr.wait_until_ready();
  12565. Client cli("localhost", port);
  12566. cli.set_read_timeout(1, 0); // 1 second timeout
  12567. auto handle = cli.open_stream("GET", "/slow-stream");
  12568. ASSERT_TRUE(handle.is_valid());
  12569. char buf[256];
  12570. ssize_t total = 0;
  12571. ssize_t n;
  12572. bool got_error = false;
  12573. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12574. total += n;
  12575. }
  12576. if (n < 0) {
  12577. got_error = true;
  12578. // Should be timeout or read error
  12579. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12580. handle.get_read_error() == Error::Read)
  12581. << "Actual error: " << to_string(handle.get_read_error());
  12582. }
  12583. // Either we got an error, or we got less data than expected
  12584. EXPECT_TRUE(got_error || total < 1000)
  12585. << "Expected timeout but got all " << total << " bytes";
  12586. svr.stop();
  12587. t.join();
  12588. }
  12589. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12590. // Test connection closed detection via BodyReader
  12591. Server svr;
  12592. std::atomic<bool> close_now{false};
  12593. svr.Get("/will-close", [&](const Request &, Response &res) {
  12594. res.set_content_provider(
  12595. 10000, // Large content_length that we won't fully send
  12596. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12597. if (offset < 100) {
  12598. std::string data(100, 'X');
  12599. sink.write(data.c_str(), data.size());
  12600. return true;
  12601. }
  12602. // Wait for signal then abort
  12603. while (!close_now) {
  12604. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12605. }
  12606. return false; // Abort - server will close connection
  12607. });
  12608. });
  12609. auto port = 8092;
  12610. std::thread t([&]() { svr.listen("localhost", port); });
  12611. svr.wait_until_ready();
  12612. Client cli("localhost", port);
  12613. auto handle = cli.open_stream("GET", "/will-close");
  12614. ASSERT_TRUE(handle.is_valid());
  12615. char buf[256];
  12616. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12617. EXPECT_GT(n, 0) << "First read should succeed";
  12618. // Signal server to close
  12619. close_now = true;
  12620. // Keep reading until error or EOF
  12621. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12622. // Keep reading
  12623. }
  12624. // Should get an error since content_length wasn't satisfied
  12625. if (n < 0) {
  12626. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12627. handle.get_read_error() == Error::Read)
  12628. << "Actual error: " << to_string(handle.get_read_error());
  12629. }
  12630. svr.stop();
  12631. t.join();
  12632. }
  12633. #ifdef CPPHTTPLIB_SSL_ENABLED
  12634. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12635. // Test that read timeout during SSL streaming is detected
  12636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12637. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12638. res.set_content_provider(
  12639. 1000, "text/plain",
  12640. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12641. if (offset < 100) {
  12642. std::string data(100, 'A');
  12643. sink.write(data.c_str(), data.size());
  12644. return true;
  12645. }
  12646. std::this_thread::sleep_for(std::chrono::seconds(3));
  12647. std::string data(900, 'B');
  12648. sink.write(data.c_str(), data.size());
  12649. return true;
  12650. });
  12651. });
  12652. auto port = 8093;
  12653. std::thread t([&]() { svr.listen("localhost", port); });
  12654. svr.wait_until_ready();
  12655. SSLClient cli("localhost", port);
  12656. cli.enable_server_certificate_verification(false);
  12657. cli.set_read_timeout(1, 0); // 1 second timeout
  12658. auto handle = cli.open_stream("GET", "/slow-stream");
  12659. ASSERT_TRUE(handle.is_valid());
  12660. char buf[256];
  12661. ssize_t total = 0;
  12662. ssize_t n;
  12663. bool got_error = false;
  12664. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12665. total += n;
  12666. }
  12667. if (n < 0) {
  12668. got_error = true;
  12669. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12670. handle.get_read_error() == Error::Read)
  12671. << "Actual error: " << to_string(handle.get_read_error());
  12672. }
  12673. EXPECT_TRUE(got_error || total < 1000)
  12674. << "Expected timeout but got all " << total << " bytes";
  12675. svr.stop();
  12676. t.join();
  12677. }
  12678. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12679. // Test SSL connection closed detection
  12680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12681. std::atomic<bool> close_now{false};
  12682. svr.Get("/will-close", [&](const Request &, Response &res) {
  12683. res.set_content_provider(
  12684. 10000, "text/plain",
  12685. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12686. if (offset < 100) {
  12687. std::string data(100, 'X');
  12688. sink.write(data.c_str(), data.size());
  12689. return true;
  12690. }
  12691. while (!close_now) {
  12692. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12693. }
  12694. return false;
  12695. });
  12696. });
  12697. auto port = 8094;
  12698. std::thread t([&]() { svr.listen("localhost", port); });
  12699. svr.wait_until_ready();
  12700. SSLClient cli("localhost", port);
  12701. cli.enable_server_certificate_verification(false);
  12702. auto handle = cli.open_stream("GET", "/will-close");
  12703. ASSERT_TRUE(handle.is_valid());
  12704. char buf[256];
  12705. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12706. EXPECT_GT(n, 0);
  12707. // Signal server to close
  12708. close_now = true;
  12709. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12710. // Keep reading
  12711. }
  12712. if (n < 0) {
  12713. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12714. handle.get_read_error() == Error::Read)
  12715. << "Actual error: " << to_string(handle.get_read_error());
  12716. }
  12717. svr.stop();
  12718. t.join();
  12719. }
  12720. #endif
  12721. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12722. using namespace httplib;
  12723. // Create a test file
  12724. const char *fname = "etag_testfile.txt";
  12725. const char *content = "etag-content";
  12726. {
  12727. std::ofstream ofs(fname);
  12728. ofs << content;
  12729. ASSERT_TRUE(ofs.good());
  12730. }
  12731. Server svr;
  12732. svr.set_mount_point("/static", ".");
  12733. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12734. svr.wait_until_ready();
  12735. Client cli(HOST, PORT);
  12736. // First request: should get 200 with ETag header
  12737. auto res1 = cli.Get("/static/etag_testfile.txt");
  12738. ASSERT_TRUE(res1);
  12739. ASSERT_EQ(200, res1->status);
  12740. ASSERT_TRUE(res1->has_header("ETag"));
  12741. std::string etag = res1->get_header_value("ETag");
  12742. EXPECT_FALSE(etag.empty());
  12743. // Verify ETag format: W/"hex-hex"
  12744. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12745. EXPECT_EQ('W', etag[0]);
  12746. EXPECT_EQ('/', etag[1]);
  12747. EXPECT_EQ('"', etag[2]);
  12748. EXPECT_EQ('"', etag.back());
  12749. // Exact match: expect 304 Not Modified
  12750. Headers h2 = {{"If-None-Match", etag}};
  12751. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12752. ASSERT_TRUE(res2);
  12753. EXPECT_EQ(304, res2->status);
  12754. // Wildcard match: expect 304 Not Modified
  12755. Headers h3 = {{"If-None-Match", "*"}};
  12756. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12757. ASSERT_TRUE(res3);
  12758. EXPECT_EQ(304, res3->status);
  12759. // Non-matching ETag: expect 200
  12760. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12761. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12762. ASSERT_TRUE(res4);
  12763. EXPECT_EQ(200, res4->status);
  12764. // Multiple ETags with one matching: expect 304
  12765. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12766. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12767. ASSERT_TRUE(res5);
  12768. EXPECT_EQ(304, res5->status);
  12769. svr.stop();
  12770. t.join();
  12771. std::remove(fname);
  12772. }
  12773. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12774. using namespace httplib;
  12775. Server svr;
  12776. svr.set_mount_point("/static", ".");
  12777. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12778. svr.wait_until_ready();
  12779. Client cli(HOST, PORT);
  12780. // Send If-None-Match: * to a non-existent file
  12781. Headers h = {{"If-None-Match", "*"}};
  12782. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12783. ASSERT_TRUE(res);
  12784. EXPECT_EQ(404, res->status);
  12785. svr.stop();
  12786. t.join();
  12787. }
  12788. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12789. using namespace httplib;
  12790. // Create a test file
  12791. const char *fname = "etag_boundary_testfile.txt";
  12792. const char *content = "boundary-test";
  12793. {
  12794. std::ofstream ofs(fname);
  12795. ofs << content;
  12796. ASSERT_TRUE(ofs.good());
  12797. }
  12798. Server svr;
  12799. svr.set_mount_point("/static", ".");
  12800. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12801. svr.wait_until_ready();
  12802. Client cli(HOST, PORT);
  12803. // Get the actual ETag
  12804. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12805. ASSERT_TRUE(res1);
  12806. ASSERT_EQ(200, res1->status);
  12807. ASSERT_TRUE(res1->has_header("ETag"));
  12808. std::string etag = res1->get_header_value("ETag");
  12809. // Test 1: Very long ETag value (longer than actual ETag)
  12810. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12811. Headers h1 = {{"If-None-Match", "W/"
  12812. "\"very-long-etag-value-that-is-much-longer-"
  12813. "than-the-actual-etag-value\""}};
  12814. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12815. ASSERT_TRUE(res2);
  12816. EXPECT_EQ(200, res2->status); // Should not match
  12817. // Test 2: Long string followed by wildcard
  12818. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12819. // string)
  12820. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12821. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12822. ASSERT_TRUE(res3);
  12823. EXPECT_EQ(304, res3->status); // Should match on "*"
  12824. // Test 3: Wildcard followed by long string
  12825. // Should match on "*" immediately and return 304
  12826. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12827. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12828. ASSERT_TRUE(res4);
  12829. EXPECT_EQ(304, res4->status); // Should match on "*"
  12830. // Test 4: Multiple long non-matching values
  12831. // Should NOT match and return 200 (test that all comparisons are safe)
  12832. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12833. "W/\"second-long-non-matching-value\", "
  12834. "W/\"third-long-non-matching-value\""}};
  12835. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12836. ASSERT_TRUE(res5);
  12837. EXPECT_EQ(200, res5->status); // Should not match
  12838. // Test 5: Single character that is not "*" (edge case)
  12839. Headers h5 = {{"If-None-Match", "X"}};
  12840. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12841. ASSERT_TRUE(res6);
  12842. EXPECT_EQ(200, res6->status); // Should not match
  12843. svr.stop();
  12844. t.join();
  12845. std::remove(fname);
  12846. }
  12847. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12848. using namespace httplib;
  12849. // Create a test file
  12850. const char *fname = "ims_testfile.txt";
  12851. const char *content = "if-modified-since-test";
  12852. {
  12853. std::ofstream ofs(fname);
  12854. ofs << content;
  12855. ASSERT_TRUE(ofs.good());
  12856. }
  12857. Server svr;
  12858. svr.set_mount_point("/static", ".");
  12859. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12860. svr.wait_until_ready();
  12861. Client cli(HOST, PORT);
  12862. // First request: should get 200 with Last-Modified header
  12863. auto res1 = cli.Get("/static/ims_testfile.txt");
  12864. ASSERT_TRUE(res1);
  12865. ASSERT_EQ(200, res1->status);
  12866. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12867. std::string last_modified = res1->get_header_value("Last-Modified");
  12868. EXPECT_FALSE(last_modified.empty());
  12869. // If-Modified-Since with same time: expect 304
  12870. Headers h2 = {{"If-Modified-Since", last_modified}};
  12871. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12872. ASSERT_TRUE(res2);
  12873. EXPECT_EQ(304, res2->status);
  12874. // If-Modified-Since with future time: expect 304
  12875. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12876. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12877. ASSERT_TRUE(res3);
  12878. EXPECT_EQ(304, res3->status);
  12879. // If-Modified-Since with past time: expect 200
  12880. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12881. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12882. ASSERT_TRUE(res4);
  12883. EXPECT_EQ(200, res4->status);
  12884. // If-None-Match takes precedence over If-Modified-Since
  12885. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12886. ASSERT_TRUE(res1->has_header("ETag"));
  12887. std::string etag = res1->get_header_value("ETag");
  12888. Headers h5 = {{"If-None-Match", etag},
  12889. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12890. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12891. ASSERT_TRUE(res5);
  12892. EXPECT_EQ(304, res5->status);
  12893. svr.stop();
  12894. t.join();
  12895. std::remove(fname);
  12896. }
  12897. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12898. using namespace httplib;
  12899. Server svr;
  12900. // Endpoint that returns compressible content
  12901. svr.Get("/compressible", [](const Request &, Response &res) {
  12902. // Return a large enough body to trigger compression
  12903. std::string body(1000, 'a');
  12904. res.set_content(body, "text/plain");
  12905. });
  12906. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12907. svr.wait_until_ready();
  12908. Client cli(HOST, PORT);
  12909. // Request with gzip support: should get Vary header when compressed
  12910. cli.set_compress(true);
  12911. auto res1 = cli.Get("/compressible");
  12912. ASSERT_TRUE(res1);
  12913. EXPECT_EQ(200, res1->status);
  12914. // If Content-Encoding is set, Vary should also be set
  12915. if (res1->has_header("Content-Encoding")) {
  12916. EXPECT_TRUE(res1->has_header("Vary"));
  12917. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12918. }
  12919. // Request without Accept-Encoding header: should not have compression
  12920. Headers h_no_compress;
  12921. auto res2 = cli.Get("/compressible", h_no_compress);
  12922. ASSERT_TRUE(res2);
  12923. EXPECT_EQ(200, res2->status);
  12924. // Verify Vary header is present when compression is applied
  12925. // (the exact behavior depends on server configuration)
  12926. svr.stop();
  12927. t.join();
  12928. }
  12929. TEST(ETagTest, IfRangeWithETag) {
  12930. using namespace httplib;
  12931. // Create a test file with known content
  12932. const char *fname = "if_range_testfile.txt";
  12933. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12934. {
  12935. std::ofstream ofs(fname);
  12936. ofs << content;
  12937. ASSERT_TRUE(ofs.good());
  12938. }
  12939. Server svr;
  12940. svr.set_mount_point("/static", ".");
  12941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12942. svr.wait_until_ready();
  12943. Client cli(HOST, PORT);
  12944. // First request: get ETag
  12945. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12946. ASSERT_TRUE(res1);
  12947. ASSERT_EQ(200, res1->status);
  12948. ASSERT_TRUE(res1->has_header("ETag"));
  12949. std::string etag = res1->get_header_value("ETag");
  12950. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12951. // Since our server generates weak ETags (W/"..."), If-Range with our
  12952. // ETag should NOT result in partial content - it should return full content.
  12953. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12954. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12955. ASSERT_TRUE(res2);
  12956. // Weak ETag in If-Range -> full content (200), not partial (206)
  12957. EXPECT_EQ(200, res2->status);
  12958. EXPECT_EQ(content, res2->body);
  12959. EXPECT_FALSE(res2->has_header("Content-Range"));
  12960. // Range request with non-matching If-Range (ETag): should get 200 (full
  12961. // content)
  12962. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12963. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12964. ASSERT_TRUE(res3);
  12965. EXPECT_EQ(200, res3->status);
  12966. EXPECT_EQ(content, res3->body);
  12967. EXPECT_FALSE(res3->has_header("Content-Range"));
  12968. // Range request with strong ETag (hypothetical - our server doesn't generate
  12969. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12970. // should return full content)
  12971. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12972. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12973. ASSERT_TRUE(res4);
  12974. EXPECT_EQ(200, res4->status);
  12975. EXPECT_EQ(content, res4->body);
  12976. EXPECT_FALSE(res4->has_header("Content-Range"));
  12977. svr.stop();
  12978. t.join();
  12979. std::remove(fname);
  12980. }
  12981. TEST(ETagTest, IfRangeWithDate) {
  12982. using namespace httplib;
  12983. // Create a test file
  12984. const char *fname = "if_range_date_testfile.txt";
  12985. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12986. {
  12987. std::ofstream ofs(fname);
  12988. ofs << content;
  12989. ASSERT_TRUE(ofs.good());
  12990. }
  12991. Server svr;
  12992. svr.set_mount_point("/static", ".");
  12993. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12994. svr.wait_until_ready();
  12995. Client cli(HOST, PORT);
  12996. // First request: get Last-Modified
  12997. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12998. ASSERT_TRUE(res1);
  12999. ASSERT_EQ(200, res1->status);
  13000. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13001. std::string last_modified = res1->get_header_value("Last-Modified");
  13002. // Range request with matching If-Range (date): should get 206
  13003. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13004. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13005. ASSERT_TRUE(res2);
  13006. EXPECT_EQ(206, res2->status);
  13007. EXPECT_EQ("FGHIJ", res2->body);
  13008. // Range request with old If-Range date: should get 200 (full content)
  13009. Headers h3 = {{"Range", "bytes=5-9"},
  13010. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13011. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13012. ASSERT_TRUE(res3);
  13013. EXPECT_EQ(200, res3->status);
  13014. EXPECT_EQ(content, res3->body);
  13015. // Range request with future If-Range date: should get 206
  13016. Headers h4 = {{"Range", "bytes=0-4"},
  13017. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13018. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13019. ASSERT_TRUE(res4);
  13020. EXPECT_EQ(206, res4->status);
  13021. EXPECT_EQ("ABCDE", res4->body);
  13022. svr.stop();
  13023. t.join();
  13024. std::remove(fname);
  13025. }
  13026. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13027. using namespace httplib;
  13028. const char *fname = "etag_malformed.txt";
  13029. const char *content = "malformed-etag";
  13030. {
  13031. std::ofstream ofs(fname);
  13032. ofs << content;
  13033. ASSERT_TRUE(ofs.good());
  13034. }
  13035. Server svr;
  13036. svr.set_mount_point("/static", ".");
  13037. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13038. svr.wait_until_ready();
  13039. Client cli(HOST, PORT);
  13040. // baseline: should get 200 and an ETag
  13041. auto res1 = cli.Get("/static/etag_malformed.txt");
  13042. ASSERT_TRUE(res1);
  13043. ASSERT_EQ(200, res1->status);
  13044. ASSERT_TRUE(res1->has_header("ETag"));
  13045. // Malformed ETag value (missing quotes) should be treated as non-matching
  13046. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13047. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13048. ASSERT_TRUE(res_bad);
  13049. EXPECT_EQ(200, res_bad->status);
  13050. // Whitespace-only header value should be considered invalid / non-matching
  13051. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13052. "Host: localhost\r\n"
  13053. "If-None-Match: \r\n"
  13054. "Connection: close\r\n"
  13055. "\r\n";
  13056. std::string out;
  13057. ASSERT_TRUE(send_request(5, raw_req, &out));
  13058. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13059. svr.stop();
  13060. t.join();
  13061. std::remove(fname);
  13062. }
  13063. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13064. using namespace httplib;
  13065. const char *fname = "ims_invalid_format.txt";
  13066. const char *content = "ims-bad-format";
  13067. {
  13068. std::ofstream ofs(fname);
  13069. ofs << content;
  13070. ASSERT_TRUE(ofs.good());
  13071. }
  13072. Server svr;
  13073. svr.set_mount_point("/static", ".");
  13074. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13075. svr.wait_until_ready();
  13076. Client cli(HOST, PORT);
  13077. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13078. ASSERT_TRUE(res1);
  13079. ASSERT_EQ(200, res1->status);
  13080. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13081. // If-Modified-Since with invalid format should not result in 304
  13082. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13083. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13084. ASSERT_TRUE(res_bad);
  13085. EXPECT_EQ(200, res_bad->status);
  13086. // If-Range with invalid date format should be treated as mismatch -> full
  13087. // content (200)
  13088. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13089. {"If-Range", "invalid-date"}};
  13090. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13091. ASSERT_TRUE(res_ifrange);
  13092. EXPECT_EQ(200, res_ifrange->status);
  13093. svr.stop();
  13094. t.join();
  13095. std::remove(fname);
  13096. }
  13097. TEST(ETagTest, IfRangeWithMalformedETag) {
  13098. using namespace httplib;
  13099. const char *fname = "ifrange_malformed.txt";
  13100. const std::string content = "0123456789";
  13101. {
  13102. std::ofstream ofs(fname);
  13103. ofs << content;
  13104. ASSERT_TRUE(ofs.good());
  13105. }
  13106. Server svr;
  13107. svr.set_mount_point("/static", ".");
  13108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13109. svr.wait_until_ready();
  13110. Client cli(HOST, PORT);
  13111. // First request: get ETag
  13112. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13113. ASSERT_TRUE(res1);
  13114. ASSERT_EQ(200, res1->status);
  13115. ASSERT_TRUE(res1->has_header("ETag"));
  13116. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13117. // full content (200)
  13118. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13119. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13120. ASSERT_TRUE(res2);
  13121. EXPECT_EQ(200, res2->status);
  13122. EXPECT_EQ(content, res2->body);
  13123. svr.stop();
  13124. t.join();
  13125. std::remove(fname);
  13126. }
  13127. TEST(ETagTest, ExtremeLargeDateValues) {
  13128. using namespace httplib;
  13129. const char *fname = "ims_extreme_date.txt";
  13130. const char *content = "ims-extreme-date";
  13131. {
  13132. std::ofstream ofs(fname);
  13133. ofs << content;
  13134. ASSERT_TRUE(ofs.good());
  13135. }
  13136. Server svr;
  13137. svr.set_mount_point("/static", ".");
  13138. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13139. svr.wait_until_ready();
  13140. Client cli(HOST, PORT);
  13141. auto res1 = cli.Get(std::string("/static/") + fname);
  13142. ASSERT_TRUE(res1);
  13143. ASSERT_EQ(200, res1->status);
  13144. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13145. // Extremely large year that may overflow date parsing routines.
  13146. Headers h_large_date = {
  13147. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13148. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13149. ASSERT_TRUE(res_bad);
  13150. // Expect server to treat this as invalid/mismatch and return full content
  13151. EXPECT_EQ(200, res_bad->status);
  13152. // If-Range with extremely large date should be treated as mismatch -> full
  13153. // content (200)
  13154. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13155. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13156. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13157. ASSERT_TRUE(res_ifrange);
  13158. EXPECT_EQ(200, res_ifrange->status);
  13159. svr.stop();
  13160. t.join();
  13161. std::remove(fname);
  13162. }
  13163. TEST(ETagTest, NegativeFileModificationTime) {
  13164. using namespace httplib;
  13165. const char *fname = "ims_negative_mtime.txt";
  13166. const std::string content = "negative-mtime";
  13167. {
  13168. std::ofstream ofs(fname);
  13169. ofs << content;
  13170. ASSERT_TRUE(ofs.good());
  13171. }
  13172. // Try to set file mtime to a negative value. This may fail on some
  13173. // platforms/filesystems; if it fails, the test will still verify server
  13174. // behaves safely by performing a regular conditional request.
  13175. #if defined(__APPLE__) || defined(__linux__)
  13176. bool set_negative = false;
  13177. do {
  13178. struct timeval times[2];
  13179. // access time: now
  13180. times[0].tv_sec = time(nullptr);
  13181. times[0].tv_usec = 0;
  13182. // modification time: negative (e.g., -1)
  13183. times[1].tv_sec = -1;
  13184. times[1].tv_usec = 0;
  13185. if (utimes(fname, times) == 0) { set_negative = true; }
  13186. } while (0);
  13187. #else
  13188. bool set_negative = false;
  13189. #endif
  13190. Server svr;
  13191. svr.set_mount_point("/static", ".");
  13192. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13193. svr.wait_until_ready();
  13194. Client cli(HOST, PORT);
  13195. auto res1 = cli.Get(std::string("/static/") + fname);
  13196. ASSERT_TRUE(res1);
  13197. ASSERT_EQ(200, res1->status);
  13198. bool has_last_modified = res1->has_header("Last-Modified");
  13199. std::string last_modified;
  13200. if (has_last_modified) {
  13201. last_modified = res1->get_header_value("Last-Modified");
  13202. }
  13203. if (set_negative) {
  13204. // If we successfully set a negative mtime, ensure server returns a
  13205. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13206. // with an old date and ensure server handles it without crash.
  13207. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13208. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13209. ASSERT_TRUE(res2);
  13210. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13211. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13212. } else {
  13213. // Could not set negative mtime on this platform; fall back to verifying
  13214. // that normal invalid/malformed dates are treated safely (non-304).
  13215. Headers h_bad_date = {
  13216. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13217. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13218. ASSERT_TRUE(res_bad);
  13219. EXPECT_EQ(200, res_bad->status);
  13220. }
  13221. svr.stop();
  13222. t.join();
  13223. std::remove(fname);
  13224. }
  13225. //==============================================================================
  13226. // SSE Parsing Tests
  13227. //==============================================================================
  13228. class SSEParsingTest : public ::testing::Test {
  13229. protected:
  13230. // Test helper that mimics SSE parsing behavior
  13231. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13232. int &retry_ms) {
  13233. // Blank line signals end of event
  13234. if (line.empty() || line == "\r") { return true; }
  13235. // Lines starting with ':' are comments (ignored)
  13236. if (!line.empty() && line[0] == ':') { return false; }
  13237. // Find the colon separator
  13238. auto colon_pos = line.find(':');
  13239. if (colon_pos == std::string::npos) {
  13240. // Line with no colon is treated as field name with empty value
  13241. return false;
  13242. }
  13243. std::string field = line.substr(0, colon_pos);
  13244. std::string value;
  13245. // Value starts after colon, skip optional single space
  13246. if (colon_pos + 1 < line.size()) {
  13247. size_t value_start = colon_pos + 1;
  13248. if (line[value_start] == ' ') { value_start++; }
  13249. value = line.substr(value_start);
  13250. // Remove trailing \r if present
  13251. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13252. }
  13253. // Handle known fields
  13254. if (field == "event") {
  13255. msg.event = value;
  13256. } else if (field == "data") {
  13257. // Multiple data lines are concatenated with newlines
  13258. if (!msg.data.empty()) { msg.data += "\n"; }
  13259. msg.data += value;
  13260. } else if (field == "id") {
  13261. // Empty id is valid (clears the last event ID)
  13262. msg.id = value;
  13263. } else if (field == "retry") {
  13264. // Parse retry interval in milliseconds
  13265. {
  13266. int v = 0;
  13267. auto res =
  13268. detail::from_chars(value.data(), value.data() + value.size(), v);
  13269. if (res.ec == std::errc{}) { retry_ms = v; }
  13270. }
  13271. }
  13272. // Unknown fields are ignored per SSE spec
  13273. return false;
  13274. }
  13275. };
  13276. // Test: Single-line data
  13277. TEST_F(SSEParsingTest, SingleLineData) {
  13278. sse::SSEMessage msg;
  13279. int retry_ms = 3000;
  13280. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13281. EXPECT_EQ(msg.data, "hello");
  13282. EXPECT_EQ(msg.event, "message");
  13283. // Blank line ends event
  13284. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13285. }
  13286. // Test: Multi-line data
  13287. TEST_F(SSEParsingTest, MultiLineData) {
  13288. sse::SSEMessage msg;
  13289. int retry_ms = 3000;
  13290. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13291. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13292. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13293. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13294. }
  13295. // Test: Custom event types
  13296. TEST_F(SSEParsingTest, CustomEventType) {
  13297. sse::SSEMessage msg;
  13298. int retry_ms = 3000;
  13299. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13300. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13301. EXPECT_EQ(msg.event, "update");
  13302. EXPECT_EQ(msg.data, "payload");
  13303. }
  13304. // Test: Event ID handling
  13305. TEST_F(SSEParsingTest, EventIdHandling) {
  13306. sse::SSEMessage msg;
  13307. int retry_ms = 3000;
  13308. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13309. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13310. EXPECT_EQ(msg.id, "12345");
  13311. }
  13312. // Test: Empty event ID (clears last event ID)
  13313. TEST_F(SSEParsingTest, EmptyEventId) {
  13314. sse::SSEMessage msg;
  13315. msg.id = "previous";
  13316. int retry_ms = 3000;
  13317. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13318. EXPECT_EQ(msg.id, "");
  13319. }
  13320. // Test: Retry field parsing
  13321. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13322. sse::SSEMessage msg;
  13323. int retry_ms = 3000;
  13324. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13325. EXPECT_EQ(retry_ms, 5000);
  13326. }
  13327. // Test: Invalid retry value
  13328. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13329. sse::SSEMessage msg;
  13330. int retry_ms = 3000;
  13331. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13332. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13333. }
  13334. // Test: Comments (lines starting with :)
  13335. TEST_F(SSEParsingTest, CommentsIgnored) {
  13336. sse::SSEMessage msg;
  13337. int retry_ms = 3000;
  13338. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13339. EXPECT_EQ(msg.data, "");
  13340. EXPECT_EQ(msg.event, "message");
  13341. }
  13342. // Test: Colon in value
  13343. TEST_F(SSEParsingTest, ColonInValue) {
  13344. sse::SSEMessage msg;
  13345. int retry_ms = 3000;
  13346. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13347. EXPECT_EQ(msg.data, "hello:world:test");
  13348. }
  13349. // Test: Line with no colon (field name only)
  13350. TEST_F(SSEParsingTest, FieldNameOnly) {
  13351. sse::SSEMessage msg;
  13352. int retry_ms = 3000;
  13353. // According to SSE spec, this is treated as field name with empty value
  13354. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13355. // Since we don't recognize "data" without colon, data should be empty
  13356. EXPECT_EQ(msg.data, "");
  13357. }
  13358. // Test: Trailing \r handling
  13359. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13360. sse::SSEMessage msg;
  13361. int retry_ms = 3000;
  13362. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13363. EXPECT_EQ(msg.data, "hello");
  13364. }
  13365. // Test: Unknown fields ignored
  13366. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13367. sse::SSEMessage msg;
  13368. int retry_ms = 3000;
  13369. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13370. EXPECT_EQ(msg.data, "");
  13371. EXPECT_EQ(msg.event, "message");
  13372. }
  13373. // Test: Space after colon is optional
  13374. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13375. sse::SSEMessage msg1, msg2;
  13376. int retry_ms = 3000;
  13377. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13378. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13379. EXPECT_EQ(msg1.data, "hello");
  13380. EXPECT_EQ(msg2.data, "hello");
  13381. }
  13382. // Test: SSEMessage clear
  13383. TEST_F(SSEParsingTest, MessageClear) {
  13384. sse::SSEMessage msg;
  13385. msg.event = "custom";
  13386. msg.data = "some data";
  13387. msg.id = "123";
  13388. msg.clear();
  13389. EXPECT_EQ(msg.event, "message");
  13390. EXPECT_EQ(msg.data, "");
  13391. EXPECT_EQ(msg.id, "");
  13392. }
  13393. // Test: Complete event parsing
  13394. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13395. sse::SSEMessage msg;
  13396. int retry_ms = 3000;
  13397. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13398. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13399. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13400. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13401. // Blank line ends event
  13402. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13403. EXPECT_EQ(msg.event, "notification");
  13404. EXPECT_EQ(msg.id, "evt-42");
  13405. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13406. EXPECT_EQ(retry_ms, 1000);
  13407. }
  13408. //==============================================================================
  13409. // Integration Tests with Server
  13410. //==============================================================================
  13411. class SSEIntegrationTest : public ::testing::Test {
  13412. protected:
  13413. void SetUp() override {
  13414. stop_server_.store(false);
  13415. events_.clear();
  13416. server_ = httplib::detail::make_unique<Server>();
  13417. setup_server();
  13418. start_server();
  13419. }
  13420. void TearDown() override {
  13421. stop_server_.store(true);
  13422. event_cv_.notify_all();
  13423. server_->stop();
  13424. if (server_thread_.joinable()) { server_thread_.join(); }
  13425. }
  13426. void setup_server() {
  13427. // Simple SSE endpoint
  13428. server_->Get("/events", [this](const Request &req, Response &res) {
  13429. auto last_id = req.get_header_value("Last-Event-ID");
  13430. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13431. res.set_chunked_content_provider(
  13432. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13433. std::unique_lock<std::mutex> lock(event_mutex_);
  13434. if (event_cv_.wait_for(
  13435. lock, std::chrono::milliseconds(200), [this] {
  13436. return !events_.empty() || stop_server_.load();
  13437. })) {
  13438. if (stop_server_.load()) { return false; }
  13439. if (!events_.empty()) {
  13440. std::string event = events_.front();
  13441. events_.erase(events_.begin());
  13442. sink.write(event.data(), event.size());
  13443. return true;
  13444. }
  13445. }
  13446. return !stop_server_.load();
  13447. });
  13448. });
  13449. // Endpoint that returns error
  13450. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13451. res.status = 500;
  13452. res.set_content("Internal Server Error", "text/plain");
  13453. });
  13454. // Endpoint for custom event types
  13455. server_->Get("/custom-events", [](const Request &, Response &res) {
  13456. res.set_chunked_content_provider(
  13457. "text/event-stream", [](size_t offset, DataSink &sink) {
  13458. if (offset == 0) {
  13459. std::string event = "event: update\ndata: updated\n\n"
  13460. "event: delete\ndata: deleted\n\n";
  13461. sink.write(event.data(), event.size());
  13462. }
  13463. return false; // End stream after sending
  13464. });
  13465. });
  13466. }
  13467. void start_server() {
  13468. port_ = server_->bind_to_any_port(HOST);
  13469. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13470. // Wait for server to start
  13471. while (!server_->is_running()) {
  13472. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13473. }
  13474. }
  13475. int get_port() const { return port_; }
  13476. void send_event(const std::string &event) {
  13477. std::lock_guard<std::mutex> lock(event_mutex_);
  13478. events_.push_back(event);
  13479. event_cv_.notify_all();
  13480. }
  13481. std::unique_ptr<Server> server_;
  13482. std::thread server_thread_;
  13483. std::mutex event_mutex_;
  13484. std::condition_variable event_cv_;
  13485. std::vector<std::string> events_;
  13486. std::atomic<bool> stop_server_{false};
  13487. std::string last_received_event_id_;
  13488. int port_ = 0;
  13489. };
  13490. // Test: Successful connection and on_open callback
  13491. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13492. // Add a simple endpoint that sends one event and closes
  13493. server_->Get("/simple-event", [](const Request &, Response &res) {
  13494. res.set_chunked_content_provider(
  13495. "text/event-stream", [](size_t offset, DataSink &sink) {
  13496. if (offset == 0) {
  13497. std::string event = "data: hello\n\n";
  13498. sink.write(event.data(), event.size());
  13499. }
  13500. return false; // Close stream after sending
  13501. });
  13502. });
  13503. Client client("localhost", get_port());
  13504. sse::SSEClient sse(client, "/simple-event");
  13505. std::atomic<bool> open_called{false};
  13506. std::atomic<bool> message_received{false};
  13507. sse.on_open([&open_called]() { open_called.store(true); });
  13508. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13509. if (msg.data == "hello") { message_received.store(true); }
  13510. });
  13511. sse.set_reconnect_interval(100);
  13512. sse.set_max_reconnect_attempts(1);
  13513. // Start async
  13514. sse.start_async();
  13515. // Wait for message to be processed
  13516. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13517. sse.stop();
  13518. EXPECT_TRUE(open_called.load());
  13519. EXPECT_TRUE(message_received.load());
  13520. }
  13521. // Test: on_message callback
  13522. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13523. // Endpoint that sends multiple events then closes
  13524. server_->Get("/multi-event", [](const Request &, Response &res) {
  13525. res.set_chunked_content_provider(
  13526. "text/event-stream", [](size_t offset, DataSink &sink) {
  13527. if (offset == 0) {
  13528. std::string events = "data: message1\n\ndata: message2\n\n";
  13529. sink.write(events.data(), events.size());
  13530. }
  13531. return false;
  13532. });
  13533. });
  13534. Client client("localhost", get_port());
  13535. sse::SSEClient sse(client, "/multi-event");
  13536. std::vector<std::string> received_messages;
  13537. std::mutex messages_mutex;
  13538. sse.on_message([&](const sse::SSEMessage &msg) {
  13539. std::lock_guard<std::mutex> lock(messages_mutex);
  13540. received_messages.push_back(msg.data);
  13541. });
  13542. sse.set_reconnect_interval(100);
  13543. sse.set_max_reconnect_attempts(1);
  13544. sse.start_async();
  13545. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13546. sse.stop();
  13547. std::lock_guard<std::mutex> lock(messages_mutex);
  13548. EXPECT_GE(received_messages.size(), 2u);
  13549. if (received_messages.size() >= 2) {
  13550. EXPECT_EQ(received_messages[0], "message1");
  13551. EXPECT_EQ(received_messages[1], "message2");
  13552. }
  13553. }
  13554. // Test: on_event for specific types
  13555. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13556. Client client("localhost", get_port());
  13557. sse::SSEClient sse(client, "/custom-events");
  13558. std::atomic<bool> update_received{false};
  13559. std::atomic<bool> delete_received{false};
  13560. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13561. if (msg.data == "updated") { update_received.store(true); }
  13562. });
  13563. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13564. if (msg.data == "deleted") { delete_received.store(true); }
  13565. });
  13566. sse.set_max_reconnect_attempts(1);
  13567. sse.start_async();
  13568. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13569. sse.stop();
  13570. EXPECT_TRUE(update_received.load());
  13571. EXPECT_TRUE(delete_received.load());
  13572. }
  13573. // Test: on_error callback on connection failure
  13574. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13575. // Connect to a non-existent port
  13576. Client client("localhost", 59999);
  13577. sse::SSEClient sse(client, "/events");
  13578. std::atomic<bool> error_called{false};
  13579. Error received_error = Error::Success;
  13580. sse.on_error([&](Error err) {
  13581. error_called.store(true);
  13582. received_error = err;
  13583. });
  13584. sse.set_reconnect_interval(50);
  13585. sse.set_max_reconnect_attempts(1);
  13586. sse.start_async();
  13587. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13588. sse.stop();
  13589. EXPECT_TRUE(error_called.load());
  13590. EXPECT_NE(received_error, Error::Success);
  13591. }
  13592. // Test: Last-Event-ID header sent on reconnect
  13593. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13594. // Endpoint that sends event with ID
  13595. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13596. res.set_chunked_content_provider(
  13597. "text/event-stream", [](size_t offset, DataSink &sink) {
  13598. if (offset == 0) {
  13599. std::string event = "id: evt-123\ndata: test\n\n";
  13600. sink.write(event.data(), event.size());
  13601. }
  13602. return false;
  13603. });
  13604. });
  13605. Client client("localhost", get_port());
  13606. sse::SSEClient sse(client, "/event-with-id");
  13607. std::atomic<bool> id_received{false};
  13608. sse.on_message([&](const sse::SSEMessage &msg) {
  13609. if (!msg.id.empty()) { id_received.store(true); }
  13610. });
  13611. sse.set_reconnect_interval(100);
  13612. sse.set_max_reconnect_attempts(1);
  13613. sse.start_async();
  13614. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13615. sse.stop();
  13616. EXPECT_TRUE(id_received.load());
  13617. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13618. }
  13619. // Test: Manual stop
  13620. TEST_F(SSEIntegrationTest, ManualStop) {
  13621. // Endpoint that sends one event and stays open briefly
  13622. std::atomic<bool> handler_running{true};
  13623. server_->Get("/stay-open", [&handler_running](const Request &,
  13624. Response &res) {
  13625. res.set_chunked_content_provider(
  13626. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13627. if (offset == 0) {
  13628. std::string event = "data: connected\n\n";
  13629. sink.write(event.data(), event.size());
  13630. }
  13631. // Keep connection open while handler_running is true
  13632. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13633. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13634. }
  13635. return false;
  13636. });
  13637. });
  13638. Client client("localhost", get_port());
  13639. sse::SSEClient sse(client, "/stay-open");
  13640. std::atomic<bool> connected{false};
  13641. sse.on_open([&connected]() { connected.store(true); });
  13642. sse.set_reconnect_interval(100);
  13643. sse.set_max_reconnect_attempts(1);
  13644. sse.start_async();
  13645. // Wait for connection to establish
  13646. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13647. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13648. }
  13649. EXPECT_TRUE(connected.load());
  13650. EXPECT_TRUE(sse.is_connected());
  13651. // Signal handler to stop
  13652. handler_running.store(false);
  13653. // Stop SSE client
  13654. sse.stop();
  13655. EXPECT_FALSE(sse.is_connected());
  13656. }
  13657. // Test: SSEClient with custom headers
  13658. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13659. // Setup a server endpoint that checks for custom header
  13660. std::atomic<bool> header_received{false};
  13661. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13662. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13663. header_received.store(true);
  13664. }
  13665. res.set_chunked_content_provider("text/event-stream",
  13666. [](size_t, DataSink &) { return false; });
  13667. });
  13668. Client client("localhost", get_port());
  13669. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13670. sse::SSEClient sse(client, "/header-check", headers);
  13671. sse.set_max_reconnect_attempts(1);
  13672. sse.start_async();
  13673. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13674. sse.stop();
  13675. EXPECT_TRUE(header_received.load());
  13676. }
  13677. // Test: Reconnect interval configuration
  13678. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13679. Client client("localhost", get_port());
  13680. sse::SSEClient sse(client, "/events");
  13681. auto &result = sse.set_reconnect_interval(500);
  13682. // Builder pattern should return reference to self
  13683. EXPECT_EQ(&result, &sse);
  13684. }
  13685. // Test: Max reconnect attempts
  13686. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13687. // Connect to non-existent port to force reconnects
  13688. Client client("localhost", 59998);
  13689. sse::SSEClient sse(client, "/events");
  13690. std::atomic<int> error_count{0};
  13691. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13692. sse.set_reconnect_interval(50);
  13693. sse.set_max_reconnect_attempts(2);
  13694. auto start = std::chrono::steady_clock::now();
  13695. sse.start(); // Blocking call
  13696. auto end = std::chrono::steady_clock::now();
  13697. // Should have stopped after 2 failed attempts
  13698. EXPECT_GE(error_count.load(), 2);
  13699. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13700. auto duration =
  13701. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13702. #ifdef _WIN32
  13703. // Windows is much slower for socket connection failures
  13704. EXPECT_LT(duration.count(), 7000);
  13705. #else
  13706. EXPECT_LT(duration.count(), 1000);
  13707. #endif
  13708. }
  13709. // Test: Multi-line data in integration
  13710. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13711. // Endpoint with multi-line data
  13712. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13713. res.set_chunked_content_provider(
  13714. "text/event-stream", [](size_t offset, DataSink &sink) {
  13715. if (offset == 0) {
  13716. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13717. sink.write(event.data(), event.size());
  13718. }
  13719. return false;
  13720. });
  13721. });
  13722. Client client("localhost", get_port());
  13723. sse::SSEClient sse(client, "/multiline-data");
  13724. std::string received_data;
  13725. std::mutex data_mutex;
  13726. sse.on_message([&](const sse::SSEMessage &msg) {
  13727. std::lock_guard<std::mutex> lock(data_mutex);
  13728. received_data = msg.data;
  13729. });
  13730. sse.set_reconnect_interval(100);
  13731. sse.set_max_reconnect_attempts(1);
  13732. sse.start_async();
  13733. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13734. sse.stop();
  13735. std::lock_guard<std::mutex> lock(data_mutex);
  13736. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13737. }
  13738. // Test: Auto-reconnect after server disconnection
  13739. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13740. std::atomic<int> connection_count{0};
  13741. std::atomic<int> message_count{0};
  13742. // Endpoint that sends one event and closes, forcing reconnect
  13743. server_->Get("/reconnect-test",
  13744. [&connection_count](const Request &, Response &res) {
  13745. connection_count.fetch_add(1);
  13746. res.set_chunked_content_provider(
  13747. "text/event-stream", [](size_t offset, DataSink &sink) {
  13748. if (offset == 0) {
  13749. std::string event = "data: hello\n\n";
  13750. sink.write(event.data(), event.size());
  13751. }
  13752. return false; // Close connection after sending
  13753. });
  13754. });
  13755. Client client("localhost", get_port());
  13756. sse::SSEClient sse(client, "/reconnect-test");
  13757. sse.on_message([&message_count](const sse::SSEMessage &) {
  13758. message_count.fetch_add(1);
  13759. });
  13760. sse.set_reconnect_interval(100);
  13761. sse.set_max_reconnect_attempts(3);
  13762. sse.start_async();
  13763. // Wait long enough for multiple reconnects
  13764. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13765. sse.stop();
  13766. // Should have connected multiple times (initial + reconnects)
  13767. EXPECT_GE(connection_count.load(), 2);
  13768. // Should have received messages from multiple connections
  13769. EXPECT_GE(message_count.load(), 2);
  13770. }
  13771. // Test: Last-Event-ID sent on reconnect
  13772. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13773. std::atomic<int> connection_count{0};
  13774. std::vector<std::string> received_last_event_ids;
  13775. std::mutex id_mutex;
  13776. // Endpoint that checks Last-Event-ID header and sends event with ID
  13777. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13778. int conn = connection_count.fetch_add(1);
  13779. // Capture the Last-Event-ID header from each connection
  13780. {
  13781. std::lock_guard<std::mutex> lock(id_mutex);
  13782. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13783. }
  13784. res.set_chunked_content_provider(
  13785. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13786. if (offset == 0) {
  13787. std::string event =
  13788. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13789. sink.write(event.data(), event.size());
  13790. }
  13791. return false;
  13792. });
  13793. });
  13794. Client client("localhost", get_port());
  13795. sse::SSEClient sse(client, "/reconnect-with-id");
  13796. sse.set_reconnect_interval(100);
  13797. sse.set_max_reconnect_attempts(3);
  13798. sse.start_async();
  13799. // Wait for at least 2 connections
  13800. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13801. sse.stop();
  13802. // Verify behavior
  13803. std::lock_guard<std::mutex> lock(id_mutex);
  13804. EXPECT_GE(received_last_event_ids.size(), 2u);
  13805. // First connection should have no Last-Event-ID
  13806. if (!received_last_event_ids.empty()) {
  13807. EXPECT_EQ(received_last_event_ids[0], "");
  13808. }
  13809. // Second connection should have Last-Event-ID from first connection
  13810. if (received_last_event_ids.size() >= 2) {
  13811. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13812. }
  13813. }
  13814. // Test: set_headers updates headers used on reconnect
  13815. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13816. std::vector<std::string> received_tokens;
  13817. std::mutex token_mutex;
  13818. // Endpoint that captures Authorization header
  13819. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13820. {
  13821. std::lock_guard<std::mutex> lock(token_mutex);
  13822. received_tokens.push_back(req.get_header_value("Authorization"));
  13823. }
  13824. res.set_chunked_content_provider(
  13825. "text/event-stream", [](size_t offset, DataSink &sink) {
  13826. if (offset == 0) {
  13827. std::string event = "data: hello\n\n";
  13828. sink.write(event.data(), event.size());
  13829. }
  13830. return false; // Close connection to trigger reconnect
  13831. });
  13832. });
  13833. Client client("localhost", get_port());
  13834. Headers headers = {{"Authorization", "Bearer old-token"}};
  13835. sse::SSEClient sse(client, "/auth-check", headers);
  13836. // Update headers on each successful connection
  13837. sse.on_open(
  13838. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13839. sse.set_reconnect_interval(100);
  13840. sse.set_max_reconnect_attempts(3);
  13841. sse.start_async();
  13842. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13843. sse.stop();
  13844. std::lock_guard<std::mutex> lock(token_mutex);
  13845. ASSERT_GE(received_tokens.size(), 2u);
  13846. // First connection uses original header
  13847. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13848. // Second connection uses updated header from set_headers
  13849. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13850. }
  13851. // Test: 401 allows reconnection (so on_error can refresh headers)
  13852. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13853. std::atomic<int> connection_count{0};
  13854. // Endpoint: returns 401 on first attempt, 200 on second
  13855. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13856. int conn = connection_count.fetch_add(1);
  13857. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13858. res.status = StatusCode::Unauthorized_401;
  13859. res.set_content("Unauthorized", "text/plain");
  13860. return;
  13861. }
  13862. res.set_chunked_content_provider(
  13863. "text/event-stream", [](size_t offset, DataSink &sink) {
  13864. if (offset == 0) {
  13865. std::string event = "data: authenticated\n\n";
  13866. sink.write(event.data(), event.size());
  13867. }
  13868. return false;
  13869. });
  13870. });
  13871. Client client("localhost", get_port());
  13872. Headers headers = {{"Authorization", "Bearer expired"}};
  13873. sse::SSEClient sse(client, "/auth-retry", headers);
  13874. std::atomic<bool> message_received{false};
  13875. // Refresh token on error
  13876. sse.on_error(
  13877. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13878. sse.on_message([&](const sse::SSEMessage &msg) {
  13879. if (msg.data == "authenticated") { message_received.store(true); }
  13880. });
  13881. sse.set_reconnect_interval(100);
  13882. sse.set_max_reconnect_attempts(3);
  13883. sse.start_async();
  13884. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13885. sse.stop();
  13886. // Should have reconnected after 401 and succeeded with new token
  13887. EXPECT_GE(connection_count.load(), 2);
  13888. EXPECT_TRUE(message_received.load());
  13889. }
  13890. TEST(Issue2318Test, EmptyHostString) {
  13891. {
  13892. httplib::Client cli_empty("", PORT);
  13893. auto res = cli_empty.Get("/");
  13894. ASSERT_FALSE(res);
  13895. EXPECT_EQ(httplib::Error::Connection, res.error());
  13896. }
  13897. {
  13898. httplib::Client cli(" ", PORT);
  13899. auto res = cli.Get("/");
  13900. ASSERT_FALSE(res);
  13901. EXPECT_EQ(httplib::Error::Connection, res.error());
  13902. }
  13903. }
  13904. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13905. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13906. Server svr;
  13907. // Set a small payload limit (1KB)
  13908. svr.set_payload_max_length(1024);
  13909. svr.Post("/test", [&](const Request &req, Response &res) {
  13910. res.set_content("Body size: " + std::to_string(req.body.size()),
  13911. "text/plain");
  13912. });
  13913. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13914. auto se = detail::scope_exit([&] {
  13915. svr.stop();
  13916. listen_thread.join();
  13917. });
  13918. svr.wait_until_ready();
  13919. // Create data that compresses well but exceeds limit when decompressed
  13920. // 8KB of repeated null bytes compresses to a very small size
  13921. std::string original_data(8 * 1024, '\0');
  13922. // Compress the data using gzip
  13923. std::string compressed_data;
  13924. detail::gzip_compressor compressor;
  13925. compressor.compress(original_data.data(), original_data.size(), true,
  13926. [&](const char *data, size_t size) {
  13927. compressed_data.append(data, size);
  13928. return true;
  13929. });
  13930. // Verify compression worked (compressed should be much smaller)
  13931. ASSERT_LT(compressed_data.size(), original_data.size());
  13932. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13933. // Send compressed data with Content-Encoding: gzip
  13934. Client cli(HOST, PORT);
  13935. Headers headers = {{"Content-Encoding", "gzip"}};
  13936. auto res =
  13937. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13938. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13939. ASSERT_TRUE(res);
  13940. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13941. }
  13942. #endif
  13943. // ============================================================================
  13944. // OpenSSL-Specific Tests
  13945. // ============================================================================
  13946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13947. X509 *readCertificate(const std::string &strFileName) {
  13948. std::ifstream inStream(strFileName);
  13949. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13950. std::istreambuf_iterator<char>());
  13951. if (strCertPEM.empty()) return (nullptr);
  13952. BIO *pbCert = BIO_new(BIO_s_mem());
  13953. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13954. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13955. BIO_free(pbCert);
  13956. return (pCert);
  13957. }
  13958. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13959. std::ifstream inStream(strFileName);
  13960. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13961. std::istreambuf_iterator<char>());
  13962. if (strPrivateKeyPEM.empty()) return (nullptr);
  13963. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13964. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13965. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13966. BIO_free(pbPrivKey);
  13967. return (pPrivateKey);
  13968. }
  13969. TEST(BindServerTest, UpdateCerts) {
  13970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13971. int port = svr.bind_to_any_port("0.0.0.0");
  13972. ASSERT_TRUE(svr.is_valid());
  13973. ASSERT_TRUE(port > 0);
  13974. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13975. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13976. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13977. ASSERT_TRUE(cert != nullptr);
  13978. ASSERT_TRUE(ca_cert != nullptr);
  13979. ASSERT_TRUE(key != nullptr);
  13980. X509_STORE *cert_store = X509_STORE_new();
  13981. X509_STORE_add_cert(cert_store, ca_cert);
  13982. // svr.update_certs(cert, key, cert_store); // deprecated
  13983. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13984. CLIENT_CA_CERT_FILE);
  13985. ASSERT_TRUE(svr.is_valid());
  13986. svr.stop();
  13987. X509_STORE_free(cert_store);
  13988. X509_free(cert);
  13989. X509_free(ca_cert);
  13990. EVP_PKEY_free(key);
  13991. }
  13992. // Test that update_certs() updates client CA list correctly
  13993. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13994. // Start with file-based constructor
  13995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13996. ASSERT_TRUE(svr.is_valid());
  13997. // Initially no client CA list should be set
  13998. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13999. ASSERT_TRUE(ssl_ctx != nullptr);
  14000. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14001. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14002. EXPECT_EQ(0, count_before);
  14003. // Now update with client CA (PEM string)
  14004. std::string cert_pem, key_pem, ca_pem;
  14005. read_file(SERVER_CERT_FILE, cert_pem);
  14006. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14007. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14008. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14009. ASSERT_TRUE(svr.is_valid());
  14010. // Now client CA list should be set
  14011. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14012. ASSERT_TRUE(ca_list_after != nullptr);
  14013. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14014. }
  14015. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14016. // Test that the file-path SSLServer constructor properly sets the client CA
  14017. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14019. ASSERT_TRUE(svr.is_valid());
  14020. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14021. ASSERT_TRUE(ssl_ctx != nullptr);
  14022. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14023. ASSERT_TRUE(ca_list != nullptr);
  14024. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14025. }
  14026. #endif
  14027. // ============================================================================
  14028. // MbedTLS-Specific Tests
  14029. // ============================================================================
  14030. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14031. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14032. using namespace httplib::tls;
  14033. // Track if callback was invoked
  14034. bool callback_invoked = false;
  14035. // The callback receives void* ctx which is actually MbedTlsContext*
  14036. // We can access the mbedtls_ssl_config via the context
  14037. auto setup_callback = [&callback_invoked](void *ctx) {
  14038. callback_invoked = true;
  14039. // Cast to MbedTlsContext* to access the ssl config
  14040. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14041. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14042. // Use static variables to hold certificate data (simplified for test)
  14043. static mbedtls_x509_crt own_cert;
  14044. static mbedtls_pk_context own_key;
  14045. static mbedtls_x509_crt ca_chain;
  14046. static bool initialized = false;
  14047. if (!initialized) {
  14048. mbedtls_x509_crt_init(&own_cert);
  14049. mbedtls_pk_init(&own_key);
  14050. mbedtls_x509_crt_init(&ca_chain);
  14051. // Load server certificate
  14052. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14053. return false;
  14054. }
  14055. // Load server private key
  14056. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14057. #if MBEDTLS_VERSION_MAJOR >= 3
  14058. ,
  14059. mbedtls_ctr_drbg_random, nullptr
  14060. #endif
  14061. ) != 0) {
  14062. return false;
  14063. }
  14064. // Load CA chain for client verification
  14065. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14066. return false;
  14067. }
  14068. initialized = true;
  14069. }
  14070. // Configure the SSL config
  14071. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14072. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14073. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14074. // Set minimum TLS version using mbedTLS native API
  14075. #if MBEDTLS_VERSION_MAJOR >= 3
  14076. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14077. #else
  14078. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14079. MBEDTLS_SSL_MINOR_VERSION_3);
  14080. #endif
  14081. return true;
  14082. };
  14083. SSLServer svr(setup_callback);
  14084. ASSERT_TRUE(svr.is_valid());
  14085. ASSERT_TRUE(callback_invoked);
  14086. svr.Get("/test", [&](const Request &req, Response &res) {
  14087. res.set_content("test", "text/plain");
  14088. auto cert = req.peer_cert();
  14089. ASSERT_TRUE(static_cast<bool>(cert));
  14090. auto common_name = cert.subject_cn();
  14091. EXPECT_EQ("Common Name", common_name);
  14092. });
  14093. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14094. auto se = detail::scope_exit([&] {
  14095. svr.stop();
  14096. t.join();
  14097. ASSERT_FALSE(svr.is_running());
  14098. });
  14099. svr.wait_until_ready();
  14100. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14101. cli.enable_server_certificate_verification(false);
  14102. cli.set_connection_timeout(30);
  14103. auto res = cli.Get("/test");
  14104. ASSERT_TRUE(res);
  14105. ASSERT_EQ(StatusCode::OK_200, res->status);
  14106. }
  14107. #endif
  14108. // WebSocket Tests
  14109. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14110. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14111. // defining the meaning of these bits has been negotiated.
  14112. auto make_frame = [](uint8_t first_byte) {
  14113. std::string frame;
  14114. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14115. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14116. frame += "Hello";
  14117. return frame;
  14118. };
  14119. // RSV1 set (0x40)
  14120. {
  14121. detail::BufferStream strm;
  14122. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14123. ws::Opcode opcode;
  14124. std::string payload;
  14125. bool fin;
  14126. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14127. false, 1024));
  14128. }
  14129. // RSV2 set (0x20)
  14130. {
  14131. detail::BufferStream strm;
  14132. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14133. ws::Opcode opcode;
  14134. std::string payload;
  14135. bool fin;
  14136. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14137. false, 1024));
  14138. }
  14139. // RSV3 set (0x10)
  14140. {
  14141. detail::BufferStream strm;
  14142. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14143. ws::Opcode opcode;
  14144. std::string payload;
  14145. bool fin;
  14146. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14147. false, 1024));
  14148. }
  14149. // No RSV bits set - should succeed
  14150. {
  14151. detail::BufferStream strm;
  14152. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14153. ws::Opcode opcode;
  14154. std::string payload;
  14155. bool fin;
  14156. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14157. false, 1024));
  14158. EXPECT_EQ(ws::Opcode::Text, opcode);
  14159. EXPECT_EQ("Hello", payload);
  14160. EXPECT_TRUE(fin);
  14161. }
  14162. }
  14163. TEST(WebSocketTest, ControlFrameValidation) {
  14164. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14165. // payload length <= 125.
  14166. // Ping with FIN=0 - must be rejected
  14167. {
  14168. detail::BufferStream strm;
  14169. std::string frame;
  14170. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14171. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14172. strm.write(frame.data(), frame.size());
  14173. ws::Opcode opcode;
  14174. std::string payload;
  14175. bool fin;
  14176. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14177. false, 1024));
  14178. }
  14179. // Close with FIN=0 - must be rejected
  14180. {
  14181. detail::BufferStream strm;
  14182. std::string frame;
  14183. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14184. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14185. strm.write(frame.data(), frame.size());
  14186. ws::Opcode opcode;
  14187. std::string payload;
  14188. bool fin;
  14189. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14190. false, 1024));
  14191. }
  14192. // Ping with payload_len=126 (extended length) - must be rejected
  14193. {
  14194. detail::BufferStream strm;
  14195. std::string frame;
  14196. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14197. frame += static_cast<char>(126); // payload_len=126 (>125)
  14198. frame += static_cast<char>(0x00); // extended length high byte
  14199. frame += static_cast<char>(126); // extended length low byte
  14200. frame += std::string(126, 'x');
  14201. strm.write(frame.data(), frame.size());
  14202. ws::Opcode opcode;
  14203. std::string payload;
  14204. bool fin;
  14205. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14206. false, 1024));
  14207. }
  14208. // Ping with FIN=1 and payload_len=125 - should succeed
  14209. {
  14210. detail::BufferStream strm;
  14211. std::string frame;
  14212. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14213. frame += static_cast<char>(125); // payload_len=125
  14214. frame += std::string(125, 'x');
  14215. strm.write(frame.data(), frame.size());
  14216. ws::Opcode opcode;
  14217. std::string payload;
  14218. bool fin;
  14219. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14220. false, 1024));
  14221. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14222. EXPECT_EQ(125u, payload.size());
  14223. EXPECT_TRUE(fin);
  14224. }
  14225. }
  14226. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14227. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14228. // length MUST be 0.
  14229. // MSB set - must be rejected
  14230. {
  14231. detail::BufferStream strm;
  14232. std::string frame;
  14233. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14234. frame += static_cast<char>(127); // 64-bit extended length
  14235. frame += static_cast<char>(0x80); // MSB set (invalid)
  14236. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14237. strm.write(frame.data(), frame.size());
  14238. ws::Opcode opcode;
  14239. std::string payload;
  14240. bool fin;
  14241. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14242. false, 1024));
  14243. }
  14244. // MSB clear - should pass length parsing (will be rejected by max_len,
  14245. // but that's a different check; use a small length to verify)
  14246. {
  14247. detail::BufferStream strm;
  14248. std::string frame;
  14249. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14250. frame += static_cast<char>(127); // 64-bit extended length
  14251. frame += std::string(7, '\0'); // high bytes = 0
  14252. frame += static_cast<char>(0x03); // length = 3
  14253. frame += "abc";
  14254. strm.write(frame.data(), frame.size());
  14255. ws::Opcode opcode;
  14256. std::string payload;
  14257. bool fin;
  14258. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14259. false, 1024));
  14260. EXPECT_EQ(ws::Opcode::Text, opcode);
  14261. EXPECT_EQ("abc", payload);
  14262. }
  14263. }
  14264. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14265. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14266. // Valid UTF-8
  14267. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14268. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14269. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14270. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14271. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14272. // Invalid UTF-8
  14273. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14274. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14275. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14276. EXPECT_FALSE(
  14277. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14278. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14279. }
  14280. TEST(WebSocketTest, ConnectAndDisconnect) {
  14281. Server svr;
  14282. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14283. std::string msg;
  14284. while (ws.read(msg)) {}
  14285. });
  14286. auto port = svr.bind_to_any_port(HOST);
  14287. std::thread t([&]() { svr.listen_after_bind(); });
  14288. svr.wait_until_ready();
  14289. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14290. ASSERT_TRUE(client.connect());
  14291. EXPECT_TRUE(client.is_open());
  14292. client.close();
  14293. EXPECT_FALSE(client.is_open());
  14294. svr.stop();
  14295. t.join();
  14296. }
  14297. TEST(WebSocketTest, ValidURL) {
  14298. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14299. EXPECT_TRUE(ws1.is_valid());
  14300. ws::WebSocketClient ws2("ws://example.com/path");
  14301. EXPECT_TRUE(ws2.is_valid());
  14302. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14303. EXPECT_TRUE(ws3.is_valid());
  14304. #ifdef CPPHTTPLIB_SSL_ENABLED
  14305. ws::WebSocketClient wss1("wss://example.com/path");
  14306. EXPECT_TRUE(wss1.is_valid());
  14307. ws::WebSocketClient wss2("wss://example.com:443/path");
  14308. EXPECT_TRUE(wss2.is_valid());
  14309. #endif
  14310. }
  14311. TEST(WebSocketTest, InvalidURL) {
  14312. // No scheme
  14313. ws::WebSocketClient ws1("localhost:8080/path");
  14314. EXPECT_FALSE(ws1.is_valid());
  14315. // No path
  14316. ws::WebSocketClient ws2("ws://localhost:8080");
  14317. EXPECT_FALSE(ws2.is_valid());
  14318. // Empty string
  14319. ws::WebSocketClient ws3("");
  14320. EXPECT_FALSE(ws3.is_valid());
  14321. // Missing host
  14322. ws::WebSocketClient ws4("ws://:8080/path");
  14323. EXPECT_FALSE(ws4.is_valid());
  14324. // Port number overflow — should not crash
  14325. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14326. EXPECT_FALSE(ws5.is_valid());
  14327. // Port out of range
  14328. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14329. EXPECT_FALSE(ws6.is_valid());
  14330. }
  14331. TEST(WebSocketTest, UnsupportedScheme) {
  14332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14333. ws::WebSocketClient ws1("http://localhost:8080/path");
  14334. EXPECT_FALSE(ws1.is_valid());
  14335. ws::WebSocketClient ws2("https://localhost:8080/path");
  14336. EXPECT_FALSE(ws2.is_valid());
  14337. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14338. EXPECT_FALSE(ws3.is_valid());
  14339. #else
  14340. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14341. std::invalid_argument);
  14342. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14343. std::invalid_argument);
  14344. #endif
  14345. }
  14346. TEST(WebSocketTest, ConnectWhenInvalid) {
  14347. ws::WebSocketClient ws("not a valid url");
  14348. EXPECT_FALSE(ws.is_valid());
  14349. EXPECT_FALSE(ws.connect());
  14350. }
  14351. TEST(WebSocketTest, DefaultPort) {
  14352. ws::WebSocketClient ws1("ws://example.com/path");
  14353. EXPECT_TRUE(ws1.is_valid());
  14354. // ws:// defaults to port 80 (verified by successful parse)
  14355. #ifdef CPPHTTPLIB_SSL_ENABLED
  14356. ws::WebSocketClient ws2("wss://example.com/path");
  14357. EXPECT_TRUE(ws2.is_valid());
  14358. // wss:// defaults to port 443 (verified by successful parse)
  14359. #endif
  14360. }
  14361. TEST(WebSocketTest, IPv6LiteralAddress) {
  14362. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14363. EXPECT_TRUE(ws1.is_valid());
  14364. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14365. EXPECT_TRUE(ws2.is_valid());
  14366. }
  14367. TEST(WebSocketTest, ComplexPath) {
  14368. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14369. EXPECT_TRUE(ws1.is_valid());
  14370. ws::WebSocketClient ws2("ws://localhost:8080/");
  14371. EXPECT_TRUE(ws2.is_valid());
  14372. }
  14373. class WebSocketIntegrationTest : public ::testing::Test {
  14374. protected:
  14375. void SetUp() override {
  14376. server_ = httplib::detail::make_unique<Server>();
  14377. setup_server();
  14378. start_server();
  14379. }
  14380. void TearDown() override {
  14381. server_->stop();
  14382. if (server_thread_.joinable()) { server_thread_.join(); }
  14383. }
  14384. void setup_server() {
  14385. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14386. std::string msg;
  14387. ws::ReadResult ret;
  14388. while ((ret = ws.read(msg))) {
  14389. if (ret == ws::Binary) {
  14390. ws.send(msg.data(), msg.size());
  14391. } else {
  14392. ws.send(msg);
  14393. }
  14394. }
  14395. });
  14396. server_->WebSocket("/ws-echo-string",
  14397. [](const Request &, ws::WebSocket &ws) {
  14398. std::string msg;
  14399. while (ws.read(msg)) {
  14400. ws.send("echo: " + msg);
  14401. }
  14402. });
  14403. server_->WebSocket(
  14404. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14405. // Echo back request metadata
  14406. ws.send("path:" + req.path);
  14407. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14408. std::string msg;
  14409. while (ws.read(msg)) {}
  14410. });
  14411. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14412. std::string msg;
  14413. ws.read(msg); // wait for a message
  14414. ws.close();
  14415. });
  14416. server_->WebSocket("/ws-close-status",
  14417. [](const Request &, ws::WebSocket &ws) {
  14418. std::string msg;
  14419. ws.read(msg); // wait for a message
  14420. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14421. });
  14422. server_->WebSocket(
  14423. "/ws-subprotocol",
  14424. [](const Request &, ws::WebSocket &ws) {
  14425. std::string msg;
  14426. while (ws.read(msg)) {
  14427. ws.send(msg);
  14428. }
  14429. },
  14430. [](const std::vector<std::string> &protocols) -> std::string {
  14431. for (const auto &p : protocols) {
  14432. if (p == "graphql-ws") { return p; }
  14433. }
  14434. return "";
  14435. });
  14436. }
  14437. void start_server() {
  14438. port_ = server_->bind_to_any_port(HOST);
  14439. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14440. server_->wait_until_ready();
  14441. }
  14442. std::unique_ptr<Server> server_;
  14443. std::thread server_thread_;
  14444. int port_ = 0;
  14445. };
  14446. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14448. "/ws-echo");
  14449. ASSERT_TRUE(client.connect());
  14450. ASSERT_TRUE(client.is_open());
  14451. ASSERT_TRUE(client.send("Hello WebSocket"));
  14452. std::string msg;
  14453. EXPECT_EQ(ws::Text, client.read(msg));
  14454. EXPECT_EQ("Hello WebSocket", msg);
  14455. client.close();
  14456. }
  14457. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14458. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14459. "/ws-echo");
  14460. ASSERT_TRUE(client.connect());
  14461. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14462. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14463. std::string msg;
  14464. EXPECT_EQ(ws::Binary, client.read(msg));
  14465. EXPECT_EQ(binary_data, msg);
  14466. client.close();
  14467. }
  14468. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14469. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14470. "/ws-echo");
  14471. ASSERT_TRUE(client.connect());
  14472. for (int i = 0; i < 10; i++) {
  14473. auto text = "message " + std::to_string(i);
  14474. ASSERT_TRUE(client.send(text));
  14475. std::string msg;
  14476. ASSERT_TRUE(client.read(msg));
  14477. EXPECT_EQ(text, msg);
  14478. }
  14479. client.close();
  14480. }
  14481. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14483. "/ws-close");
  14484. ASSERT_TRUE(client.connect());
  14485. // Send a message to trigger the server to close
  14486. ASSERT_TRUE(client.send("trigger close"));
  14487. // The server will close, so read should return false
  14488. std::string msg;
  14489. EXPECT_FALSE(client.read(msg));
  14490. EXPECT_FALSE(client.is_open());
  14491. }
  14492. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14493. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14494. "/ws-echo");
  14495. ASSERT_TRUE(client.connect());
  14496. // 128KB message
  14497. std::string large_data(128 * 1024, 'X');
  14498. ASSERT_TRUE(client.send(large_data));
  14499. std::string msg;
  14500. ASSERT_TRUE(client.read(msg));
  14501. EXPECT_EQ(large_data, msg);
  14502. client.close();
  14503. }
  14504. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14505. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14506. "/ws-echo");
  14507. ASSERT_TRUE(client.connect());
  14508. const int num_threads = 4;
  14509. std::vector<std::thread> threads;
  14510. std::atomic<int> send_count{0};
  14511. for (int t = 0; t < num_threads; t++) {
  14512. threads.emplace_back([&client, &send_count, t]() {
  14513. for (int i = 0; i < 5; i++) {
  14514. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14515. if (client.send(text)) { send_count++; }
  14516. }
  14517. });
  14518. }
  14519. for (auto &th : threads) {
  14520. th.join();
  14521. }
  14522. int received = 0;
  14523. std::string msg;
  14524. while (received < send_count.load()) {
  14525. if (!client.read(msg)) { break; }
  14526. received++;
  14527. }
  14528. EXPECT_EQ(send_count.load(), received);
  14529. client.close();
  14530. }
  14531. TEST_F(WebSocketIntegrationTest, ReadString) {
  14532. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14533. "/ws-echo-string");
  14534. ASSERT_TRUE(client.connect());
  14535. ASSERT_TRUE(client.send("hello"));
  14536. std::string msg;
  14537. ASSERT_TRUE(client.read(msg));
  14538. EXPECT_EQ("echo: hello", msg);
  14539. ASSERT_TRUE(client.send("world"));
  14540. ASSERT_TRUE(client.read(msg));
  14541. EXPECT_EQ("echo: world", msg);
  14542. client.close();
  14543. }
  14544. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14545. Headers headers = {{"X-Test-Header", "test-value"}};
  14546. ws::WebSocketClient client(
  14547. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14548. ASSERT_TRUE(client.connect());
  14549. std::string msg;
  14550. ASSERT_TRUE(client.read(msg));
  14551. EXPECT_EQ("path:/ws-request-info", msg);
  14552. ASSERT_TRUE(client.read(msg));
  14553. EXPECT_EQ("header:test-value", msg);
  14554. client.close();
  14555. }
  14556. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14558. "/ws-echo");
  14559. client.set_read_timeout(1, 0); // 1 second
  14560. ASSERT_TRUE(client.connect());
  14561. // Don't send anything — server echo handler waits for a message,
  14562. // so read() should time out and return false.
  14563. std::string msg;
  14564. EXPECT_FALSE(client.read(msg));
  14565. }
  14566. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14567. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14568. "/ws-echo");
  14569. client.set_read_timeout(5, 0);
  14570. ASSERT_TRUE(client.connect());
  14571. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14572. // The server should reject it and close the connection.
  14573. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14574. client.send(oversized);
  14575. // The server's read() should have failed due to payload limit,
  14576. // so our read() should return false (connection closed).
  14577. std::string msg;
  14578. EXPECT_FALSE(client.read(msg));
  14579. }
  14580. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14581. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14582. "/ws-echo");
  14583. client.set_read_timeout(10, 0);
  14584. ASSERT_TRUE(client.connect());
  14585. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14586. // This should succeed.
  14587. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14588. ASSERT_TRUE(client.send(at_limit));
  14589. std::string msg;
  14590. ASSERT_TRUE(client.read(msg));
  14591. EXPECT_EQ(at_limit.size(), msg.size());
  14592. client.close();
  14593. }
  14594. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14595. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14596. "/nonexistent");
  14597. EXPECT_FALSE(client.connect());
  14598. EXPECT_FALSE(client.is_open());
  14599. }
  14600. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14602. "/ws-echo");
  14603. ASSERT_TRUE(client.connect());
  14604. ASSERT_TRUE(client.send(""));
  14605. std::string msg;
  14606. EXPECT_EQ(ws::Text, client.read(msg));
  14607. EXPECT_EQ("", msg);
  14608. client.close();
  14609. }
  14610. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14612. "/ws-echo");
  14613. // First connection
  14614. ASSERT_TRUE(client.connect());
  14615. ASSERT_TRUE(client.send("first"));
  14616. std::string msg;
  14617. ASSERT_TRUE(client.read(msg));
  14618. EXPECT_EQ("first", msg);
  14619. client.close();
  14620. EXPECT_FALSE(client.is_open());
  14621. // Reconnect using the same client object
  14622. ASSERT_TRUE(client.connect());
  14623. ASSERT_TRUE(client.is_open());
  14624. ASSERT_TRUE(client.send("second"));
  14625. ASSERT_TRUE(client.read(msg));
  14626. EXPECT_EQ("second", msg);
  14627. client.close();
  14628. }
  14629. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14631. "/ws-close-status");
  14632. ASSERT_TRUE(client.connect());
  14633. // Trigger the server to close with GoingAway status
  14634. ASSERT_TRUE(client.send("trigger"));
  14635. // read() should return false after receiving the close frame
  14636. std::string msg;
  14637. EXPECT_FALSE(client.read(msg));
  14638. EXPECT_FALSE(client.is_open());
  14639. }
  14640. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14642. "/ws-echo");
  14643. ASSERT_TRUE(client.connect());
  14644. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14645. EXPECT_FALSE(client.is_open());
  14646. }
  14647. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14648. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14649. ws::WebSocketClient client(
  14650. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14651. ASSERT_TRUE(client.connect());
  14652. // Server should have selected graphql-ws
  14653. EXPECT_EQ("graphql-ws", client.subprotocol());
  14654. client.close();
  14655. }
  14656. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14657. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14658. ws::WebSocketClient client(
  14659. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14660. ASSERT_TRUE(client.connect());
  14661. // Server should not have selected any subprotocol
  14662. EXPECT_TRUE(client.subprotocol().empty());
  14663. client.close();
  14664. }
  14665. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14666. // Connect without requesting any subprotocol
  14667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14668. "/ws-subprotocol");
  14669. ASSERT_TRUE(client.connect());
  14670. EXPECT_TRUE(client.subprotocol().empty());
  14671. client.close();
  14672. }
  14673. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14675. "/ws-echo");
  14676. client.set_tcp_nodelay(true);
  14677. client.set_connection_timeout(3, 0);
  14678. bool socket_options_called = false;
  14679. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14680. ASSERT_TRUE(client.connect());
  14681. ASSERT_TRUE(client.is_open());
  14682. EXPECT_TRUE(socket_options_called);
  14683. ASSERT_TRUE(client.send("hello"));
  14684. std::string msg;
  14685. auto result = client.read(msg);
  14686. EXPECT_EQ(result, ws::ReadResult::Text);
  14687. EXPECT_EQ(msg, "hello");
  14688. client.close();
  14689. }
  14690. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14691. Server svr;
  14692. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14693. if (!req.has_header("Authorization")) {
  14694. res.status = StatusCode::Unauthorized_401;
  14695. res.set_content("Unauthorized", "text/plain");
  14696. return Server::HandlerResponse::Handled;
  14697. }
  14698. return Server::HandlerResponse::Unhandled;
  14699. });
  14700. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14701. std::string msg;
  14702. while (ws.read(msg)) {
  14703. ws.send(msg);
  14704. }
  14705. });
  14706. auto port = svr.bind_to_any_port("localhost");
  14707. std::thread t([&]() { svr.listen_after_bind(); });
  14708. svr.wait_until_ready();
  14709. // Without Authorization header - should be rejected before upgrade
  14710. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14711. EXPECT_FALSE(client1.connect());
  14712. // With Authorization header - should succeed
  14713. Headers headers = {{"Authorization", "Bearer token123"}};
  14714. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14715. headers);
  14716. ASSERT_TRUE(client2.connect());
  14717. ASSERT_TRUE(client2.send("hello"));
  14718. std::string msg;
  14719. ASSERT_TRUE(client2.read(msg));
  14720. EXPECT_EQ("hello", msg);
  14721. client2.close();
  14722. svr.stop();
  14723. t.join();
  14724. }
  14725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14726. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14727. protected:
  14728. void SetUp() override {
  14729. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14730. SERVER_PRIVATE_KEY_FILE);
  14731. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14732. std::string msg;
  14733. ws::ReadResult ret;
  14734. while ((ret = ws.read(msg))) {
  14735. if (ret == ws::Binary) {
  14736. ws.send(msg.data(), msg.size());
  14737. } else {
  14738. ws.send(msg);
  14739. }
  14740. }
  14741. });
  14742. port_ = server_->bind_to_any_port(HOST);
  14743. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14744. server_->wait_until_ready();
  14745. }
  14746. void TearDown() override {
  14747. server_->stop();
  14748. if (server_thread_.joinable()) { server_thread_.join(); }
  14749. }
  14750. std::unique_ptr<SSLServer> server_;
  14751. std::thread server_thread_;
  14752. int port_ = 0;
  14753. };
  14754. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14755. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14756. "/ws-echo");
  14757. client.enable_server_certificate_verification(false);
  14758. ASSERT_TRUE(client.connect());
  14759. ASSERT_TRUE(client.is_open());
  14760. ASSERT_TRUE(client.send("Hello WSS"));
  14761. std::string msg;
  14762. EXPECT_EQ(ws::Text, client.read(msg));
  14763. EXPECT_EQ("Hello WSS", msg);
  14764. client.close();
  14765. }
  14766. #endif
  14767. #if !defined(_WIN32)
  14768. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14769. auto secret_dir = std::string("./symlink_test_secret");
  14770. auto served_dir = std::string("./symlink_test_served");
  14771. auto secret_file = secret_dir + "/secret.txt";
  14772. auto symlink_path = served_dir + "/escape";
  14773. // Setup: create directories and files
  14774. mkdir(secret_dir.c_str(), 0755);
  14775. mkdir(served_dir.c_str(), 0755);
  14776. {
  14777. std::ofstream ofs(secret_file);
  14778. ofs << "SECRET_DATA";
  14779. }
  14780. // Create symlink using absolute path so it resolves correctly
  14781. #ifdef PATH_MAX
  14782. char abs_secret[PATH_MAX];
  14783. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14784. #else
  14785. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  14786. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  14787. ASSERT_NE(nullptr, abs_secret);
  14788. #endif
  14789. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14790. auto se = detail::scope_exit([&] {
  14791. unlink(symlink_path.c_str());
  14792. unlink(secret_file.c_str());
  14793. rmdir(served_dir.c_str());
  14794. rmdir(secret_dir.c_str());
  14795. });
  14796. Server svr;
  14797. svr.set_mount_point("/", served_dir);
  14798. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14799. auto se2 = detail::scope_exit([&] {
  14800. svr.stop();
  14801. listen_thread.join();
  14802. });
  14803. svr.wait_until_ready();
  14804. Client cli("localhost", PORT);
  14805. // Symlink pointing outside base dir should be blocked
  14806. auto res = cli.Get("/escape/secret.txt");
  14807. ASSERT_TRUE(res);
  14808. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14809. }
  14810. #endif
  14811. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14812. // A GET request with Content-Length to a static file handler must have its
  14813. // body drained before the keep-alive connection is reused. Otherwise the
  14814. // unread body bytes are interpreted as the next HTTP request.
  14815. //
  14816. // The body is sent AFTER receiving the first response (as in the original
  14817. // PoC) so that the stream_line_reader cannot buffer it together with the
  14818. // headers of the first request.
  14819. Server svr;
  14820. svr.set_mount_point("/", "./www");
  14821. std::atomic<int> smuggled_count(0);
  14822. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14823. smuggled_count++;
  14824. res.set_content("oops", "text/plain");
  14825. });
  14826. auto port = svr.bind_to_any_port("localhost");
  14827. thread t = thread([&] { svr.listen_after_bind(); });
  14828. auto se = detail::scope_exit([&] {
  14829. svr.stop();
  14830. t.join();
  14831. });
  14832. svr.wait_until_ready();
  14833. auto error = Error::Success;
  14834. auto sock = detail::create_client_socket(
  14835. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14836. /*connection_timeout_sec=*/2, 0,
  14837. /*read_timeout_sec=*/2, 0,
  14838. /*write_timeout_sec=*/2, 0, std::string(), error);
  14839. ASSERT_NE(INVALID_SOCKET, sock);
  14840. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14841. // The "smuggled" request will be sent as the body of the outer GET
  14842. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14843. "Host: localhost\r\n"
  14844. "Connection: close\r\n"
  14845. "\r\n";
  14846. // Step 1: Send only the outer request headers (no body yet)
  14847. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14848. "Host: localhost\r\n"
  14849. "Content-Length: " +
  14850. std::to_string(smuggled.size()) +
  14851. "\r\n"
  14852. "\r\n";
  14853. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14854. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14855. // Step 2: Read the first response (server serves file without reading body)
  14856. std::string first_response;
  14857. char buf[4096];
  14858. for (;;) {
  14859. auto n = recv(sock, buf, sizeof(buf), 0);
  14860. if (n <= 0) break;
  14861. first_response.append(buf, static_cast<size_t>(n));
  14862. // Stop once we have a complete response (headers + body)
  14863. auto hdr_end = first_response.find("\r\n\r\n");
  14864. if (hdr_end != std::string::npos) {
  14865. // Check for Content-Length to know when the body is complete
  14866. auto cl_pos = first_response.find("Content-Length:");
  14867. if (cl_pos != std::string::npos) {
  14868. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14869. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14870. auto cl = std::stoul(
  14871. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14872. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14873. } else {
  14874. break; // No Content-Length, assume headers-only response
  14875. }
  14876. }
  14877. }
  14878. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14879. // Step 3: Now send the body, which looks like a new HTTP request.
  14880. // On a vulnerable server the keep-alive loop reads this as a second request.
  14881. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14882. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14883. // Step 4: Try to read a second response (should NOT exist after fix)
  14884. std::string second_response;
  14885. for (;;) {
  14886. auto n = recv(sock, buf, sizeof(buf), 0);
  14887. if (n <= 0) break;
  14888. second_response.append(buf, static_cast<size_t>(n));
  14889. }
  14890. // The smuggled request must NOT have been processed
  14891. EXPECT_EQ(0, smuggled_count.load());
  14892. }
  14893. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14894. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14895. // must be rejected with 400 Bad Request.
  14896. Server svr;
  14897. svr.Post("/test", [&](const Request &, Response &res) {
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. thread t = thread([&] { svr.listen(HOST, PORT); });
  14901. auto se = detail::scope_exit([&] {
  14902. svr.stop();
  14903. t.join();
  14904. ASSERT_FALSE(svr.is_running());
  14905. });
  14906. svr.wait_until_ready();
  14907. // Exact "chunked"
  14908. {
  14909. auto req = "POST /test HTTP/1.1\r\n"
  14910. "Host: localhost\r\n"
  14911. "Content-Length: 5\r\n"
  14912. "Transfer-Encoding: chunked\r\n"
  14913. "Connection: close\r\n"
  14914. "\r\n"
  14915. "hello";
  14916. std::string response;
  14917. ASSERT_TRUE(send_request(1, req, &response));
  14918. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14919. response.substr(0, response.find("\r\n")));
  14920. }
  14921. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14922. {
  14923. auto req = "POST /test HTTP/1.1\r\n"
  14924. "Host: localhost\r\n"
  14925. "Content-Length: 5\r\n"
  14926. "Transfer-Encoding: gzip, chunked\r\n"
  14927. "Connection: close\r\n"
  14928. "\r\n"
  14929. "hello";
  14930. std::string response;
  14931. ASSERT_TRUE(send_request(1, req, &response));
  14932. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14933. response.substr(0, response.find("\r\n")));
  14934. }
  14935. }