1
0

test.cc 537 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514
  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. TEST(ConnectionErrorTest, InvalidHost) {
  1273. auto host = "-abcde.com";
  1274. #ifdef CPPHTTPLIB_SSL_ENABLED
  1275. auto port = 443;
  1276. SSLClient cli(host, port);
  1277. #else
  1278. auto port = 80;
  1279. Client cli(host, port);
  1280. #endif
  1281. cli.set_connection_timeout(std::chrono::seconds(2));
  1282. auto res = cli.Get("/");
  1283. ASSERT_TRUE(!res);
  1284. EXPECT_EQ(Error::Connection, res.error());
  1285. }
  1286. TEST(ConnectionErrorTest, InvalidHost2) {
  1287. auto host = "httpcan.org/";
  1288. #ifdef CPPHTTPLIB_SSL_ENABLED
  1289. SSLClient cli(host);
  1290. #else
  1291. Client cli(host);
  1292. #endif
  1293. cli.set_connection_timeout(std::chrono::seconds(2));
  1294. auto res = cli.Get("/");
  1295. ASSERT_TRUE(!res);
  1296. EXPECT_EQ(Error::Connection, res.error());
  1297. }
  1298. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1299. auto host = "httpcan.org/";
  1300. #ifdef CPPHTTPLIB_SSL_ENABLED
  1301. SSLClient cli(host);
  1302. #else
  1303. Client cli(host);
  1304. #endif
  1305. cli.set_connection_timeout(std::chrono::seconds(2));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(!res);
  1308. stringstream s;
  1309. s << "error code: " << res.error();
  1310. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1311. }
  1312. TEST(ConnectionErrorTest, InvalidPort) {
  1313. auto host = "localhost";
  1314. auto port = 44380;
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. SSLClient cli(host, port);
  1317. #else
  1318. Client cli(host, port);
  1319. #endif
  1320. cli.set_connection_timeout(std::chrono::seconds(2));
  1321. auto res = cli.Get("/");
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_TRUE(Error::Connection == res.error() ||
  1324. Error::ConnectionTimeout == res.error());
  1325. }
  1326. TEST(ConnectionErrorTest, Timeout_Online) {
  1327. auto host = "google.com";
  1328. #ifdef CPPHTTPLIB_SSL_ENABLED
  1329. auto port = 44380;
  1330. SSLClient cli(host, port);
  1331. #else
  1332. auto port = 8080;
  1333. Client cli(host, port);
  1334. #endif
  1335. cli.set_connection_timeout(std::chrono::seconds(2));
  1336. // only probe one address type so that the error reason
  1337. // correlates to the timed-out IPv4, not the unsupported
  1338. // IPv6 connection attempt
  1339. cli.set_address_family(AF_INET);
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1343. }
  1344. TEST(CancelTest, NoCancel_Online) {
  1345. auto host = "httpbingo.org";
  1346. auto path = std::string{"/range/32"};
  1347. #ifdef CPPHTTPLIB_SSL_ENABLED
  1348. auto port = 443;
  1349. SSLClient cli(host, port);
  1350. #else
  1351. auto port = 80;
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(5));
  1355. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1356. ASSERT_TRUE(res);
  1357. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1361. // Use /bytes with a large payload so that the DownloadProgress callback
  1362. // (which only fires for Content-Length responses) is invoked before the
  1363. // entire body is received, giving cancellation a chance to fire.
  1364. auto host = "httpbingo.org";
  1365. auto path = std::string{"/bytes/524288"};
  1366. #ifdef CPPHTTPLIB_SSL_ENABLED
  1367. auto port = 443;
  1368. SSLClient cli(host, port);
  1369. #else
  1370. auto port = 80;
  1371. Client cli(host, port);
  1372. #endif
  1373. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1374. cli.set_connection_timeout(std::chrono::seconds(5));
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, WithCancelLargePayload_Online) {
  1379. auto host = "httpbingo.org";
  1380. auto path = std::string{"/bytes/524288"};
  1381. #ifdef CPPHTTPLIB_SSL_ENABLED
  1382. auto port = 443;
  1383. SSLClient cli(host, port);
  1384. #else
  1385. auto port = 80;
  1386. Client cli(host, port);
  1387. #endif
  1388. cli.set_connection_timeout(std::chrono::seconds(5));
  1389. uint32_t count = 0;
  1390. auto res =
  1391. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1392. ASSERT_TRUE(!res);
  1393. EXPECT_EQ(Error::Canceled, res.error());
  1394. }
  1395. TEST(CancelTest, NoCancelPost) {
  1396. Server svr;
  1397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1398. res.set_content("Hello World!", "text/plain");
  1399. });
  1400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1401. auto se = detail::scope_exit([&] {
  1402. svr.stop();
  1403. thread.join();
  1404. ASSERT_FALSE(svr.is_running());
  1405. });
  1406. svr.wait_until_ready();
  1407. Client cli(HOST, PORT);
  1408. cli.set_connection_timeout(std::chrono::seconds(5));
  1409. auto res =
  1410. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1411. "application/json", [](uint64_t, uint64_t) { return true; });
  1412. ASSERT_TRUE(res);
  1413. EXPECT_EQ("Hello World!", res->body);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. }
  1416. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1417. Server svr;
  1418. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1419. res.set_content("Hello World!", "text/plain");
  1420. });
  1421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1422. auto se = detail::scope_exit([&] {
  1423. svr.stop();
  1424. thread.join();
  1425. ASSERT_FALSE(svr.is_running());
  1426. });
  1427. svr.wait_until_ready();
  1428. Client cli(HOST, PORT);
  1429. cli.set_connection_timeout(std::chrono::seconds(5));
  1430. auto res =
  1431. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1432. "application/json", [](uint64_t, uint64_t) { return false; });
  1433. ASSERT_TRUE(!res);
  1434. EXPECT_EQ(Error::Canceled, res.error());
  1435. }
  1436. TEST(CancelTest, WithCancelLargePayloadPost) {
  1437. Server svr;
  1438. svr.set_payload_max_length(200 * 1024 * 1024);
  1439. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1440. res.set_content(LARGE_DATA, "text/plain");
  1441. });
  1442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. thread.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. Client cli(HOST, PORT);
  1450. cli.set_payload_max_length(200 * 1024 * 1024);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPut) {
  1459. Server svr;
  1460. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1480. Server svr;
  1481. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPut) {
  1500. Server svr;
  1501. svr.set_payload_max_length(200 * 1024 * 1024);
  1502. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1503. res.set_content(LARGE_DATA, "text/plain");
  1504. });
  1505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1506. auto se = detail::scope_exit([&] {
  1507. svr.stop();
  1508. thread.join();
  1509. ASSERT_FALSE(svr.is_running());
  1510. });
  1511. svr.wait_until_ready();
  1512. Client cli(HOST, PORT);
  1513. cli.set_payload_max_length(200 * 1024 * 1024);
  1514. cli.set_connection_timeout(std::chrono::seconds(5));
  1515. auto res =
  1516. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1517. "application/json", [](uint64_t, uint64_t) { return false; });
  1518. ASSERT_TRUE(!res);
  1519. EXPECT_EQ(Error::Canceled, res.error());
  1520. }
  1521. TEST(CancelTest, NoCancelPatch) {
  1522. Server svr;
  1523. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1524. res.set_content("Hello World!", "text/plain");
  1525. });
  1526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. thread.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. Client cli(HOST, PORT);
  1534. cli.set_connection_timeout(std::chrono::seconds(5));
  1535. auto res =
  1536. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1537. "application/json", [](uint64_t, uint64_t) { return true; });
  1538. ASSERT_TRUE(res);
  1539. EXPECT_EQ("Hello World!", res->body);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. }
  1542. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1543. Server svr;
  1544. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return false; });
  1559. ASSERT_TRUE(!res);
  1560. EXPECT_EQ(Error::Canceled, res.error());
  1561. }
  1562. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1563. Server svr;
  1564. svr.set_payload_max_length(200 * 1024 * 1024);
  1565. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content(LARGE_DATA, "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_payload_max_length(200 * 1024 * 1024);
  1577. cli.set_connection_timeout(std::chrono::seconds(5));
  1578. auto res =
  1579. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1580. "application/json", [](uint64_t, uint64_t) { return false; });
  1581. ASSERT_TRUE(!res);
  1582. EXPECT_EQ(Error::Canceled, res.error());
  1583. }
  1584. TEST(CancelTest, NoCancelDelete) {
  1585. Server svr;
  1586. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content("Hello World!", "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_connection_timeout(std::chrono::seconds(5));
  1598. auto res =
  1599. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1600. "application/json", [](uint64_t, uint64_t) { return true; });
  1601. ASSERT_TRUE(res);
  1602. EXPECT_EQ("Hello World!", res->body);
  1603. EXPECT_EQ(StatusCode::OK_200, res->status);
  1604. }
  1605. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1606. Server svr;
  1607. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return false; });
  1622. ASSERT_TRUE(!res);
  1623. EXPECT_EQ(Error::Canceled, res.error());
  1624. }
  1625. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1626. Server svr;
  1627. svr.set_payload_max_length(200 * 1024 * 1024);
  1628. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content(LARGE_DATA, "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_payload_max_length(200 * 1024 * 1024);
  1640. cli.set_connection_timeout(std::chrono::seconds(5));
  1641. auto res =
  1642. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1643. "application/json", [](uint64_t, uint64_t) { return false; });
  1644. ASSERT_TRUE(!res);
  1645. EXPECT_EQ(Error::Canceled, res.error());
  1646. }
  1647. static std::string remove_whitespace(const std::string &input) {
  1648. std::string output;
  1649. output.reserve(input.size());
  1650. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1651. [](unsigned char c) { return !std::isspace(c); });
  1652. return output;
  1653. }
  1654. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1655. auto host = "httpbingo.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #ifdef CPPHTTPLIB_SSL_ENABLED
  1658. auto port = 443;
  1659. SSLClient cli(host, port);
  1660. #else
  1661. auto port = 80;
  1662. Client cli(host, port);
  1663. #endif
  1664. {
  1665. auto res = cli.Get(path);
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1668. }
  1669. {
  1670. auto res =
  1671. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1672. ASSERT_TRUE(res);
  1673. auto body = remove_whitespace(res->body);
  1674. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1675. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. {
  1679. cli.set_basic_auth("hello", "world");
  1680. auto res = cli.Get(path);
  1681. ASSERT_TRUE(res);
  1682. auto body = remove_whitespace(res->body);
  1683. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1684. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1685. EXPECT_EQ(StatusCode::OK_200, res->status);
  1686. }
  1687. {
  1688. cli.set_basic_auth("hello", "bad");
  1689. auto res = cli.Get(path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_basic_auth("bad", "world");
  1695. auto res = cli.Get(path);
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1698. }
  1699. }
  1700. #ifdef CPPHTTPLIB_SSL_ENABLED
  1701. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1702. auto host = "httpbingo.org";
  1703. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1704. auto paths = std::vector<std::string>{
  1705. "/digest-auth/auth/hello/world/MD5",
  1706. "/digest-auth/auth/hello/world/SHA-256",
  1707. };
  1708. auto port = 443;
  1709. SSLClient cli(host, port);
  1710. {
  1711. auto res = cli.Get(unauth_path);
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1714. }
  1715. {
  1716. cli.set_digest_auth("hello", "world");
  1717. for (const auto &path : paths) {
  1718. auto res = cli.Get(path.c_str());
  1719. ASSERT_TRUE(res);
  1720. auto body = remove_whitespace(res->body);
  1721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. cli.set_digest_auth("hello", "bad");
  1726. for (const auto &path : paths) {
  1727. auto res = cli.Get(path.c_str());
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1730. }
  1731. }
  1732. }
  1733. #endif
  1734. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1735. auto host = "google.com";
  1736. auto another_host = "example.com";
  1737. auto wrong_ip = "0.0.0.0";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(res);
  1746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1747. }
  1748. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1749. auto host = "google.com";
  1750. auto wrong_ip = "0.0.0.0";
  1751. #ifdef CPPHTTPLIB_SSL_ENABLED
  1752. SSLClient cli(host);
  1753. #else
  1754. Client cli(host);
  1755. #endif
  1756. cli.set_hostname_addr_map({{host, wrong_ip}});
  1757. auto res = cli.Get("/");
  1758. ASSERT_TRUE(!res);
  1759. EXPECT_EQ(Error::Connection, res.error());
  1760. }
  1761. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1762. auto host = "httpbingo.org";
  1763. auto path = std::string{"/absolute-redirect/3"};
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get(path);
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(RedirectTest, Redirect_Online) {
  1775. auto host = "httpbingo.org";
  1776. auto path = std::string{"/redirect/3"};
  1777. #ifdef CPPHTTPLIB_SSL_ENABLED
  1778. SSLClient cli(host);
  1779. #else
  1780. Client cli(host);
  1781. #endif
  1782. cli.set_follow_location(true);
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::OK_200, res->status);
  1786. }
  1787. TEST(RelativeRedirectTest, Redirect_Online) {
  1788. auto host = "httpbingo.org";
  1789. auto path = std::string{"/relative-redirect/3"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. SSLClient cli(host);
  1792. #else
  1793. Client cli(host);
  1794. #endif
  1795. cli.set_follow_location(true);
  1796. auto res = cli.Get(path);
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::OK_200, res->status);
  1799. }
  1800. TEST(TooManyRedirectTest, Redirect_Online) {
  1801. auto host = "httpbingo.org";
  1802. auto path = std::string{"/redirect/21"};
  1803. #ifdef CPPHTTPLIB_SSL_ENABLED
  1804. SSLClient cli(host);
  1805. #else
  1806. Client cli(host);
  1807. #endif
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get(path);
  1810. ASSERT_TRUE(!res);
  1811. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1812. }
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. TEST(YahooRedirectTest, Redirect_Online) {
  1815. Client cli("yahoo.com");
  1816. auto res = cli.Get("/");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1819. cli.set_follow_location(true);
  1820. res = cli.Get("/");
  1821. ASSERT_TRUE(res);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1824. }
  1825. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1826. #define REDIR_HOST "httpbingo.org"
  1827. #define REDIR_PATH "/redirect-to"
  1828. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1829. SSLClient cli(REDIR_HOST);
  1830. cli.set_follow_location(true);
  1831. auto res =
  1832. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1833. ASSERT_TRUE(res);
  1834. EXPECT_EQ(StatusCode::OK_200, res->status);
  1835. }
  1836. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1837. SSLClient cli(REDIR_HOST);
  1838. cli.set_follow_location(true);
  1839. Params params;
  1840. params.emplace("url", "http://example.com");
  1841. params.emplace("status_code", "302");
  1842. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1847. SSLClient cli(REDIR_HOST);
  1848. cli.set_follow_location(true);
  1849. Params params;
  1850. params.emplace("url", "http://example.com");
  1851. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(UrlWithSpace, Redirect_Online) {
  1856. SSLClient cli("edge.forgecdn.net");
  1857. cli.set_follow_location(true);
  1858. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::OK_200, res->status);
  1861. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1862. }
  1863. #endif
  1864. #if !defined(_WIN32) && !defined(_WIN64)
  1865. TEST(ReceiveSignals, Signal) {
  1866. auto setupSignalHandlers = []() {
  1867. struct sigaction act;
  1868. sigemptyset(&act.sa_mask);
  1869. act.sa_flags = SA_SIGINFO;
  1870. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1871. switch (sig) {
  1872. case SIGINT:
  1873. default: break;
  1874. }
  1875. };
  1876. ::sigaction(SIGINT, &act, nullptr);
  1877. };
  1878. Server svr;
  1879. int port = 0;
  1880. auto thread = std::thread([&]() {
  1881. setupSignalHandlers();
  1882. port = svr.bind_to_any_port(HOST);
  1883. svr.listen_after_bind();
  1884. });
  1885. auto se = detail::scope_exit([&] {
  1886. svr.stop();
  1887. thread.join();
  1888. ASSERT_FALSE(svr.is_running());
  1889. });
  1890. svr.wait_until_ready();
  1891. ASSERT_TRUE(svr.is_running());
  1892. pthread_kill(thread.native_handle(), SIGINT);
  1893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1894. ASSERT_TRUE(svr.is_running());
  1895. }
  1896. #endif
  1897. TEST(RedirectToDifferentPort, Redirect) {
  1898. Server svr1;
  1899. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1900. res.set_content("Hello World!", "text/plain");
  1901. });
  1902. int svr1_port = 0;
  1903. auto thread1 = std::thread([&]() {
  1904. svr1_port = svr1.bind_to_any_port(HOST);
  1905. svr1.listen_after_bind();
  1906. });
  1907. Server svr2;
  1908. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1909. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1910. });
  1911. int svr2_port = 0;
  1912. auto thread2 = std::thread([&]() {
  1913. svr2_port = svr2.bind_to_any_port(HOST);
  1914. svr2.listen_after_bind();
  1915. });
  1916. auto se = detail::scope_exit([&] {
  1917. svr2.stop();
  1918. thread2.join();
  1919. svr1.stop();
  1920. thread1.join();
  1921. ASSERT_FALSE(svr2.is_running());
  1922. ASSERT_FALSE(svr1.is_running());
  1923. });
  1924. svr1.wait_until_ready();
  1925. svr2.wait_until_ready();
  1926. Client cli("localhost", svr2_port);
  1927. cli.set_follow_location(true);
  1928. auto res = cli.Get("/2");
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(StatusCode::OK_200, res->status);
  1931. EXPECT_EQ("Hello World!", res->body);
  1932. }
  1933. static void
  1934. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1935. Server svr1;
  1936. std::string captured_authorization;
  1937. svr1.Get("/target", [&](const Request &req, Response &res) {
  1938. captured_authorization = req.get_header_value("Authorization");
  1939. res.set_content("OK", "text/plain");
  1940. });
  1941. int svr1_port = 0;
  1942. auto thread1 = std::thread([&]() {
  1943. svr1_port = svr1.bind_to_any_port(HOST);
  1944. svr1.listen_after_bind();
  1945. });
  1946. Server svr2;
  1947. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1948. res.set_redirect(
  1949. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1950. });
  1951. int svr2_port = 0;
  1952. auto thread2 = std::thread([&]() {
  1953. svr2_port = svr2.bind_to_any_port(HOST);
  1954. svr2.listen_after_bind();
  1955. });
  1956. auto se = detail::scope_exit([&] {
  1957. svr2.stop();
  1958. thread2.join();
  1959. svr1.stop();
  1960. thread1.join();
  1961. ASSERT_FALSE(svr2.is_running());
  1962. ASSERT_FALSE(svr1.is_running());
  1963. });
  1964. svr1.wait_until_ready();
  1965. svr2.wait_until_ready();
  1966. Client cli("localhost", svr2_port);
  1967. cli.set_follow_location(true);
  1968. set_auth(cli);
  1969. auto res = cli.Get("/redir");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1973. EXPECT_TRUE(captured_authorization.empty());
  1974. }
  1975. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1976. TestDoNotForwardCredentialsOnRedirect(
  1977. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1978. }
  1979. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1980. TestDoNotForwardCredentialsOnRedirect(
  1981. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1982. }
  1983. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1984. Server svr;
  1985. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1986. // Port number that overflows int — should not crash
  1987. res.set_redirect("http://localhost:99999999999999999999/target");
  1988. });
  1989. auto port = svr.bind_to_any_port(HOST);
  1990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, port);
  1998. cli.set_follow_location(true);
  1999. auto res = cli.Get("/redir");
  2000. // Should fail gracefully, not crash (no valid response due to bad port)
  2001. EXPECT_FALSE(res);
  2002. }
  2003. TEST(RedirectFromPageWithContent, Redirect) {
  2004. Server svr;
  2005. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2006. res.set_content("___", "text/plain");
  2007. res.set_redirect("/2");
  2008. });
  2009. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli("localhost", PORT);
  2021. cli.set_follow_location(true);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. EXPECT_EQ("Hello World!", body);
  2030. }
  2031. {
  2032. Client cli("localhost", PORT);
  2033. std::string body;
  2034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2035. body.append(data, data_length);
  2036. return true;
  2037. });
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::Found_302, res->status);
  2040. EXPECT_EQ("___", body);
  2041. }
  2042. }
  2043. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2044. Server svr;
  2045. auto port_str = std::to_string(PORT);
  2046. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2047. auto expected_host = "[::1]:" + port_str;
  2048. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2049. res.set_content("___", "text/plain");
  2050. // res.set_redirect("/2");
  2051. res.set_redirect(redirect_url);
  2052. });
  2053. svr.Get("/2", [&](const Request &req, Response &res) {
  2054. auto host_header = req.headers.find("Host");
  2055. ASSERT_TRUE(host_header != req.headers.end());
  2056. EXPECT_EQ(expected_host, host_header->second);
  2057. res.set_content("Hello World!", "text/plain");
  2058. });
  2059. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2060. auto se = detail::scope_exit([&] {
  2061. svr.stop();
  2062. th.join();
  2063. ASSERT_FALSE(svr.is_running());
  2064. });
  2065. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2066. // actually starts anything, so the condition !svr.is_running() will
  2067. // always remain true, and the loop never stops.
  2068. // This basically counts how many milliseconds have passed since the
  2069. // call to svr.listen(), and if after 5 seconds nothing started yet
  2070. // aborts the test.
  2071. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2072. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2073. ASSERT_LT(milliseconds, 5000U);
  2074. }
  2075. {
  2076. Client cli("::1", PORT);
  2077. cli.set_follow_location(true);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::OK_200, res->status);
  2085. EXPECT_EQ("Hello World!", body);
  2086. }
  2087. {
  2088. Client cli("::1", PORT);
  2089. std::string body;
  2090. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2091. body.append(data, data_length);
  2092. return true;
  2093. });
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::Found_302, res->status);
  2096. EXPECT_EQ("___", body);
  2097. }
  2098. }
  2099. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2100. Server svr;
  2101. svr.Get("/foo", [](const Request &req, Response &res) {
  2102. auto a = req.params.find("a");
  2103. if (a != req.params.end()) {
  2104. res.set_content((*a).second, "text/plain");
  2105. res.status = StatusCode::OK_200;
  2106. } else {
  2107. res.status = StatusCode::BadRequest_400;
  2108. }
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. {
  2118. Client cli(HOST, PORT);
  2119. cli.set_path_encode(false);
  2120. auto res = cli.Get("/foo?a=explicitly+encoded");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(StatusCode::OK_200, res->status);
  2123. // This expects it back with a space, as the `+` won't have been
  2124. // url-encoded, and server-side the params get decoded turning `+`
  2125. // into spaces.
  2126. EXPECT_EQ("explicitly encoded", res->body);
  2127. }
  2128. }
  2129. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2130. Server svr;
  2131. svr.Get("/", [](const Request &req, Response &) {
  2132. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. {
  2142. Client cli(HOST, PORT);
  2143. cli.set_path_encode(false);
  2144. auto res = cli.Get("/?something=%0A");
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. }
  2148. }
  2149. TEST(BindServerTest, BindDualStack) {
  2150. Server svr;
  2151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2152. res.set_content("Hello World!", "text/plain");
  2153. });
  2154. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2155. auto se = detail::scope_exit([&] {
  2156. svr.stop();
  2157. thread.join();
  2158. ASSERT_FALSE(svr.is_running());
  2159. });
  2160. svr.wait_until_ready();
  2161. {
  2162. Client cli("127.0.0.1", PORT);
  2163. auto res = cli.Get("/1");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ("Hello World!", res->body);
  2167. }
  2168. {
  2169. Client cli("::1", PORT);
  2170. auto res = cli.Get("/1");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. EXPECT_EQ("Hello World!", res->body);
  2174. }
  2175. }
  2176. TEST(BindServerTest, BindAndListenSeparately) {
  2177. Server svr;
  2178. int port = svr.bind_to_any_port("0.0.0.0");
  2179. ASSERT_TRUE(svr.is_valid());
  2180. ASSERT_TRUE(port > 0);
  2181. svr.stop();
  2182. }
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2186. CLIENT_CA_CERT_DIR);
  2187. int port = svr.bind_to_any_port("0.0.0.0");
  2188. ASSERT_TRUE(svr.is_valid());
  2189. ASSERT_TRUE(port > 0);
  2190. svr.stop();
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2193. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2194. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2195. int port = svr.bind_to_any_port("0.0.0.0");
  2196. ASSERT_TRUE(svr.is_valid());
  2197. ASSERT_TRUE(port > 0);
  2198. svr.stop();
  2199. }
  2200. TEST(BindServerTest, UpdateCertsPem) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2202. int port = svr.bind_to_any_port("0.0.0.0");
  2203. ASSERT_TRUE(svr.is_valid());
  2204. ASSERT_TRUE(port > 0);
  2205. // Read PEM files
  2206. std::string cert_pem, key_pem, ca_pem;
  2207. read_file(SERVER_CERT_FILE, cert_pem);
  2208. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2209. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2210. // Update server certificates using PEM API
  2211. ASSERT_TRUE(
  2212. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2213. ASSERT_TRUE(svr.is_valid());
  2214. svr.stop();
  2215. }
  2216. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2217. // Start server with client CA (enables client auth)
  2218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2219. ASSERT_TRUE(svr.is_valid());
  2220. bool handler_called = false;
  2221. svr.Get("/test", [&](const Request &req, Response &res) {
  2222. handler_called = true;
  2223. // Verify client certificate is present
  2224. auto cert = req.peer_cert();
  2225. EXPECT_TRUE(static_cast<bool>(cert));
  2226. res.set_content("ok", "text/plain");
  2227. });
  2228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. t.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. // Read PEM files
  2236. std::string cert_pem, key_pem, ca_pem;
  2237. read_file(SERVER_CERT_FILE, cert_pem);
  2238. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2239. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2240. // Update server certificates and client CA using PEM API while server running
  2241. ASSERT_TRUE(
  2242. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2243. // Connect with client certificate
  2244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2245. cli.enable_server_certificate_verification(false);
  2246. cli.set_connection_timeout(30);
  2247. auto res = cli.Get("/test");
  2248. ASSERT_TRUE(res);
  2249. ASSERT_EQ(StatusCode::OK_200, res->status);
  2250. ASSERT_TRUE(handler_called);
  2251. EXPECT_EQ("ok", res->body);
  2252. }
  2253. #endif
  2254. TEST(ErrorHandlerTest, ContentLength) {
  2255. Server svr;
  2256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2257. res.status = StatusCode::OK_200;
  2258. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2259. "text/html"); // <= Content-Length still 13
  2260. });
  2261. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2262. res.set_content("Hello World!\n", "text/plain");
  2263. res.status = 524;
  2264. });
  2265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2266. auto se = detail::scope_exit([&] {
  2267. svr.stop();
  2268. thread.join();
  2269. ASSERT_FALSE(svr.is_running());
  2270. });
  2271. svr.wait_until_ready();
  2272. {
  2273. Client cli(HOST, PORT);
  2274. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2278. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2280. }
  2281. }
  2282. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2283. TEST(ExceptionTest, WithoutExceptionHandler) {
  2284. Server svr;
  2285. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2286. throw std::runtime_error("exception...");
  2287. });
  2288. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2289. throw std::runtime_error("exception\r\n...");
  2290. });
  2291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. listen_thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. Client cli("localhost", PORT);
  2299. {
  2300. auto res = cli.Get("/exception");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2303. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2304. }
  2305. {
  2306. auto res = cli.Get("/unknown");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2310. }
  2311. }
  2312. TEST(ExceptionTest, WithExceptionHandler) {
  2313. Server svr;
  2314. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2315. std::exception_ptr ep) {
  2316. EXPECT_FALSE(ep == nullptr);
  2317. try {
  2318. std::rethrow_exception(ep);
  2319. } catch (std::exception &e) {
  2320. EXPECT_EQ("abc", std::string(e.what()));
  2321. } catch (...) {}
  2322. res.status = StatusCode::InternalServerError_500;
  2323. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2324. "text/html"); // <= Content-Length still 13 at this point
  2325. });
  2326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2327. res.set_content("Hello World!\n", "text/plain");
  2328. throw std::runtime_error("abc");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. for (size_t i = 0; i < 10; i++) {
  2338. Client cli(HOST, PORT);
  2339. for (size_t j = 0; j < 100; j++) {
  2340. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2344. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2345. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2346. }
  2347. cli.set_keep_alive(true);
  2348. for (size_t j = 0; j < 100; j++) {
  2349. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2353. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2354. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2355. }
  2356. }
  2357. }
  2358. TEST(ExceptionTest, AndErrorHandler) {
  2359. Server svr;
  2360. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2361. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2362. });
  2363. svr.set_exception_handler(
  2364. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2365. EXPECT_FALSE(ep == nullptr);
  2366. try {
  2367. std::rethrow_exception(ep);
  2368. } catch (std::exception &e) {
  2369. res.set_content(e.what(), "text/html");
  2370. } catch (...) {}
  2371. res.status = StatusCode::InternalServerError_500;
  2372. });
  2373. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2374. throw std::runtime_error("EXCEPTION");
  2375. });
  2376. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2377. res.set_content("ERROR", "text/html");
  2378. res.status = StatusCode::InternalServerError_500;
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. {
  2389. auto res = cli.Get("/exception");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2392. EXPECT_EQ("EXCEPTION", res->body);
  2393. }
  2394. {
  2395. auto res = cli.Get("/error");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2398. EXPECT_EQ("ERROR", res->body);
  2399. }
  2400. {
  2401. auto res = cli.Get("/invalid");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("NOT_FOUND", res->body);
  2405. }
  2406. }
  2407. #endif
  2408. TEST(NoContentTest, ContentLength) {
  2409. Server svr;
  2410. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2411. res.status = StatusCode::NoContent_204;
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. {
  2421. Client cli(HOST, PORT);
  2422. auto res = cli.Get("/hi");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2425. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2426. }
  2427. }
  2428. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2429. #ifdef CPPHTTPLIB_SSL_ENABLED
  2430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2431. ASSERT_TRUE(svr.is_valid());
  2432. #else
  2433. Server svr;
  2434. #endif
  2435. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("PRE_ROUTING", "on");
  2438. res.set_content("Routing Handler", "text/plain");
  2439. return httplib::Server::HandlerResponse::Handled;
  2440. }
  2441. return httplib::Server::HandlerResponse::Unhandled;
  2442. });
  2443. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2444. res.set_content("Error", "text/html");
  2445. });
  2446. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2447. if (req.path == "/routing_handler") {
  2448. res.set_header("POST_ROUTING", "on");
  2449. }
  2450. });
  2451. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2452. res.set_content("Hello World!\n", "text/plain");
  2453. });
  2454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2455. auto se = detail::scope_exit([&] {
  2456. svr.stop();
  2457. thread.join();
  2458. ASSERT_FALSE(svr.is_running());
  2459. });
  2460. svr.wait_until_ready();
  2461. {
  2462. #ifdef CPPHTTPLIB_SSL_ENABLED
  2463. SSLClient cli(HOST, PORT);
  2464. cli.enable_server_certificate_verification(false);
  2465. #else
  2466. Client cli(HOST, PORT);
  2467. #endif
  2468. auto res = cli.Get("/routing_handler");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("Routing Handler", res->body);
  2472. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2473. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2474. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2475. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2476. }
  2477. {
  2478. #ifdef CPPHTTPLIB_SSL_ENABLED
  2479. SSLClient cli(HOST, PORT);
  2480. cli.enable_server_certificate_verification(false);
  2481. #else
  2482. Client cli(HOST, PORT);
  2483. #endif
  2484. auto res = cli.Get("/hi");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Hello World!\n", res->body);
  2488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2490. }
  2491. {
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(HOST, PORT);
  2494. cli.enable_server_certificate_verification(false);
  2495. #else
  2496. Client cli(HOST, PORT);
  2497. #endif
  2498. auto res = cli.Get("/aaa");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2501. EXPECT_EQ("Error", res->body);
  2502. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2503. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2504. }
  2505. }
  2506. TEST(RequestHandlerTest, PreRequestHandler) {
  2507. auto route_path = "/user/:user";
  2508. Server svr;
  2509. svr.Get("/hi", [](const Request &, Response &res) {
  2510. res.set_content("hi", "text/plain");
  2511. });
  2512. svr.Get(route_path, [](const Request &req, Response &res) {
  2513. res.set_content(req.path_params.at("user"), "text/plain");
  2514. });
  2515. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2516. if (req.matched_route == route_path) {
  2517. auto user = req.path_params.at("user");
  2518. if (user != "john") {
  2519. res.status = StatusCode::Forbidden_403;
  2520. res.set_content("error", "text/html");
  2521. return Server::HandlerResponse::Handled;
  2522. }
  2523. }
  2524. return Server::HandlerResponse::Unhandled;
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. {
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. EXPECT_EQ("hi", res->body);
  2539. }
  2540. {
  2541. auto res = cli.Get("/user/john");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. EXPECT_EQ("john", res->body);
  2545. }
  2546. {
  2547. auto res = cli.Get("/user/invalid-user");
  2548. ASSERT_TRUE(res);
  2549. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2550. EXPECT_EQ("error", res->body);
  2551. }
  2552. }
  2553. TEST(AnyTest, BasicOperations) {
  2554. // Default construction
  2555. httplib::any a;
  2556. EXPECT_FALSE(a.has_value());
  2557. // Value construction and any_cast (pointer form, noexcept)
  2558. httplib::any b(42);
  2559. EXPECT_TRUE(b.has_value());
  2560. auto *p = httplib::any_cast<int>(&b);
  2561. ASSERT_NE(nullptr, p);
  2562. EXPECT_EQ(42, *p);
  2563. // Type mismatch → nullptr
  2564. auto *q = httplib::any_cast<std::string>(&b);
  2565. EXPECT_EQ(nullptr, q);
  2566. // any_cast (value form) succeeds
  2567. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2568. // any_cast (value form) throws on type mismatch
  2569. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2570. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2571. #endif
  2572. // Copy
  2573. httplib::any c = b;
  2574. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2575. // Move
  2576. httplib::any d = std::move(c);
  2577. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2578. // Assignment with different type
  2579. b = std::string("hello");
  2580. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2581. // Reset
  2582. b.reset();
  2583. EXPECT_FALSE(b.has_value());
  2584. }
  2585. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2586. struct AuthCtx {
  2587. std::string user_id;
  2588. };
  2589. Server svr;
  2590. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2591. res.user_data["auth"] = AuthCtx{"alice"};
  2592. return Server::HandlerResponse::Unhandled;
  2593. });
  2594. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2595. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2596. ASSERT_NE(nullptr, ctx);
  2597. res.set_content("Hello " + ctx->user_id, "text/plain");
  2598. });
  2599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2600. auto se = detail::scope_exit([&] {
  2601. svr.stop();
  2602. thread.join();
  2603. ASSERT_FALSE(svr.is_running());
  2604. });
  2605. svr.wait_until_ready();
  2606. Client cli(HOST, PORT);
  2607. auto res = cli.Get("/me");
  2608. ASSERT_TRUE(res);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. EXPECT_EQ("Hello alice", res->body);
  2611. }
  2612. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2613. struct RoleCtx {
  2614. std::string role;
  2615. };
  2616. Server svr;
  2617. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2618. res.user_data["role"] = RoleCtx{"admin"};
  2619. return Server::HandlerResponse::Unhandled;
  2620. });
  2621. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2622. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2623. ASSERT_NE(nullptr, ctx);
  2624. res.set_content(ctx->role, "text/plain");
  2625. });
  2626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2627. auto se = detail::scope_exit([&] {
  2628. svr.stop();
  2629. thread.join();
  2630. ASSERT_FALSE(svr.is_running());
  2631. });
  2632. svr.wait_until_ready();
  2633. Client cli(HOST, PORT);
  2634. auto res = cli.Get("/role");
  2635. ASSERT_TRUE(res);
  2636. EXPECT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ("admin", res->body);
  2638. }
  2639. TEST(InvalidFormatTest, StatusCode) {
  2640. Server svr;
  2641. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2642. res.set_content("Hello World!\n", "text/plain");
  2643. res.status = 9999; // Status should be a three-digit code...
  2644. });
  2645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2646. auto se = detail::scope_exit([&] {
  2647. svr.stop();
  2648. thread.join();
  2649. ASSERT_FALSE(svr.is_running());
  2650. });
  2651. svr.wait_until_ready();
  2652. {
  2653. Client cli(HOST, PORT);
  2654. auto res = cli.Get("/hi");
  2655. ASSERT_FALSE(res);
  2656. }
  2657. }
  2658. TEST(URLFragmentTest, WithFragment) {
  2659. Server svr;
  2660. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2661. EXPECT_TRUE(req.target == "/hi");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. {
  2671. Client cli(HOST, PORT);
  2672. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2673. EXPECT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::OK_200, res->status);
  2675. res = cli.Get("/hi%23key1=val1=key2=val2");
  2676. EXPECT_TRUE(res);
  2677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2678. }
  2679. }
  2680. TEST(HeaderWriter, SetHeaderWriter) {
  2681. Server svr;
  2682. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2683. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2684. return detail::write_headers(strm, hdrs);
  2685. });
  2686. svr.Get("/hi", [](const Request &req, Response &res) {
  2687. auto it = req.headers.find("CustomClientHeader");
  2688. EXPECT_TRUE(it != req.headers.end());
  2689. EXPECT_EQ(it->second, "CustomClientValue");
  2690. res.set_content("Hello World!\n", "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. {
  2700. Client cli(HOST, PORT);
  2701. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2702. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2703. return detail::write_headers(strm, hdrs);
  2704. });
  2705. auto res = cli.Get("/hi");
  2706. EXPECT_TRUE(res);
  2707. EXPECT_EQ(StatusCode::OK_200, res->status);
  2708. auto it = res->headers.find("CustomServerHeader");
  2709. EXPECT_TRUE(it != res->headers.end());
  2710. EXPECT_EQ(it->second, "CustomServerValue");
  2711. }
  2712. }
  2713. class ServerTest : public ::testing::Test {
  2714. protected:
  2715. ServerTest()
  2716. : cli_(HOST, PORT)
  2717. #ifdef CPPHTTPLIB_SSL_ENABLED
  2718. ,
  2719. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2720. #endif
  2721. {
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. cli_.enable_server_certificate_verification(false);
  2724. #endif
  2725. // Allow LARGE_DATA (100MB) responses
  2726. cli_.set_payload_max_length(200 * 1024 * 1024);
  2727. }
  2728. virtual void SetUp() {
  2729. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2730. svr_.set_payload_max_length(200 * 1024 * 1024);
  2731. svr_.set_mount_point("/", "./www");
  2732. svr_.set_mount_point("/mount", "./www2");
  2733. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2734. svr_.Get("/hi",
  2735. [&](const Request & /*req*/, Response &res) {
  2736. res.set_content("Hello World!", "text/plain");
  2737. })
  2738. .Get("/file_content",
  2739. [&](const Request & /*req*/, Response &res) {
  2740. res.set_file_content("./www/dir/test.html");
  2741. })
  2742. .Get("/file_content_with_content_type",
  2743. [&](const Request & /*req*/, Response &res) {
  2744. res.set_file_content("./www/file", "text/plain");
  2745. })
  2746. .Get("/invalid_file_content",
  2747. [&](const Request & /*req*/, Response &res) {
  2748. res.set_file_content("./www/dir/invalid_file_path");
  2749. })
  2750. .Get("/http_response_splitting",
  2751. [&](const Request & /*req*/, Response &res) {
  2752. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2753. EXPECT_EQ(0U, res.headers.size());
  2754. EXPECT_FALSE(res.has_header("a"));
  2755. res.set_header("a", "1\nSet-Cookie: a=1");
  2756. EXPECT_EQ(0U, res.headers.size());
  2757. EXPECT_FALSE(res.has_header("a"));
  2758. res.set_header("a", "1\rSet-Cookie: a=1");
  2759. EXPECT_EQ(0U, res.headers.size());
  2760. EXPECT_FALSE(res.has_header("a"));
  2761. res.set_header("a\r\nb", "0");
  2762. EXPECT_EQ(0U, res.headers.size());
  2763. EXPECT_FALSE(res.has_header("a"));
  2764. res.set_header("a\rb", "0");
  2765. EXPECT_EQ(0U, res.headers.size());
  2766. EXPECT_FALSE(res.has_header("a"));
  2767. res.set_header("a\nb", "0");
  2768. EXPECT_EQ(0U, res.headers.size());
  2769. EXPECT_FALSE(res.has_header("a"));
  2770. res.set_redirect("1\r\nSet-Cookie: a=1");
  2771. EXPECT_EQ(0U, res.headers.size());
  2772. EXPECT_FALSE(res.has_header("Location"));
  2773. })
  2774. .Get("/slow",
  2775. [&](const Request & /*req*/, Response &res) {
  2776. std::this_thread::sleep_for(std::chrono::seconds(2));
  2777. res.set_content("slow", "text/plain");
  2778. })
  2779. #if 0
  2780. .Post("/slowpost",
  2781. [&](const Request & /*req*/, Response &res) {
  2782. std::this_thread::sleep_for(std::chrono::seconds(2));
  2783. res.set_content("slow", "text/plain");
  2784. })
  2785. #endif
  2786. .Get("/remote_addr",
  2787. [&](const Request &req, Response &res) {
  2788. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2789. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2790. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2791. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2792. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2793. #endif
  2794. res.set_content(req.remote_addr, "text/plain");
  2795. })
  2796. .Get("/local_addr",
  2797. [&](const Request &req, Response &res) {
  2798. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2799. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2800. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2801. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2802. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2803. #endif
  2804. auto local_addr = req.local_addr;
  2805. auto local_port = std::to_string(req.local_port);
  2806. res.set_content(local_addr.append(":").append(local_port),
  2807. "text/plain");
  2808. })
  2809. .Get("/endwith%",
  2810. [&](const Request & /*req*/, Response &res) {
  2811. res.set_content("Hello World!", "text/plain");
  2812. })
  2813. .Get("/a\\+\\+b",
  2814. [&](const Request &req, Response &res) {
  2815. ASSERT_TRUE(req.has_param("a +b"));
  2816. auto val = req.get_param_value("a +b");
  2817. res.set_content(val, "text/plain");
  2818. })
  2819. .Get("/", [&](const Request & /*req*/,
  2820. Response &res) { res.set_redirect("/hi"); })
  2821. .Post("/1",
  2822. [](const Request & /*req*/, Response &res) {
  2823. res.set_redirect("/2", StatusCode::SeeOther_303);
  2824. })
  2825. .Get("/2",
  2826. [](const Request & /*req*/, Response &res) {
  2827. res.set_content("redirected.", "text/plain");
  2828. res.status = StatusCode::OK_200;
  2829. })
  2830. .Post("/person",
  2831. [&](const Request &req, Response &res) {
  2832. if (req.has_param("name") && req.has_param("note")) {
  2833. persons_[req.get_param_value("name")] =
  2834. req.get_param_value("note");
  2835. } else {
  2836. res.status = StatusCode::BadRequest_400;
  2837. }
  2838. })
  2839. .Put("/person",
  2840. [&](const Request &req, Response &res) {
  2841. if (req.has_param("name") && req.has_param("note")) {
  2842. persons_[req.get_param_value("name")] =
  2843. req.get_param_value("note");
  2844. } else {
  2845. res.status = StatusCode::BadRequest_400;
  2846. }
  2847. })
  2848. .Get("/person/(.*)",
  2849. [&](const Request &req, Response &res) {
  2850. string name = req.matches[1];
  2851. if (persons_.find(name) != persons_.end()) {
  2852. auto note = persons_[name];
  2853. res.set_content(note, "text/plain");
  2854. } else {
  2855. res.status = StatusCode::NotFound_404;
  2856. }
  2857. })
  2858. .Delete("/person",
  2859. [&](const Request &req, Response &res) {
  2860. if (req.has_param("name")) {
  2861. string name = req.get_param_value("name");
  2862. if (persons_.find(name) != persons_.end()) {
  2863. persons_.erase(name);
  2864. res.set_content("DELETED", "text/plain");
  2865. } else {
  2866. res.status = StatusCode::NotFound_404;
  2867. }
  2868. } else {
  2869. res.status = StatusCode::BadRequest_400;
  2870. }
  2871. })
  2872. .Post("/x-www-form-urlencoded-json",
  2873. [&](const Request &req, Response &res) {
  2874. auto json = req.get_param_value("json");
  2875. ASSERT_EQ(JSON_DATA, json);
  2876. res.set_content(json, "appliation/json");
  2877. res.status = StatusCode::OK_200;
  2878. })
  2879. .Get("/streamed-chunked",
  2880. [&](const Request & /*req*/, Response &res) {
  2881. res.set_chunked_content_provider(
  2882. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2883. sink.os << "123";
  2884. sink.os << "456";
  2885. sink.os << "789";
  2886. sink.done();
  2887. return true;
  2888. });
  2889. })
  2890. .Get("/streamed-chunked-with-prohibited-trailer",
  2891. [&](const Request & /*req*/, Response &res) {
  2892. auto i = new int(0);
  2893. // Declare both a prohibited trailer (Content-Length) and an
  2894. // allowed one
  2895. res.set_header("Trailer", "Content-Length, X-Allowed");
  2896. res.set_chunked_content_provider(
  2897. "text/plain",
  2898. [i](size_t /*offset*/, DataSink &sink) {
  2899. switch (*i) {
  2900. case 0: sink.os << "123"; break;
  2901. case 1: sink.os << "456"; break;
  2902. case 2: sink.os << "789"; break;
  2903. case 3: {
  2904. sink.done_with_trailer(
  2905. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2906. } break;
  2907. }
  2908. (*i)++;
  2909. return true;
  2910. },
  2911. [i](bool success) {
  2912. EXPECT_TRUE(success);
  2913. delete i;
  2914. });
  2915. })
  2916. .Get("/streamed-chunked2",
  2917. [&](const Request & /*req*/, Response &res) {
  2918. auto i = new int(0);
  2919. res.set_chunked_content_provider(
  2920. "text/plain",
  2921. [i](size_t /*offset*/, DataSink &sink) {
  2922. switch (*i) {
  2923. case 0: sink.os << "123"; break;
  2924. case 1: sink.os << "456"; break;
  2925. case 2: sink.os << "789"; break;
  2926. case 3: sink.done(); break;
  2927. }
  2928. (*i)++;
  2929. return true;
  2930. },
  2931. [i](bool success) {
  2932. EXPECT_TRUE(success);
  2933. delete i;
  2934. });
  2935. })
  2936. .Get("/streamed-chunked-with-trailer",
  2937. [&](const Request & /*req*/, Response &res) {
  2938. auto i = new int(0);
  2939. res.set_header("Trailer", "Dummy1, Dummy2");
  2940. res.set_chunked_content_provider(
  2941. "text/plain",
  2942. [i](size_t /*offset*/, DataSink &sink) {
  2943. switch (*i) {
  2944. case 0: sink.os << "123"; break;
  2945. case 1: sink.os << "456"; break;
  2946. case 2: sink.os << "789"; break;
  2947. case 3: {
  2948. sink.done_with_trailer(
  2949. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2950. } break;
  2951. }
  2952. (*i)++;
  2953. return true;
  2954. },
  2955. [i](bool success) {
  2956. EXPECT_TRUE(success);
  2957. delete i;
  2958. });
  2959. })
  2960. .Get("/streamed",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_content_provider(
  2963. 6, "text/plain",
  2964. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2965. sink.os << (offset < 3 ? "a" : "b");
  2966. return true;
  2967. });
  2968. })
  2969. .Get("/streamed-with-range",
  2970. [&](const Request &req, Response &res) {
  2971. auto data = new std::string("abcdefg");
  2972. res.set_content_provider(
  2973. data->size(), "text/plain",
  2974. [data](size_t offset, size_t length, DataSink &sink) {
  2975. size_t DATA_CHUNK_SIZE = 4;
  2976. const auto &d = *data;
  2977. auto out_len =
  2978. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2979. auto ret =
  2980. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2981. EXPECT_TRUE(ret);
  2982. return true;
  2983. },
  2984. [data, &req](bool success) {
  2985. EXPECT_EQ(success, !req.has_param("error"));
  2986. delete data;
  2987. });
  2988. })
  2989. .Get("/streamed-cancel",
  2990. [&](const Request & /*req*/, Response &res) {
  2991. res.set_content_provider(
  2992. size_t(-1), "text/plain",
  2993. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2994. sink.os << "data_chunk";
  2995. return true;
  2996. });
  2997. })
  2998. .Get("/regex-with-delimiter",
  2999. [&](const Request &req, Response & /*res*/) {
  3000. ASSERT_TRUE(req.has_param("key"));
  3001. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3002. })
  3003. .Get("/with-range",
  3004. [&](const Request & /*req*/, Response &res) {
  3005. res.set_content("abcdefg", "text/plain");
  3006. })
  3007. .Get("/test-start-time",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_NE(req.start_time_,
  3010. std::chrono::steady_clock::time_point::min());
  3011. })
  3012. .Get("/with-range-customized-response",
  3013. [&](const Request & /*req*/, Response &res) {
  3014. res.status = StatusCode::BadRequest_400;
  3015. res.set_content(JSON_DATA, "application/json");
  3016. })
  3017. .Post("/chunked",
  3018. [&](const Request &req, Response & /*res*/) {
  3019. EXPECT_EQ(req.body, "dechunked post body");
  3020. })
  3021. .Post("/large-chunked",
  3022. [&](const Request &req, Response & /*res*/) {
  3023. std::string expected(6 * 30 * 1024u, 'a');
  3024. EXPECT_EQ(req.body, expected);
  3025. })
  3026. .Post("/multipart",
  3027. [&](const Request &req, Response & /*res*/) {
  3028. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3029. req.form.get_field_count("text2") +
  3030. req.form.get_field_count("file3") +
  3031. req.form.get_field_count("file4"));
  3032. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3033. req.form.get_file_count("file2"));
  3034. ASSERT_TRUE(!req.form.has_file("???"));
  3035. ASSERT_TRUE(!req.form.has_field("???"));
  3036. ASSERT_TRUE(req.body.empty());
  3037. {
  3038. const auto &text = req.form.get_field("text1");
  3039. EXPECT_EQ("text default", text);
  3040. }
  3041. {
  3042. const auto &text = req.form.get_field("text2");
  3043. EXPECT_EQ("aωb", text);
  3044. }
  3045. {
  3046. const auto &file = req.form.get_file("file1");
  3047. EXPECT_EQ("hello.txt", file.filename);
  3048. EXPECT_EQ("text/plain", file.content_type);
  3049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3050. }
  3051. {
  3052. const auto &file = req.form.get_file("file2");
  3053. EXPECT_EQ("world.json", file.filename);
  3054. EXPECT_EQ("application/json", file.content_type);
  3055. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3056. }
  3057. {
  3058. const auto &text = req.form.get_field("file3");
  3059. EXPECT_EQ(0u, text.size());
  3060. }
  3061. {
  3062. const auto &text = req.form.get_field("file4");
  3063. EXPECT_EQ(0u, text.size());
  3064. }
  3065. })
  3066. .Post("/multipart/multi_file_values",
  3067. [&](const Request &req, Response & /*res*/) {
  3068. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3069. req.form.get_field_count("multi_text1"));
  3070. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3071. ASSERT_TRUE(!req.form.has_file("???"));
  3072. ASSERT_TRUE(!req.form.has_field("???"));
  3073. ASSERT_TRUE(req.body.empty());
  3074. {
  3075. const auto &text = req.form.get_field("text");
  3076. EXPECT_EQ("default text", text);
  3077. }
  3078. {
  3079. const auto &text1_values = req.form.get_fields("multi_text1");
  3080. EXPECT_EQ(2u, text1_values.size());
  3081. EXPECT_EQ("aaaaa", text1_values[0]);
  3082. EXPECT_EQ("bbbbb", text1_values[1]);
  3083. }
  3084. {
  3085. const auto &file1_values = req.form.get_files("multi_file1");
  3086. EXPECT_EQ(2u, file1_values.size());
  3087. auto file1 = file1_values[0];
  3088. EXPECT_EQ(file1.filename, "hello.txt");
  3089. EXPECT_EQ(file1.content_type, "text/plain");
  3090. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3091. auto file2 = file1_values[1];
  3092. EXPECT_EQ(file2.filename, "world.json");
  3093. EXPECT_EQ(file2.content_type, "application/json");
  3094. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3095. }
  3096. })
  3097. .Post("/empty",
  3098. [&](const Request &req, Response &res) {
  3099. EXPECT_EQ(req.body, "");
  3100. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3101. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3102. res.set_content("empty", "text/plain");
  3103. })
  3104. .Post("/empty-no-content-type",
  3105. [&](const Request &req, Response &res) {
  3106. EXPECT_EQ(req.body, "");
  3107. EXPECT_FALSE(req.has_header("Content-Type"));
  3108. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3109. res.set_content("empty-no-content-type", "text/plain");
  3110. })
  3111. .Post("/path-only",
  3112. [&](const Request &req, Response &res) {
  3113. EXPECT_EQ(req.body, "");
  3114. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3115. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3116. res.set_content("path-only", "text/plain");
  3117. })
  3118. .Post("/path-headers-only",
  3119. [&](const Request &req, Response &res) {
  3120. EXPECT_EQ(req.body, "");
  3121. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3122. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3123. EXPECT_EQ("world", req.get_header_value("hello"));
  3124. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3125. res.set_content("path-headers-only", "text/plain");
  3126. })
  3127. .Post("/post-large",
  3128. [&](const Request &req, Response &res) {
  3129. EXPECT_EQ(req.body, LARGE_DATA);
  3130. res.set_content(req.body, "text/plain");
  3131. })
  3132. .Post("/post-loopback",
  3133. [&](const Request &, Response &res,
  3134. ContentReader const &content_reader) {
  3135. std::string body;
  3136. content_reader([&](const char *data, size_t data_length) {
  3137. body.append(data, data_length);
  3138. return true;
  3139. });
  3140. res.set_content(body, "text/plain");
  3141. })
  3142. .Put("/put-loopback",
  3143. [&](const Request &, Response &res,
  3144. ContentReader const &content_reader) {
  3145. std::string body;
  3146. content_reader([&](const char *data, size_t data_length) {
  3147. body.append(data, data_length);
  3148. return true;
  3149. });
  3150. res.set_content(body, "text/plain");
  3151. })
  3152. .Patch("/patch-loopback",
  3153. [&](const Request &, Response &res,
  3154. ContentReader const &content_reader) {
  3155. std::string body;
  3156. content_reader([&](const char *data, size_t data_length) {
  3157. body.append(data, data_length);
  3158. return true;
  3159. });
  3160. res.set_content(body, "text/plain");
  3161. })
  3162. .Put("/empty-no-content-type",
  3163. [&](const Request &req, Response &res) {
  3164. EXPECT_EQ(req.body, "");
  3165. EXPECT_FALSE(req.has_header("Content-Type"));
  3166. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3167. res.set_content("empty-no-content-type", "text/plain");
  3168. })
  3169. .Put("/put",
  3170. [&](const Request &req, Response &res) {
  3171. EXPECT_EQ(req.body, "PUT");
  3172. res.set_content(req.body, "text/plain");
  3173. })
  3174. .Put("/put-large",
  3175. [&](const Request &req, Response &res) {
  3176. EXPECT_EQ(req.body, LARGE_DATA);
  3177. res.set_content(req.body, "text/plain");
  3178. })
  3179. .Patch("/patch",
  3180. [&](const Request &req, Response &res) {
  3181. EXPECT_EQ(req.body, "PATCH");
  3182. res.set_content(req.body, "text/plain");
  3183. })
  3184. .Delete("/delete",
  3185. [&](const Request & /*req*/, Response &res) {
  3186. res.set_content("DELETE", "text/plain");
  3187. })
  3188. .Delete("/delete-body",
  3189. [&](const Request &req, Response &res) {
  3190. EXPECT_EQ(req.body, "content");
  3191. res.set_content(req.body, "text/plain");
  3192. })
  3193. .Options(R"(\*)",
  3194. [&](const Request & /*req*/, Response &res) {
  3195. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3196. })
  3197. .Get("/request-target",
  3198. [&](const Request &req, Response & /*res*/) {
  3199. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3200. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3201. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3202. })
  3203. .Get("/long-query-value",
  3204. [&](const Request &req, Response & /*res*/) {
  3205. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3206. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3207. })
  3208. .Get("/too-long-query-value",
  3209. [&](const Request &req, Response & /*res*/) {
  3210. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3211. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3212. })
  3213. .Get("/array-param",
  3214. [&](const Request &req, Response & /*res*/) {
  3215. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3216. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3217. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3218. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3219. })
  3220. .Post("/validate-no-multiple-headers",
  3221. [&](const Request &req, Response & /*res*/) {
  3222. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3223. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3224. })
  3225. .Post("/content_receiver",
  3226. [&](const Request &req, Response &res,
  3227. const ContentReader &content_reader) {
  3228. if (req.is_multipart_form_data()) {
  3229. std::vector<FormData> items;
  3230. content_reader(
  3231. [&](const FormData &file) {
  3232. items.push_back(file);
  3233. return true;
  3234. },
  3235. [&](const char *data, size_t data_length) {
  3236. items.back().content.append(data, data_length);
  3237. return true;
  3238. });
  3239. EXPECT_EQ(5u, items.size());
  3240. {
  3241. const auto &file = get_file_value(items, "text1");
  3242. EXPECT_TRUE(file.filename.empty());
  3243. EXPECT_EQ("text default", file.content);
  3244. }
  3245. {
  3246. const auto &file = get_file_value(items, "text2");
  3247. EXPECT_TRUE(file.filename.empty());
  3248. EXPECT_EQ("aωb", file.content);
  3249. }
  3250. {
  3251. const auto &file = get_file_value(items, "file1");
  3252. EXPECT_EQ("hello.txt", file.filename);
  3253. EXPECT_EQ("text/plain", file.content_type);
  3254. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3255. }
  3256. {
  3257. const auto &file = get_file_value(items, "file2");
  3258. EXPECT_EQ("world.json", file.filename);
  3259. EXPECT_EQ("application/json", file.content_type);
  3260. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3261. }
  3262. {
  3263. const auto &file = get_file_value(items, "file3");
  3264. EXPECT_TRUE(file.filename.empty());
  3265. EXPECT_EQ("application/octet-stream", file.content_type);
  3266. EXPECT_EQ(0u, file.content.size());
  3267. }
  3268. } else {
  3269. std::string body;
  3270. content_reader([&](const char *data, size_t data_length) {
  3271. EXPECT_EQ(7U, data_length);
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. EXPECT_EQ(body, "content");
  3276. res.set_content(body, "text/plain");
  3277. }
  3278. })
  3279. .Put("/content_receiver",
  3280. [&](const Request & /*req*/, Response &res,
  3281. const ContentReader &content_reader) {
  3282. std::string body;
  3283. content_reader([&](const char *data, size_t data_length) {
  3284. body.append(data, data_length);
  3285. return true;
  3286. });
  3287. EXPECT_EQ(body, "content");
  3288. res.set_content(body, "text/plain");
  3289. })
  3290. .Patch("/content_receiver",
  3291. [&](const Request & /*req*/, Response &res,
  3292. const ContentReader &content_reader) {
  3293. std::string body;
  3294. content_reader([&](const char *data, size_t data_length) {
  3295. body.append(data, data_length);
  3296. return true;
  3297. });
  3298. EXPECT_EQ(body, "content");
  3299. res.set_content(body, "text/plain");
  3300. })
  3301. .Post("/query-string-and-body",
  3302. [&](const Request &req, Response & /*res*/) {
  3303. ASSERT_TRUE(req.has_param("key"));
  3304. EXPECT_EQ(req.get_param_value("key"), "value");
  3305. EXPECT_EQ(req.body, "content");
  3306. })
  3307. .Get("/last-request",
  3308. [&](const Request &req, Response & /*res*/) {
  3309. EXPECT_EQ("close", req.get_header_value("Connection"));
  3310. })
  3311. .Get(R"(/redirect/(\d+))",
  3312. [&](const Request &req, Response &res) {
  3313. auto num = std::stoi(req.matches[1]) + 1;
  3314. std::string url = "/redirect/" + std::to_string(num);
  3315. res.set_redirect(url);
  3316. })
  3317. .Post("/binary",
  3318. [&](const Request &req, Response &res) {
  3319. EXPECT_EQ(4U, req.body.size());
  3320. EXPECT_EQ("application/octet-stream",
  3321. req.get_header_value("Content-Type"));
  3322. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3323. res.set_content(req.body, "application/octet-stream");
  3324. })
  3325. .Put("/binary",
  3326. [&](const Request &req, Response &res) {
  3327. EXPECT_EQ(4U, req.body.size());
  3328. EXPECT_EQ("application/octet-stream",
  3329. req.get_header_value("Content-Type"));
  3330. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3331. res.set_content(req.body, "application/octet-stream");
  3332. })
  3333. .Patch("/binary",
  3334. [&](const Request &req, Response &res) {
  3335. EXPECT_EQ(4U, req.body.size());
  3336. EXPECT_EQ("application/octet-stream",
  3337. req.get_header_value("Content-Type"));
  3338. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3339. res.set_content(req.body, "application/octet-stream");
  3340. })
  3341. .Delete("/binary",
  3342. [&](const Request &req, Response &res) {
  3343. EXPECT_EQ(4U, req.body.size());
  3344. EXPECT_EQ("application/octet-stream",
  3345. req.get_header_value("Content-Type"));
  3346. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3347. res.set_content(req.body, "application/octet-stream");
  3348. })
  3349. .Get("/issue1772",
  3350. [&](const Request & /*req*/, Response &res) {
  3351. res.status = 401;
  3352. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3353. })
  3354. .Delete("/issue609",
  3355. [](const httplib::Request &, httplib::Response &res,
  3356. const httplib::ContentReader &) {
  3357. res.set_content("ok", "text/plain");
  3358. })
  3359. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3360. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3361. .Get("/compress",
  3362. [&](const Request & /*req*/, Response &res) {
  3363. res.set_content(
  3364. "12345678901234567890123456789012345678901234567890123456789"
  3365. "01234567890123456789012345678901234567890",
  3366. "text/plain");
  3367. })
  3368. .Get("/compress-with-charset",
  3369. [&](const Request & /*req*/, Response &res) {
  3370. res.set_content(
  3371. "12345678901234567890123456789012345678901234567890123456789"
  3372. "01234567890123456789012345678901234567890",
  3373. "application/json; charset=utf-8");
  3374. })
  3375. .Get("/nocompress",
  3376. [&](const Request & /*req*/, Response &res) {
  3377. res.set_content(
  3378. "12345678901234567890123456789012345678901234567890123456789"
  3379. "01234567890123456789012345678901234567890",
  3380. "application/octet-stream");
  3381. })
  3382. .Post("/compress-multipart",
  3383. [&](const Request &req, Response & /*res*/) {
  3384. EXPECT_EQ(2u, req.form.fields.size());
  3385. ASSERT_TRUE(!req.form.has_field("???"));
  3386. {
  3387. const auto &text = req.form.get_field("key1");
  3388. EXPECT_EQ("test", text);
  3389. }
  3390. {
  3391. const auto &text = req.form.get_field("key2");
  3392. EXPECT_EQ("--abcdefg123", text);
  3393. }
  3394. })
  3395. #endif
  3396. ;
  3397. persons_["john"] = "programmer";
  3398. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3399. svr_.wait_until_ready();
  3400. }
  3401. virtual void TearDown() {
  3402. svr_.stop();
  3403. if (!request_threads_.empty()) {
  3404. std::this_thread::sleep_for(std::chrono::seconds(1));
  3405. for (auto &t : request_threads_) {
  3406. t.join();
  3407. }
  3408. }
  3409. t_.join();
  3410. }
  3411. map<string, string> persons_;
  3412. #ifdef CPPHTTPLIB_SSL_ENABLED
  3413. SSLClient cli_;
  3414. SSLServer svr_;
  3415. #else
  3416. Client cli_;
  3417. Server svr_;
  3418. #endif
  3419. thread t_;
  3420. std::vector<thread> request_threads_;
  3421. };
  3422. TEST_F(ServerTest, GetMethod200) {
  3423. auto res = cli_.Get("/hi");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ("HTTP/1.1", res->version);
  3426. EXPECT_EQ(StatusCode::OK_200, res->status);
  3427. EXPECT_EQ("OK", res->reason);
  3428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3430. EXPECT_EQ("Hello World!", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetEmptyFile) {
  3433. auto res = cli_.Get("/empty_file");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::OK_200, res->status);
  3436. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3437. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3438. EXPECT_EQ("", res->body);
  3439. }
  3440. TEST_F(ServerTest, GetFileContent) {
  3441. auto res = cli_.Get("/file_content");
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3445. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3446. EXPECT_EQ("test.html", res->body);
  3447. }
  3448. TEST_F(ServerTest, GetFileContentWithRange) {
  3449. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3453. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3454. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3455. EXPECT_EQ("est", res->body);
  3456. }
  3457. TEST_F(ServerTest, GetFileContentWithContentType) {
  3458. auto res = cli_.Get("/file_content_with_content_type");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3462. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3463. EXPECT_EQ("file\n", res->body);
  3464. }
  3465. TEST_F(ServerTest, GetInvalidFileContent) {
  3466. auto res = cli_.Get("/invalid_file_content");
  3467. ASSERT_TRUE(res);
  3468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3469. }
  3470. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3471. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3472. ASSERT_TRUE(res);
  3473. EXPECT_EQ("HTTP/1.1", res->version);
  3474. EXPECT_EQ(StatusCode::OK_200, res->status);
  3475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3476. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3477. EXPECT_EQ("Hello World!", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethod302) {
  3480. auto res = cli_.Get("/");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::Found_302, res->status);
  3483. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3484. }
  3485. TEST_F(ServerTest, GetMethod302Redirect) {
  3486. cli_.set_follow_location(true);
  3487. auto res = cli_.Get("/");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::OK_200, res->status);
  3490. EXPECT_EQ("Hello World!", res->body);
  3491. EXPECT_EQ("/hi", res->location);
  3492. }
  3493. TEST_F(ServerTest, GetMethod404) {
  3494. auto res = cli_.Get("/invalid");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3497. }
  3498. TEST_F(ServerTest, HeadMethod200) {
  3499. auto res = cli_.Head("/hi");
  3500. ASSERT_TRUE(res);
  3501. EXPECT_EQ(StatusCode::OK_200, res->status);
  3502. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3503. EXPECT_TRUE(res->body.empty());
  3504. }
  3505. TEST_F(ServerTest, HeadMethod200Static) {
  3506. auto res = cli_.Head("/mount/dir/index.html");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3510. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3511. EXPECT_TRUE(res->body.empty());
  3512. }
  3513. TEST_F(ServerTest, HeadMethod404) {
  3514. auto res = cli_.Head("/invalid");
  3515. ASSERT_TRUE(res);
  3516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3517. EXPECT_TRUE(res->body.empty());
  3518. }
  3519. TEST_F(ServerTest, GetMethodPersonJohn) {
  3520. auto res = cli_.Get("/person/john");
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3524. EXPECT_EQ("programmer", res->body);
  3525. }
  3526. TEST_F(ServerTest, PostMethod1) {
  3527. auto res = cli_.Get("/person/john1");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3530. res = cli_.Post("/person", "name=john1&note=coder",
  3531. "application/x-www-form-urlencoded");
  3532. ASSERT_TRUE(res);
  3533. ASSERT_EQ(StatusCode::OK_200, res->status);
  3534. res = cli_.Get("/person/john1");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3538. ASSERT_EQ("coder", res->body);
  3539. }
  3540. TEST_F(ServerTest, PostMethod2) {
  3541. auto res = cli_.Get("/person/john2");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3544. Params params;
  3545. params.emplace("name", "john2");
  3546. params.emplace("note", "coder");
  3547. res = cli_.Post("/person", params);
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. res = cli_.Get("/person/john2");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::OK_200, res->status);
  3553. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. ASSERT_EQ("coder", res->body);
  3555. }
  3556. TEST_F(ServerTest, PutMethod3) {
  3557. auto res = cli_.Get("/person/john3");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3560. Params params;
  3561. params.emplace("name", "john3");
  3562. params.emplace("note", "coder");
  3563. res = cli_.Put("/person", params);
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. res = cli_.Get("/person/john3");
  3567. ASSERT_TRUE(res);
  3568. ASSERT_EQ(StatusCode::OK_200, res->status);
  3569. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3570. ASSERT_EQ("coder", res->body);
  3571. }
  3572. TEST_F(ServerTest, DeleteMethod1) {
  3573. auto res = cli_.Get("/person/john4");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3576. Params params;
  3577. params.emplace("name", "john4");
  3578. params.emplace("note", "coder");
  3579. res = cli_.Post("/person", params);
  3580. ASSERT_TRUE(res);
  3581. ASSERT_EQ(StatusCode::OK_200, res->status);
  3582. res = cli_.Get("/person/john4");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3586. ASSERT_EQ("coder", res->body);
  3587. Params delete_params;
  3588. delete_params.emplace("name", "john4");
  3589. res = cli_.Delete("/person", delete_params);
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_EQ("DELETED", res->body);
  3593. res = cli_.Get("/person/john4");
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3596. }
  3597. TEST_F(ServerTest, DeleteMethod2) {
  3598. auto res = cli_.Get("/person/john5");
  3599. ASSERT_TRUE(res);
  3600. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3601. Params params;
  3602. params.emplace("name", "john5");
  3603. params.emplace("note", "developer");
  3604. res = cli_.Post("/person", params);
  3605. ASSERT_TRUE(res);
  3606. ASSERT_EQ(StatusCode::OK_200, res->status);
  3607. res = cli_.Get("/person/john5");
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3611. ASSERT_EQ("developer", res->body);
  3612. Params delete_params;
  3613. delete_params.emplace("name", "john5");
  3614. Headers headers;
  3615. headers.emplace("Custom-Header", "test-value");
  3616. res = cli_.Delete("/person", headers, delete_params);
  3617. ASSERT_TRUE(res);
  3618. ASSERT_EQ(StatusCode::OK_200, res->status);
  3619. ASSERT_EQ("DELETED", res->body);
  3620. res = cli_.Get("/person/john5");
  3621. ASSERT_TRUE(res);
  3622. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3623. }
  3624. TEST_F(ServerTest, DeleteMethod3) {
  3625. auto res = cli_.Get("/person/john6");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3628. Params params;
  3629. params.emplace("name", "john6");
  3630. params.emplace("note", "tester");
  3631. res = cli_.Post("/person", params);
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. res = cli_.Get("/person/john6");
  3635. ASSERT_TRUE(res);
  3636. ASSERT_EQ(StatusCode::OK_200, res->status);
  3637. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3638. ASSERT_EQ("tester", res->body);
  3639. Params delete_params;
  3640. delete_params.emplace("name", "john6");
  3641. Headers headers;
  3642. headers.emplace("Custom-Header", "test-value");
  3643. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ("DELETED", res->body);
  3647. res = cli_.Get("/person/john6");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3650. }
  3651. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3652. Params params;
  3653. params.emplace("json", JSON_DATA);
  3654. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::OK_200, res->status);
  3657. ASSERT_EQ(JSON_DATA, res->body);
  3658. }
  3659. TEST_F(ServerTest, PostEmptyContent) {
  3660. auto res = cli_.Post("/empty", "", "text/plain");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ("empty", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3666. auto res = cli_.Post("/empty-no-content-type");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::OK_200, res->status);
  3669. ASSERT_EQ("empty-no-content-type", res->body);
  3670. }
  3671. TEST_F(ServerTest, PostPathOnly) {
  3672. auto res = cli_.Post("/path-only");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. ASSERT_EQ("path-only", res->body);
  3676. }
  3677. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3678. auto res = cli_.Post("/path-headers-only",
  3679. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ("path-headers-only", res->body);
  3683. }
  3684. TEST_F(ServerTest, PostLarge) {
  3685. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3686. ASSERT_TRUE(res);
  3687. ASSERT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ(LARGE_DATA, res->body);
  3689. }
  3690. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3691. auto res = cli_.Put("/empty-no-content-type");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("empty-no-content-type", res->body);
  3695. }
  3696. TEST_F(ServerTest, GetMethodDir) {
  3697. auto res = cli_.Get("/dir/");
  3698. ASSERT_TRUE(res);
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3701. auto body = R"(<html>
  3702. <head>
  3703. </head>
  3704. <body>
  3705. <a href="/dir/test.html">Test</a>
  3706. <a href="/hi">hi</a>
  3707. </body>
  3708. </html>
  3709. )";
  3710. EXPECT_EQ(body, res->body);
  3711. }
  3712. TEST_F(ServerTest, GetMethodDirTest) {
  3713. auto res = cli_.Get("/dir/test.html");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3717. EXPECT_EQ("test.html", res->body);
  3718. }
  3719. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3720. auto res = cli_.Get("/dir/../dir/test.html");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3724. EXPECT_EQ("test.html", res->body);
  3725. }
  3726. TEST_F(ServerTest, GetMethodInvalidPath) {
  3727. auto res = cli_.Get("/dir/../test.html");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3730. }
  3731. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3732. auto res = cli_.Get("/../www/dir/test.html");
  3733. ASSERT_TRUE(res);
  3734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3735. }
  3736. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3737. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3738. ASSERT_TRUE(res);
  3739. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3740. }
  3741. TEST_F(ServerTest, GetMethodDirMountTest) {
  3742. auto res = cli_.Get("/mount/dir/test.html");
  3743. ASSERT_TRUE(res);
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3746. EXPECT_EQ("test.html", res->body);
  3747. }
  3748. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3749. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3753. EXPECT_EQ("test.html", res->body);
  3754. }
  3755. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3756. auto res = cli_.Get("/mount/dir/../test.html");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3759. }
  3760. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3761. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3762. ASSERT_TRUE(res);
  3763. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3764. }
  3765. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3766. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3767. ASSERT_TRUE(res);
  3768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3769. }
  3770. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3771. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3774. }
  3775. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3776. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3779. }
  3780. TEST_F(ServerTest, PostMethod303) {
  3781. auto res = cli_.Post("/1", "body", "text/plain");
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3784. EXPECT_EQ("/2", res->get_header_value("Location"));
  3785. }
  3786. TEST_F(ServerTest, PostMethod303Redirect) {
  3787. cli_.set_follow_location(true);
  3788. auto res = cli_.Post("/1", "body", "text/plain");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. EXPECT_EQ("redirected.", res->body);
  3792. EXPECT_EQ("/2", res->location);
  3793. }
  3794. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3795. auto res = cli_.Get("/dir/test.abcde");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::OK_200, res->status);
  3798. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3799. EXPECT_EQ("abcde", res->body);
  3800. }
  3801. TEST_F(ServerTest, StaticFileRange) {
  3802. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3807. EXPECT_EQ(true, res->has_header("Content-Range"));
  3808. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3809. EXPECT_EQ(std::string("cd"), res->body);
  3810. }
  3811. TEST_F(ServerTest, StaticFileRanges) {
  3812. auto res =
  3813. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3816. EXPECT_TRUE(
  3817. res->get_header_value("Content-Type")
  3818. .find(
  3819. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3820. 0);
  3821. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3822. }
  3823. TEST_F(ServerTest, StaticFileRangeHead) {
  3824. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3825. ASSERT_TRUE(res);
  3826. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3827. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3828. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3829. EXPECT_EQ(true, res->has_header("Content-Range"));
  3830. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3831. }
  3832. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3833. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3837. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3838. EXPECT_EQ(true, res->has_header("Content-Range"));
  3839. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3840. res->get_header_value("Content-Range"));
  3841. EXPECT_EQ("LAST\n", res->body);
  3842. }
  3843. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3844. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3849. EXPECT_EQ(true, res->has_header("Content-Range"));
  3850. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3851. }
  3852. TEST_F(ServerTest, StaticFileBigFile) {
  3853. auto res = cli_.Get("/dir/1MB.txt");
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(StatusCode::OK_200, res->status);
  3856. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3857. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3858. }
  3859. TEST_F(ServerTest, InvalidBaseDirMount) {
  3860. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3861. }
  3862. TEST_F(ServerTest, Binary) {
  3863. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3864. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3865. "application/octet-stream");
  3866. ASSERT_TRUE(res);
  3867. ASSERT_EQ(StatusCode::OK_200, res->status);
  3868. ASSERT_EQ(4U, res->body.size());
  3869. res = cli_.Put("/binary", binary.data(), binary.size(),
  3870. "application/octet-stream");
  3871. ASSERT_TRUE(res);
  3872. ASSERT_EQ(StatusCode::OK_200, res->status);
  3873. ASSERT_EQ(4U, res->body.size());
  3874. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3875. "application/octet-stream");
  3876. ASSERT_TRUE(res);
  3877. ASSERT_EQ(StatusCode::OK_200, res->status);
  3878. ASSERT_EQ(4U, res->body.size());
  3879. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3880. "application/octet-stream");
  3881. ASSERT_TRUE(res);
  3882. ASSERT_EQ(StatusCode::OK_200, res->status);
  3883. ASSERT_EQ(4U, res->body.size());
  3884. }
  3885. TEST_F(ServerTest, BinaryString) {
  3886. auto binary = std::string("\x00\x01\x02\x03", 4);
  3887. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::OK_200, res->status);
  3890. ASSERT_EQ(4U, res->body.size());
  3891. res = cli_.Put("/binary", binary, "application/octet-stream");
  3892. ASSERT_TRUE(res);
  3893. ASSERT_EQ(StatusCode::OK_200, res->status);
  3894. ASSERT_EQ(4U, res->body.size());
  3895. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3896. ASSERT_TRUE(res);
  3897. ASSERT_EQ(StatusCode::OK_200, res->status);
  3898. ASSERT_EQ(4U, res->body.size());
  3899. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3900. ASSERT_TRUE(res);
  3901. ASSERT_EQ(StatusCode::OK_200, res->status);
  3902. ASSERT_EQ(4U, res->body.size());
  3903. }
  3904. TEST_F(ServerTest, EmptyRequest) {
  3905. auto res = cli_.Get("");
  3906. ASSERT_TRUE(!res);
  3907. EXPECT_EQ(Error::Connection, res.error());
  3908. }
  3909. TEST_F(ServerTest, LongRequest) {
  3910. std::string request;
  3911. for (size_t i = 0; i < 545; i++) {
  3912. request += "/TooLongRequest";
  3913. }
  3914. request += "OK";
  3915. auto res = cli_.Get(request.c_str());
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3918. }
  3919. TEST_F(ServerTest, TooLongRequest) {
  3920. std::string request;
  3921. for (size_t i = 0; i < 546; i++) {
  3922. request += "/TooLongRequest";
  3923. }
  3924. request += "_NG";
  3925. auto start = std::chrono::high_resolution_clock::now();
  3926. cli_.set_keep_alive(true);
  3927. auto res = cli_.Get(request.c_str());
  3928. auto end = std::chrono::high_resolution_clock::now();
  3929. auto elapsed =
  3930. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3931. .count();
  3932. ASSERT_TRUE(res);
  3933. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3934. EXPECT_LE(elapsed, 1000);
  3935. EXPECT_EQ("close", res->get_header_value("Connection"));
  3936. EXPECT_FALSE(cli_.is_socket_open());
  3937. }
  3938. TEST_F(ServerTest, AlmostTooLongRequest) {
  3939. // test for #2046 - URI length check shouldn't include other content on req
  3940. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3941. // leading /, space, HTTP/1.1)
  3942. std::string request =
  3943. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3944. auto res = cli_.Get(request.c_str());
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3947. }
  3948. TEST_F(ServerTest, LongHeader) {
  3949. Request req;
  3950. req.method = "GET";
  3951. req.path = "/hi";
  3952. std::string host_and_port;
  3953. host_and_port += HOST;
  3954. host_and_port += ":";
  3955. host_and_port += std::to_string(PORT);
  3956. req.headers.emplace("Host", host_and_port.c_str());
  3957. req.headers.emplace("Accept", "*/*");
  3958. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3959. req.headers.emplace(
  3960. "Header-Name",
  3961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@");
  3990. auto res = std::make_shared<Response>();
  3991. auto error = Error::Success;
  3992. auto ret = cli_.send(req, *res, error);
  3993. ASSERT_TRUE(ret);
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. }
  3996. TEST_F(ServerTest, LongQueryValue) {
  3997. auto start = std::chrono::high_resolution_clock::now();
  3998. cli_.set_keep_alive(true);
  3999. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4000. auto end = std::chrono::high_resolution_clock::now();
  4001. auto elapsed =
  4002. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4003. .count();
  4004. ASSERT_TRUE(res);
  4005. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4006. EXPECT_LE(elapsed, 1000);
  4007. EXPECT_EQ("close", res->get_header_value("Connection"));
  4008. EXPECT_FALSE(cli_.is_socket_open());
  4009. }
  4010. TEST_F(ServerTest, TooLongQueryValue) {
  4011. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4012. ASSERT_FALSE(res);
  4013. EXPECT_EQ(Error::Read, res.error());
  4014. }
  4015. TEST_F(ServerTest, TooLongHeader) {
  4016. Request req;
  4017. req.method = "GET";
  4018. req.path = "/hi";
  4019. std::string host_and_port;
  4020. host_and_port += HOST;
  4021. host_and_port += ":";
  4022. host_and_port += std::to_string(PORT);
  4023. req.headers.emplace("Host", host_and_port.c_str());
  4024. req.headers.emplace("Accept", "*/*");
  4025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4026. req.headers.emplace(
  4027. "Header-Name",
  4028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@");
  4057. auto res = std::make_shared<Response>();
  4058. auto error = Error::Success;
  4059. auto ret = cli_.send(req, *res, error);
  4060. ASSERT_TRUE(ret);
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. }
  4063. TEST_F(ServerTest, HeaderCountAtLimit) {
  4064. // Test with headers just under the 100 limit
  4065. httplib::Headers headers;
  4066. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4067. // This should keep us just under the 100 header limit
  4068. for (int i = 0; i < 95; i++) {
  4069. std::string name = "X-Test-Header-" + std::to_string(i);
  4070. std::string value = "value" + std::to_string(i);
  4071. headers.emplace(name, value);
  4072. }
  4073. // This should work fine as we're under the limit
  4074. auto res = cli_.Get("/hi", headers);
  4075. EXPECT_TRUE(res);
  4076. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4077. }
  4078. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4079. // Test with many headers to exceed the 100 limit
  4080. httplib::Headers headers;
  4081. // Add 150 headers to definitely exceed the 100 limit
  4082. for (int i = 0; i < 150; i++) {
  4083. std::string name = "X-Test-Header-" + std::to_string(i);
  4084. std::string value = "value" + std::to_string(i);
  4085. headers.emplace(name, value);
  4086. }
  4087. // This should fail due to exceeding header count limit
  4088. cli_.set_keep_alive(true);
  4089. auto res = cli_.Get("/hi", headers);
  4090. // The server should respond with 400 Bad Request
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4093. EXPECT_EQ("close", res->get_header_value("Connection"));
  4094. EXPECT_FALSE(cli_.is_socket_open());
  4095. }
  4096. TEST_F(ServerTest, PercentEncoding) {
  4097. auto res = cli_.Get("/e%6edwith%");
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. }
  4101. TEST_F(ServerTest, PercentEncodingUnicode) {
  4102. auto res = cli_.Get("/e%u006edwith%");
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ(StatusCode::OK_200, res->status);
  4105. }
  4106. TEST_F(ServerTest, InvalidPercentEncoding) {
  4107. auto res = cli_.Get("/%endwith%");
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4110. }
  4111. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4112. auto res = cli_.Get("/%uendwith%");
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4115. }
  4116. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4117. auto res = cli_.Get("/hello?aaa=bbb%");
  4118. ASSERT_TRUE(res);
  4119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4120. }
  4121. TEST_F(ServerTest, PlusSignEncoding) {
  4122. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::OK_200, res->status);
  4125. EXPECT_EQ("a +b", res->body);
  4126. }
  4127. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4128. // This test simulates a potential DoS attack using many headers
  4129. // to verify our security fix prevents memory exhaustion
  4130. httplib::Headers attack_headers;
  4131. // Attempt to add many headers like an attacker would (200 headers to far
  4132. // exceed limit)
  4133. for (int i = 0; i < 200; i++) {
  4134. std::string name = "X-Attack-Header-" + std::to_string(i);
  4135. std::string value = "attack_payload_" + std::to_string(i);
  4136. attack_headers.emplace(name, value);
  4137. }
  4138. // Try to POST with excessive headers
  4139. cli_.set_keep_alive(true);
  4140. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4141. // Should either fail or return 400 Bad Request due to security limit
  4142. if (res) {
  4143. // If we get a response, it should be 400 Bad Request
  4144. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4145. EXPECT_EQ("close", res->get_header_value("Connection"));
  4146. }
  4147. EXPECT_FALSE(cli_.is_socket_open());
  4148. }
  4149. TEST_F(ServerTest, MultipartFormData) {
  4150. UploadFormDataItems items = {
  4151. {"text1", "text default", "", ""},
  4152. {"text2", "aωb", "", ""},
  4153. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4154. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4155. {"file3", "", "", "application/octet-stream"},
  4156. {"file4", "", "", " application/json tmp-string "}};
  4157. auto res = cli_.Post("/multipart", items);
  4158. ASSERT_TRUE(res);
  4159. EXPECT_EQ(StatusCode::OK_200, res->status);
  4160. }
  4161. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4162. UploadFormDataItems items = {
  4163. {"text", "default text", "", ""},
  4164. {"multi_text1", "aaaaa", "", ""},
  4165. {"multi_text1", "bbbbb", "", ""},
  4166. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4167. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4168. "application/json"},
  4169. };
  4170. auto res = cli_.Post("/multipart/multi_file_values", items);
  4171. ASSERT_TRUE(res);
  4172. EXPECT_EQ(StatusCode::OK_200, res->status);
  4173. }
  4174. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4175. auto res = cli_.Get("/hi");
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::OK_200, res->status);
  4178. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4179. EXPECT_EQ("Hello World!", res->body);
  4180. }
  4181. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4182. Request req;
  4183. req.method = "POST";
  4184. req.path = "/chunked";
  4185. std::string host_and_port;
  4186. host_and_port += HOST;
  4187. host_and_port += ":";
  4188. host_and_port += std::to_string(PORT);
  4189. req.headers.emplace("Host", host_and_port.c_str());
  4190. req.headers.emplace("Accept", "*/*");
  4191. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4192. req.headers.emplace("Content-Type", "text/plain");
  4193. req.headers.emplace("Content-Length", "0");
  4194. req.headers.emplace(
  4195. "Transfer-Encoding",
  4196. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4197. // Client does not chunk, so make a chunked body manually.
  4198. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4199. auto res = std::make_shared<Response>();
  4200. auto error = Error::Success;
  4201. auto ret = cli_.send(req, *res, error);
  4202. ASSERT_TRUE(ret);
  4203. EXPECT_EQ(StatusCode::OK_200, res->status);
  4204. }
  4205. TEST_F(ServerTest, GetStreamed2) {
  4206. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("ab"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetStreamed) {
  4215. auto res = cli_.Get("/streamed");
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4219. EXPECT_EQ(std::string("aaabbb"), res->body);
  4220. }
  4221. TEST_F(ServerTest, GetStreamedWithRange1) {
  4222. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4225. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(true, res->has_header("Content-Range"));
  4227. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4228. EXPECT_EQ(std::string("def"), res->body);
  4229. }
  4230. TEST_F(ServerTest, GetStreamedWithRange2) {
  4231. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("bcdefg"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4240. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4241. ASSERT_TRUE(res);
  4242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4243. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4244. EXPECT_EQ(true, res->has_header("Content-Range"));
  4245. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4246. EXPECT_EQ(std::string("efg"), res->body);
  4247. }
  4248. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4249. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4252. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4253. EXPECT_EQ(false, res->has_header("Content-Range"));
  4254. EXPECT_EQ(0U, res->body.size());
  4255. }
  4256. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4257. auto res = cli_.Get("/streamed-with-range",
  4258. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4259. "92233720368547758079223372036854775807"}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4262. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(0U, res->body.size());
  4265. }
  4266. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4267. auto res = cli_.Get(
  4268. "/with-range",
  4269. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4270. {"Accept-Encoding", ""}});
  4271. ASSERT_TRUE(res);
  4272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4274. EXPECT_EQ(true, res->has_header("Content-Range"));
  4275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4276. EXPECT_EQ(std::string("abcdefg"), res->body);
  4277. }
  4278. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4279. auto res = cli_.Get("/with-range", {
  4280. {"Range", "bytes=0-"},
  4281. {"Accept-Encoding", ""},
  4282. });
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4285. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4286. EXPECT_EQ(true, res->has_header("Content-Range"));
  4287. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4288. EXPECT_EQ(std::string("abcdefg"), res->body);
  4289. }
  4290. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4291. auto res =
  4292. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4293. ASSERT_TRUE(res);
  4294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4295. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4296. EXPECT_EQ(false, res->has_header("Content-Range"));
  4297. EXPECT_EQ(267U, res->body.size());
  4298. // Check that both range contents are present
  4299. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4300. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4301. // Check that Content-Range headers are present for both ranges
  4302. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4303. std::string::npos);
  4304. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4305. std::string::npos);
  4306. }
  4307. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4308. Ranges ranges;
  4309. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4310. ranges.emplace_back(0, -1);
  4311. }
  4312. auto res =
  4313. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4314. ASSERT_TRUE(res);
  4315. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4316. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4317. EXPECT_EQ(false, res->has_header("Content-Range"));
  4318. EXPECT_EQ(0U, res->body.size());
  4319. }
  4320. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4321. auto res =
  4322. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4325. EXPECT_EQ(5U, res->body.size());
  4326. // Check that overlapping ranges are coalesced into a single range
  4327. EXPECT_EQ("bcdef", res->body);
  4328. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4329. // Should be single range, not multipart
  4330. EXPECT_TRUE(res->has_header("Content-Range"));
  4331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4332. }
  4333. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4334. auto res =
  4335. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4338. EXPECT_EQ(268U, res->body.size());
  4339. // Check that both range contents are present
  4340. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4341. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4342. // Check that Content-Range headers are present for both ranges
  4343. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4344. std::string::npos);
  4345. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4346. std::string::npos);
  4347. }
  4348. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4349. auto res =
  4350. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4353. EXPECT_EQ(269U, res->body.size());
  4354. // Check that both duplicate range contents are present
  4355. size_t first_abc = res->body.find("abc\r\n");
  4356. EXPECT_TRUE(first_abc != std::string::npos);
  4357. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4358. EXPECT_TRUE(second_abc != std::string::npos);
  4359. // Check that Content-Range headers are present for both ranges
  4360. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4361. EXPECT_TRUE(first_range != std::string::npos);
  4362. size_t second_range =
  4363. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4364. EXPECT_TRUE(second_range != std::string::npos);
  4365. }
  4366. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4367. auto res = cli_.Get("/streamed-with-range?error",
  4368. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4372. EXPECT_EQ(false, res->has_header("Content-Range"));
  4373. EXPECT_EQ(0U, res->body.size());
  4374. }
  4375. TEST_F(ServerTest, GetStreamedEndless) {
  4376. uint64_t offset = 0;
  4377. auto res = cli_.Get("/streamed-cancel",
  4378. [&](const char * /*data*/, uint64_t data_length) {
  4379. if (offset < 100) {
  4380. offset += data_length;
  4381. return true;
  4382. }
  4383. return false;
  4384. });
  4385. ASSERT_TRUE(!res);
  4386. EXPECT_EQ(Error::Canceled, res.error());
  4387. }
  4388. TEST_F(ServerTest, ClientStop) {
  4389. std::atomic_size_t count{4};
  4390. std::vector<std::thread> threads;
  4391. for (auto i = count.load(); i != 0; --i) {
  4392. threads.emplace_back([&]() {
  4393. auto res = cli_.Get("/streamed-cancel",
  4394. [&](const char *, uint64_t) { return true; });
  4395. --count;
  4396. ASSERT_TRUE(!res);
  4397. EXPECT_TRUE(res.error() == Error::Canceled ||
  4398. res.error() == Error::Read || res.error() == Error::Write);
  4399. });
  4400. }
  4401. std::this_thread::sleep_for(std::chrono::seconds(2));
  4402. while (count != 0) {
  4403. cli_.stop();
  4404. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4405. }
  4406. for (auto &t : threads) {
  4407. t.join();
  4408. }
  4409. }
  4410. TEST_F(ServerTest, GetWithRange1) {
  4411. auto res = cli_.Get("/with-range", {
  4412. make_range_header({{3, 5}}),
  4413. {"Accept-Encoding", ""},
  4414. });
  4415. ASSERT_TRUE(res);
  4416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4417. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4418. EXPECT_EQ(true, res->has_header("Content-Range"));
  4419. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4420. EXPECT_EQ(std::string("def"), res->body);
  4421. }
  4422. TEST_F(ServerTest, GetWithRange2) {
  4423. auto res = cli_.Get("/with-range", {
  4424. make_range_header({{1, -1}}),
  4425. {"Accept-Encoding", ""},
  4426. });
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4429. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4430. EXPECT_EQ(true, res->has_header("Content-Range"));
  4431. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4432. EXPECT_EQ(std::string("bcdefg"), res->body);
  4433. }
  4434. TEST_F(ServerTest, GetWithRange3) {
  4435. auto res = cli_.Get("/with-range", {
  4436. make_range_header({{0, 0}}),
  4437. {"Accept-Encoding", ""},
  4438. });
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4441. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4442. EXPECT_EQ(true, res->has_header("Content-Range"));
  4443. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4444. EXPECT_EQ(std::string("a"), res->body);
  4445. }
  4446. TEST_F(ServerTest, GetWithRange4) {
  4447. auto res = cli_.Get("/with-range", {
  4448. make_range_header({{-1, 2}}),
  4449. {"Accept-Encoding", ""},
  4450. });
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4453. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ(true, res->has_header("Content-Range"));
  4455. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4456. EXPECT_EQ(std::string("fg"), res->body);
  4457. }
  4458. TEST_F(ServerTest, GetWithRange5) {
  4459. auto res = cli_.Get("/with-range", {
  4460. make_range_header({{0, 5}}),
  4461. {"Accept-Encoding", ""},
  4462. });
  4463. ASSERT_TRUE(res);
  4464. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4465. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4466. EXPECT_EQ(true, res->has_header("Content-Range"));
  4467. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4468. EXPECT_EQ(std::string("abcdef"), res->body);
  4469. }
  4470. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4471. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4472. ASSERT_TRUE(res);
  4473. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4474. }
  4475. TEST_F(ServerTest, GetWithRangeMultipart) {
  4476. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4477. ASSERT_TRUE(res);
  4478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4479. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4480. EXPECT_EQ(false, res->has_header("Content-Range"));
  4481. EXPECT_EQ(267U, res->body.size());
  4482. }
  4483. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4484. auto res =
  4485. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4488. }
  4489. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4490. auto res = cli_.Get("/with-range-customized-response",
  4491. {{make_range_header({{1, 2}})}});
  4492. ASSERT_TRUE(res);
  4493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4494. EXPECT_EQ(true, res->has_header("Content-Length"));
  4495. EXPECT_EQ(false, res->has_header("Content-Range"));
  4496. EXPECT_EQ(JSON_DATA, res->body);
  4497. }
  4498. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4499. auto res = cli_.Get("/with-range-customized-response",
  4500. {{make_range_header({{1, 2}, {4, 5}})}});
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4503. EXPECT_EQ(true, res->has_header("Content-Length"));
  4504. EXPECT_EQ(false, res->has_header("Content-Range"));
  4505. EXPECT_EQ(JSON_DATA, res->body);
  4506. }
  4507. TEST_F(ServerTest, Issue1772) {
  4508. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4511. }
  4512. TEST_F(ServerTest, Issue609) {
  4513. auto res = cli_.Delete("/issue609");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ(std::string("ok"), res->body);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedChunked) {
  4519. auto res = cli_.Get("/streamed-chunked");
  4520. ASSERT_TRUE(res);
  4521. EXPECT_EQ(StatusCode::OK_200, res->status);
  4522. EXPECT_EQ(std::string("123456789"), res->body);
  4523. }
  4524. TEST_F(ServerTest, GetStreamedChunked2) {
  4525. auto res = cli_.Get("/streamed-chunked2");
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. EXPECT_EQ(std::string("123456789"), res->body);
  4529. }
  4530. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4531. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. EXPECT_EQ(std::string("123456789"), res->body);
  4535. EXPECT_TRUE(res->has_header("Trailer"));
  4536. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4537. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4538. // Trailers are now stored separately from headers (security fix)
  4539. EXPECT_EQ(2U, res->trailers.size());
  4540. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4541. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4542. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4543. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4544. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4545. // Verify trailers are NOT in headers (security verification)
  4546. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4547. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4548. }
  4549. TEST_F(ServerTest, LargeChunkedPost) {
  4550. Request req;
  4551. req.method = "POST";
  4552. req.path = "/large-chunked";
  4553. std::string host_and_port;
  4554. host_and_port += HOST;
  4555. host_and_port += ":";
  4556. host_and_port += std::to_string(PORT);
  4557. req.headers.emplace("Host", host_and_port.c_str());
  4558. req.headers.emplace("Accept", "*/*");
  4559. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4560. req.headers.emplace("Content-Type", "text/plain");
  4561. req.headers.emplace("Content-Length", "0");
  4562. req.headers.emplace("Transfer-Encoding", "chunked");
  4563. std::string long_string(30 * 1024u, 'a');
  4564. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4565. // Attempt to make a large enough post to exceed OS buffers, to test that
  4566. // the server handles short reads if the full chunk data isn't available.
  4567. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4568. auto res = std::make_shared<Response>();
  4569. auto error = Error::Success;
  4570. auto ret = cli_.send(req, *res, error);
  4571. ASSERT_TRUE(ret);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. }
  4574. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4575. auto res = cli_.Get("/remote_addr");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4579. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4580. }
  4581. TEST_F(ServerTest, GetMethodLocalAddr) {
  4582. auto res = cli_.Get("/local_addr");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4586. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4587. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4588. }
  4589. TEST_F(ServerTest, HTTPResponseSplitting) {
  4590. auto res = cli_.Get("/http_response_splitting");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. }
  4594. TEST_F(ServerTest, SlowRequest) {
  4595. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4596. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4597. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4598. }
  4599. #if 0
  4600. TEST_F(ServerTest, SlowPost) {
  4601. char buffer[64 * 1024];
  4602. memset(buffer, 0x42, sizeof(buffer));
  4603. auto res = cli_.Post(
  4604. "/slowpost", 64 * 1024 * 1024,
  4605. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4606. auto ret = sink.write(buffer, sizeof(buffer));
  4607. EXPECT_TRUE(ret);
  4608. return true;
  4609. },
  4610. "text/plain");
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(StatusCode::OK_200, res->status);
  4613. }
  4614. TEST_F(ServerTest, SlowPostFail) {
  4615. char buffer[64 * 1024];
  4616. memset(buffer, 0x42, sizeof(buffer));
  4617. cli_.set_write_timeout(std::chrono::seconds(0));
  4618. auto res = cli_.Post(
  4619. "/slowpost", 64 * 1024 * 1024,
  4620. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4621. sink.write(buffer, sizeof(buffer));
  4622. return true;
  4623. },
  4624. "text/plain");
  4625. ASSERT_TRUE(!res);
  4626. EXPECT_EQ(Error::Write, res.error());
  4627. }
  4628. #endif
  4629. TEST_F(ServerTest, Put) {
  4630. auto res = cli_.Put("/put", "PUT", "text/plain");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("PUT", res->body);
  4634. }
  4635. TEST_F(ServerTest, PutWithContentProvider) {
  4636. auto res = cli_.Put(
  4637. "/put", 3,
  4638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4639. sink.os << "PUT";
  4640. return true;
  4641. },
  4642. "text/plain");
  4643. ASSERT_TRUE(res);
  4644. EXPECT_EQ(StatusCode::OK_200, res->status);
  4645. EXPECT_EQ("PUT", res->body);
  4646. }
  4647. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4648. auto res = cli_.Post(
  4649. "/post", 42,
  4650. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4651. return false;
  4652. },
  4653. "text/plain");
  4654. ASSERT_TRUE(!res);
  4655. EXPECT_EQ(Error::Canceled, res.error());
  4656. }
  4657. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4658. auto res = cli_.Put(
  4659. "/put",
  4660. [](size_t /*offset*/, DataSink &sink) {
  4661. sink.os << "PUT";
  4662. sink.done();
  4663. return true;
  4664. },
  4665. "text/plain");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("PUT", res->body);
  4669. }
  4670. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4671. auto res = cli_.Post(
  4672. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4673. "text/plain");
  4674. ASSERT_TRUE(!res);
  4675. EXPECT_EQ(Error::Canceled, res.error());
  4676. }
  4677. TEST_F(ServerTest, PostLoopBack) {
  4678. std::string body;
  4679. auto res = cli_.Post(
  4680. "/post-loopback", 9,
  4681. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4682. EXPECT_EQ(9u, length);
  4683. sink.write("123", 3);
  4684. sink.write("456", 3);
  4685. sink.write("789", 3);
  4686. return true;
  4687. },
  4688. "text/plain",
  4689. [&body](const char *data, size_t data_length) {
  4690. body.append(data, data_length);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(res);
  4694. EXPECT_EQ(StatusCode::OK_200, res->status);
  4695. EXPECT_EQ("123456789", body);
  4696. }
  4697. TEST_F(ServerTest, PutLoopBack) {
  4698. std::string body;
  4699. auto res = cli_.Put(
  4700. "/put-loopback", 9,
  4701. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4702. EXPECT_EQ(9u, length);
  4703. sink.write("123", 3);
  4704. sink.write("456", 3);
  4705. sink.write("789", 3);
  4706. return true;
  4707. },
  4708. "text/plain",
  4709. [&body](const char *data, size_t data_length) {
  4710. body.append(data, data_length);
  4711. return true;
  4712. });
  4713. ASSERT_TRUE(res);
  4714. EXPECT_EQ(StatusCode::OK_200, res->status);
  4715. EXPECT_EQ("123456789", body);
  4716. }
  4717. TEST_F(ServerTest, PatchLoopBack) {
  4718. std::string body;
  4719. auto res = cli_.Patch(
  4720. "/patch-loopback", 9,
  4721. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4722. EXPECT_EQ(9u, length);
  4723. sink.write("123", 3);
  4724. sink.write("456", 3);
  4725. sink.write("789", 3);
  4726. return true;
  4727. },
  4728. "text/plain",
  4729. [&body](const char *data, size_t data_length) {
  4730. body.append(data, data_length);
  4731. return true;
  4732. });
  4733. ASSERT_TRUE(res);
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("123456789", body);
  4736. }
  4737. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4738. std::string body;
  4739. auto res = cli_.Post(
  4740. "/post-loopback",
  4741. [](size_t /*offset*/, DataSink &sink) {
  4742. sink.write("123", 3);
  4743. sink.write("456", 3);
  4744. sink.write("789", 3);
  4745. sink.done();
  4746. return true;
  4747. },
  4748. "text/plain",
  4749. [&body](const char *data, size_t data_length) {
  4750. body.append(data, data_length);
  4751. return true;
  4752. });
  4753. ASSERT_TRUE(res);
  4754. EXPECT_EQ(StatusCode::OK_200, res->status);
  4755. EXPECT_EQ("123456789", body);
  4756. }
  4757. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4758. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4759. cli_.set_compress(true);
  4760. auto res = cli_.Put(
  4761. "/put", 3,
  4762. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4763. sink.os << "PUT";
  4764. return true;
  4765. },
  4766. "text/plain");
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. EXPECT_EQ("PUT", res->body);
  4770. }
  4771. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4772. cli_.set_compress(true);
  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, PutWithContentProviderWithoutLengthWithGzip) {
  4783. cli_.set_compress(true);
  4784. auto res = cli_.Put(
  4785. "/put",
  4786. [](size_t /*offset*/, DataSink &sink) {
  4787. sink.os << "PUT";
  4788. sink.done();
  4789. return true;
  4790. },
  4791. "text/plain");
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ("PUT", res->body);
  4795. }
  4796. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4797. cli_.set_compress(true);
  4798. auto res = cli_.Post(
  4799. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4800. "text/plain");
  4801. ASSERT_TRUE(!res);
  4802. EXPECT_EQ(Error::Canceled, res.error());
  4803. }
  4804. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4805. cli_.set_compress(true);
  4806. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4807. ASSERT_TRUE(res);
  4808. EXPECT_EQ(StatusCode::OK_200, res->status);
  4809. EXPECT_EQ(LARGE_DATA, res->body);
  4810. }
  4811. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4812. #ifdef CPPHTTPLIB_SSL_ENABLED
  4813. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4814. Client cli(s.c_str());
  4815. cli.enable_server_certificate_verification(false);
  4816. #else
  4817. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4818. Client cli(s.c_str());
  4819. #endif
  4820. cli.set_compress(true);
  4821. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4822. ASSERT_TRUE(res);
  4823. EXPECT_EQ(StatusCode::OK_200, res->status);
  4824. EXPECT_EQ(LARGE_DATA, res->body);
  4825. // The compressed size should be less than a 10th of the original. May vary
  4826. // depending on the zlib library.
  4827. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4828. static_cast<uint64_t>(10 * 1024 * 1024));
  4829. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4830. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4831. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4832. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4833. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4834. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4835. #endif
  4836. }
  4837. TEST_F(ServerTest, PutContentWithDeflate) {
  4838. cli_.set_compress(false);
  4839. Headers headers;
  4840. headers.emplace("Content-Encoding", "deflate");
  4841. // PUT in deflate format:
  4842. auto res = cli_.Put("/put", headers,
  4843. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("PUT", res->body);
  4847. }
  4848. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4849. Headers headers;
  4850. headers.emplace("Accept-Encoding", "gzip, deflate");
  4851. auto res = cli_.Get("/streamed-chunked", headers);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ(std::string("123456789"), res->body);
  4855. }
  4856. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4857. Headers headers;
  4858. headers.emplace("Accept-Encoding", "gzip, deflate");
  4859. auto res = cli_.Get("/streamed-chunked2", headers);
  4860. ASSERT_TRUE(res);
  4861. EXPECT_EQ(StatusCode::OK_200, res->status);
  4862. EXPECT_EQ(std::string("123456789"), res->body);
  4863. }
  4864. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4865. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::OK_200, res->status);
  4868. }
  4869. TEST(GzipDecompressor, ChunkedDecompression) {
  4870. std::string data;
  4871. for (size_t i = 0; i < 32 * 1024; ++i) {
  4872. data.push_back(static_cast<char>('a' + i % 26));
  4873. }
  4874. std::string compressed_data;
  4875. {
  4876. httplib::detail::gzip_compressor compressor;
  4877. bool result = compressor.compress(
  4878. data.data(), data.size(),
  4879. /*last=*/true,
  4880. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4881. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4882. compressed_data_size);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(result);
  4886. }
  4887. std::string decompressed_data;
  4888. {
  4889. httplib::detail::gzip_decompressor decompressor;
  4890. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4891. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4892. size_t chunk_size = 130;
  4893. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4894. chunk_begin += chunk_size) {
  4895. size_t current_chunk_size =
  4896. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4897. bool result = decompressor.decompress(
  4898. compressed_data.data() + chunk_begin, current_chunk_size,
  4899. [&](const char *decompressed_data_chunk,
  4900. size_t decompressed_data_chunk_size) {
  4901. decompressed_data.insert(decompressed_data.size(),
  4902. decompressed_data_chunk,
  4903. decompressed_data_chunk_size);
  4904. return true;
  4905. });
  4906. ASSERT_TRUE(result);
  4907. }
  4908. }
  4909. ASSERT_EQ(data, decompressed_data);
  4910. }
  4911. TEST(GzipDecompressor, DeflateDecompression) {
  4912. std::string original_text = "Raw deflate without gzip";
  4913. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4914. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4915. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4916. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4917. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4918. std::string decompressed_data;
  4919. {
  4920. httplib::detail::gzip_decompressor decompressor;
  4921. bool result = decompressor.decompress(
  4922. compressed_data.data(), compressed_data.size(),
  4923. [&](const char *decompressed_data_chunk,
  4924. size_t decompressed_data_chunk_size) {
  4925. decompressed_data.insert(decompressed_data.size(),
  4926. decompressed_data_chunk,
  4927. decompressed_data_chunk_size);
  4928. return true;
  4929. });
  4930. ASSERT_TRUE(result);
  4931. }
  4932. ASSERT_EQ(original_text, decompressed_data);
  4933. }
  4934. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4935. std::string original_text = "Raw deflate without gzip";
  4936. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4937. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4938. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4939. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4940. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4941. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4942. std::string decompressed_data;
  4943. {
  4944. httplib::detail::gzip_decompressor decompressor;
  4945. bool result = decompressor.decompress(
  4946. compressed_data.data(), compressed_data.size(),
  4947. [&](const char *decompressed_data_chunk,
  4948. size_t decompressed_data_chunk_size) {
  4949. decompressed_data.insert(decompressed_data.size(),
  4950. decompressed_data_chunk,
  4951. decompressed_data_chunk_size);
  4952. return true;
  4953. });
  4954. ASSERT_TRUE(result);
  4955. }
  4956. ASSERT_EQ(original_text, decompressed_data);
  4957. }
  4958. #endif
  4959. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4960. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4961. Headers headers;
  4962. headers.emplace("Accept-Encoding", "br");
  4963. auto res = cli_.Get("/streamed-chunked", headers);
  4964. ASSERT_TRUE(res);
  4965. EXPECT_EQ(StatusCode::OK_200, res->status);
  4966. EXPECT_EQ(std::string("123456789"), res->body);
  4967. }
  4968. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4969. Headers headers;
  4970. headers.emplace("Accept-Encoding", "br");
  4971. auto res = cli_.Get("/streamed-chunked2", headers);
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ(StatusCode::OK_200, res->status);
  4974. EXPECT_EQ(std::string("123456789"), res->body);
  4975. }
  4976. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4977. cli_.set_compress(true);
  4978. auto res = cli_.Put(
  4979. "/put", 3,
  4980. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4981. sink.os << "PUT";
  4982. return true;
  4983. },
  4984. "text/plain");
  4985. ASSERT_TRUE(res);
  4986. EXPECT_EQ(StatusCode::OK_200, res->status);
  4987. EXPECT_EQ("PUT", res->body);
  4988. }
  4989. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4990. cli_.set_compress(true);
  4991. auto res = cli_.Put(
  4992. "/put",
  4993. [](size_t /*offset*/, DataSink &sink) {
  4994. sink.os << "PUT";
  4995. sink.done();
  4996. return true;
  4997. },
  4998. "text/plain");
  4999. ASSERT_TRUE(res);
  5000. EXPECT_EQ(StatusCode::OK_200, res->status);
  5001. EXPECT_EQ("PUT", res->body);
  5002. }
  5003. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5004. cli_.set_compress(true);
  5005. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. EXPECT_EQ(LARGE_DATA, res->body);
  5009. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5010. }
  5011. #endif
  5012. TEST_F(ServerTest, Patch) {
  5013. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5014. ASSERT_TRUE(res);
  5015. EXPECT_EQ(StatusCode::OK_200, res->status);
  5016. EXPECT_EQ("PATCH", res->body);
  5017. }
  5018. TEST_F(ServerTest, Delete) {
  5019. auto res = cli_.Delete("/delete");
  5020. ASSERT_TRUE(res);
  5021. EXPECT_EQ(StatusCode::OK_200, res->status);
  5022. EXPECT_EQ("DELETE", res->body);
  5023. }
  5024. TEST_F(ServerTest, DeleteContentReceiver) {
  5025. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5026. ASSERT_TRUE(res);
  5027. EXPECT_EQ(StatusCode::OK_200, res->status);
  5028. EXPECT_EQ("content", res->body);
  5029. }
  5030. TEST_F(ServerTest, Options) {
  5031. auto res = cli_.Options("*");
  5032. ASSERT_TRUE(res);
  5033. EXPECT_EQ(StatusCode::OK_200, res->status);
  5034. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5035. EXPECT_TRUE(res->body.empty());
  5036. }
  5037. TEST_F(ServerTest, URL) {
  5038. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. }
  5042. TEST_F(ServerTest, ArrayParam) {
  5043. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5044. ASSERT_TRUE(res);
  5045. EXPECT_EQ(StatusCode::OK_200, res->status);
  5046. }
  5047. TEST_F(ServerTest, NoMultipleHeaders) {
  5048. Headers headers = {{"Content-Length", "5"}};
  5049. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5050. "text/plain");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. }
  5054. TEST_F(ServerTest, PostContentReceiver) {
  5055. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5056. ASSERT_TRUE(res);
  5057. ASSERT_EQ(StatusCode::OK_200, res->status);
  5058. ASSERT_EQ("content", res->body);
  5059. }
  5060. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5061. UploadFormDataItems items = {
  5062. {"text1", "text default", "", ""},
  5063. {"text2", "aωb", "", ""},
  5064. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5065. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5066. {"file3", "", "", "application/octet-stream"},
  5067. };
  5068. auto res = cli_.Post("/content_receiver", items);
  5069. ASSERT_TRUE(res);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5073. UploadFormDataItems items = {
  5074. {"text1", "text default", "", ""},
  5075. {"text2", "aωb", "", ""},
  5076. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5077. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5078. {"file3", "", "", "application/octet-stream"},
  5079. };
  5080. auto boundary = std::string("+++++");
  5081. std::string body;
  5082. for (const auto &item : items) {
  5083. body += "--" + boundary + "\r\n";
  5084. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5085. if (!item.filename.empty()) {
  5086. body += "; filename=\"" + item.filename + "\"";
  5087. }
  5088. body += "\r\n";
  5089. if (!item.content_type.empty()) {
  5090. body += "Content-Type: " + item.content_type + "\r\n";
  5091. }
  5092. body += "\r\n";
  5093. body += item.content + "\r\n";
  5094. }
  5095. body += "--" + boundary + "--\r\n";
  5096. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5097. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. }
  5101. TEST_F(ServerTest, PostContentReceiverGzip) {
  5102. cli_.set_compress(true);
  5103. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5104. ASSERT_TRUE(res);
  5105. ASSERT_EQ(StatusCode::OK_200, res->status);
  5106. ASSERT_EQ("content", res->body);
  5107. }
  5108. TEST_F(ServerTest, PutContentReceiver) {
  5109. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. ASSERT_EQ(StatusCode::OK_200, res->status);
  5112. ASSERT_EQ("content", res->body);
  5113. }
  5114. TEST_F(ServerTest, PatchContentReceiver) {
  5115. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5116. ASSERT_TRUE(res);
  5117. ASSERT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ("content", res->body);
  5119. }
  5120. template <typename ClientType>
  5121. void TestWithHeadersAndContentReceiver(
  5122. ClientType &cli,
  5123. std::function<Result(ClientType &, const std::string &, const Headers &,
  5124. const std::string &, const std::string &,
  5125. ContentReceiver, DownloadProgress)>
  5126. request_func) {
  5127. Headers headers;
  5128. headers.emplace("X-Custom-Header", "test-value");
  5129. std::string received_body;
  5130. auto res = request_func(
  5131. cli, "/content_receiver", headers, "content", "application/json",
  5132. [&](const char *data, size_t data_length) {
  5133. received_body.append(data, data_length);
  5134. return true;
  5135. },
  5136. nullptr);
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("content", received_body);
  5140. }
  5141. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5142. #ifdef CPPHTTPLIB_SSL_ENABLED
  5143. using ClientT = SSLClient;
  5144. #else
  5145. using ClientT = Client;
  5146. #endif
  5147. TestWithHeadersAndContentReceiver<ClientT>(
  5148. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5149. const std::string &body, const std::string &content_type,
  5150. ContentReceiver receiver, DownloadProgress progress) {
  5151. return cli.Post(path, headers, body, content_type, receiver, progress);
  5152. });
  5153. }
  5154. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5155. #ifdef CPPHTTPLIB_SSL_ENABLED
  5156. using ClientT = SSLClient;
  5157. #else
  5158. using ClientT = Client;
  5159. #endif
  5160. TestWithHeadersAndContentReceiver<ClientT>(
  5161. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5162. const std::string &body, const std::string &content_type,
  5163. ContentReceiver receiver, DownloadProgress progress) {
  5164. return cli.Put(path, headers, body, content_type, receiver, progress);
  5165. });
  5166. }
  5167. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5168. #ifdef CPPHTTPLIB_SSL_ENABLED
  5169. using ClientT = SSLClient;
  5170. #else
  5171. using ClientT = Client;
  5172. #endif
  5173. TestWithHeadersAndContentReceiver<ClientT>(
  5174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5175. const std::string &body, const std::string &content_type,
  5176. ContentReceiver receiver, DownloadProgress progress) {
  5177. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5178. });
  5179. }
  5180. template <typename ClientType>
  5181. void TestWithHeadersAndContentReceiverWithProgress(
  5182. ClientType &cli,
  5183. std::function<Result(ClientType &, const std::string &, const Headers &,
  5184. const std::string &, const std::string &,
  5185. ContentReceiver, DownloadProgress)>
  5186. request_func) {
  5187. Headers headers;
  5188. headers.emplace("X-Test-Header", "progress-test");
  5189. std::string received_body;
  5190. auto progress_called = false;
  5191. auto res = request_func(
  5192. cli, "/content_receiver", headers, "content", "text/plain",
  5193. [&](const char *data, size_t data_length) {
  5194. received_body.append(data, data_length);
  5195. return true;
  5196. },
  5197. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5198. progress_called = true;
  5199. return true;
  5200. });
  5201. ASSERT_TRUE(res);
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. EXPECT_EQ("content", received_body);
  5204. EXPECT_TRUE(progress_called);
  5205. }
  5206. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. using ClientT = SSLClient;
  5209. #else
  5210. using ClientT = Client;
  5211. #endif
  5212. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5213. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5214. const std::string &body, const std::string &content_type,
  5215. ContentReceiver receiver, DownloadProgress progress) {
  5216. return cli.Post(path, headers, body, content_type, receiver, progress);
  5217. });
  5218. }
  5219. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver, DownloadProgress progress) {
  5229. return cli.Put(path, headers, body, content_type, receiver, progress);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver, DownloadProgress progress) {
  5242. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5243. });
  5244. }
  5245. template <typename ClientType>
  5246. void TestWithHeadersAndContentReceiverError(
  5247. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5248. const Headers &, const std::string &,
  5249. const std::string &, ContentReceiver)>
  5250. request_func) {
  5251. Headers headers;
  5252. headers.emplace("X-Error-Test", "true");
  5253. std::string received_body;
  5254. auto receiver_failed = false;
  5255. auto res =
  5256. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5257. [&](const char *data, size_t data_length) {
  5258. received_body.append(data, data_length);
  5259. receiver_failed = true;
  5260. return false;
  5261. });
  5262. ASSERT_FALSE(res);
  5263. EXPECT_TRUE(receiver_failed);
  5264. }
  5265. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5266. #ifdef CPPHTTPLIB_SSL_ENABLED
  5267. using ClientT = SSLClient;
  5268. #else
  5269. using ClientT = Client;
  5270. #endif
  5271. TestWithHeadersAndContentReceiverError<ClientT>(
  5272. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5273. const std::string &body, const std::string &content_type,
  5274. ContentReceiver receiver) {
  5275. return cli.Post(path, headers, body, content_type, receiver);
  5276. });
  5277. }
  5278. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5279. #ifdef CPPHTTPLIB_SSL_ENABLED
  5280. using ClientT = SSLClient;
  5281. #else
  5282. using ClientT = Client;
  5283. #endif
  5284. TestWithHeadersAndContentReceiverError<ClientT>(
  5285. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5286. const std::string &body, const std::string &content_type,
  5287. ContentReceiver receiver) {
  5288. return cli.Put(path, headers, body, content_type, receiver);
  5289. });
  5290. }
  5291. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5292. #ifdef CPPHTTPLIB_SSL_ENABLED
  5293. using ClientT = SSLClient;
  5294. #else
  5295. using ClientT = Client;
  5296. #endif
  5297. TestWithHeadersAndContentReceiverError<ClientT>(
  5298. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5299. const std::string &body, const std::string &content_type,
  5300. ContentReceiver receiver) {
  5301. return cli.Patch(path, headers, body, content_type, receiver);
  5302. });
  5303. }
  5304. TEST_F(ServerTest, PostQueryStringAndBody) {
  5305. auto res =
  5306. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5307. ASSERT_TRUE(res);
  5308. ASSERT_EQ(StatusCode::OK_200, res->status);
  5309. }
  5310. TEST_F(ServerTest, HTTP2Magic) {
  5311. Request req;
  5312. req.method = "PRI";
  5313. req.path = "*";
  5314. req.body = "SM";
  5315. auto res = std::make_shared<Response>();
  5316. auto error = Error::Success;
  5317. auto ret = cli_.send(req, *res, error);
  5318. ASSERT_TRUE(ret);
  5319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5320. }
  5321. TEST_F(ServerTest, KeepAlive) {
  5322. auto res = cli_.Get("/hi");
  5323. ASSERT_TRUE(res);
  5324. EXPECT_EQ(StatusCode::OK_200, res->status);
  5325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5326. EXPECT_EQ("Hello World!", res->body);
  5327. res = cli_.Get("/hi");
  5328. ASSERT_TRUE(res);
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5331. EXPECT_EQ("Hello World!", res->body);
  5332. res = cli_.Get("/hi");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5336. EXPECT_EQ("Hello World!", res->body);
  5337. res = cli_.Get("/not-exist");
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5340. res = cli_.Post("/empty", "", "text/plain");
  5341. ASSERT_TRUE(res);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5344. EXPECT_EQ("empty", res->body);
  5345. EXPECT_EQ("close", res->get_header_value("Connection"));
  5346. res = cli_.Post(
  5347. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5348. "text/plain");
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5352. EXPECT_EQ("empty", res->body);
  5353. cli_.set_keep_alive(false);
  5354. res = cli_.Get("/last-request");
  5355. ASSERT_TRUE(res);
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. EXPECT_EQ("close", res->get_header_value("Connection"));
  5358. }
  5359. TEST_F(ServerTest, TooManyRedirect) {
  5360. cli_.set_follow_location(true);
  5361. auto res = cli_.Get("/redirect/0");
  5362. ASSERT_TRUE(!res);
  5363. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5364. }
  5365. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5366. Request req;
  5367. req.method = "FOOBAR";
  5368. req.path = "/hi";
  5369. cli_.set_keep_alive(true);
  5370. auto res = cli_.send(req);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5373. EXPECT_EQ("close", res->get_header_value("Connection"));
  5374. EXPECT_FALSE(cli_.is_socket_open());
  5375. }
  5376. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5377. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5378. TEST_F(ServerTest, Gzip) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "gzip, deflate");
  5381. auto res = cli_.Get("/compress", headers);
  5382. ASSERT_TRUE(res);
  5383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5385. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5387. "7890123456789012345678901234567890",
  5388. res->body);
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. }
  5391. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5392. Headers headers;
  5393. headers.emplace("Accept-Encoding", "gzip, deflate");
  5394. auto res = cli_.Get("/compress-with-charset", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("application/json; charset=utf-8",
  5398. res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. res->body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5405. Headers headers;
  5406. headers.emplace("Accept-Encoding", "");
  5407. auto res = cli_.Get("/compress", headers);
  5408. ASSERT_TRUE(res);
  5409. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5411. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5413. "7890123456789012345678901234567890",
  5414. res->body);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithContentReceiver) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "gzip, deflate");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "gzip, deflate");
  5439. cli_.set_decompress(false);
  5440. auto res = cli_.Get("/compress", headers);
  5441. ASSERT_TRUE(res);
  5442. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5444. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5445. EXPECT_EQ(33U, res->body.size());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. }
  5448. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5449. Headers headers;
  5450. headers.emplace("Accept-Encoding", "");
  5451. std::string body;
  5452. auto res = cli_.Get("/compress", headers,
  5453. [&](const char *data, uint64_t data_length) {
  5454. EXPECT_EQ(100U, data_length);
  5455. body.append(data, data_length);
  5456. return true;
  5457. });
  5458. ASSERT_TRUE(res);
  5459. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5461. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5463. "7890123456789012345678901234567890",
  5464. body);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. }
  5467. TEST_F(ServerTest, NoGzip) {
  5468. Headers headers;
  5469. headers.emplace("Accept-Encoding", "gzip, deflate");
  5470. auto res = cli_.Get("/nocompress", headers);
  5471. ASSERT_TRUE(res);
  5472. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5473. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5474. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5475. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5476. "7890123456789012345678901234567890",
  5477. res->body);
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. }
  5480. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip, deflate");
  5483. std::string body;
  5484. auto res = cli_.Get("/nocompress", headers,
  5485. [&](const char *data, uint64_t data_length) {
  5486. EXPECT_EQ(100U, data_length);
  5487. body.append(data, data_length);
  5488. return true;
  5489. });
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5492. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5493. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5494. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5495. "7890123456789012345678901234567890",
  5496. body);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. }
  5499. TEST_F(ServerTest, MultipartFormDataGzip) {
  5500. UploadFormDataItems items = {
  5501. {"key1", "test", "", ""},
  5502. {"key2", "--abcdefg123", "", ""},
  5503. };
  5504. cli_.set_compress(true);
  5505. auto res = cli_.Post("/compress-multipart", items);
  5506. ASSERT_TRUE(res);
  5507. EXPECT_EQ(StatusCode::OK_200, res->status);
  5508. }
  5509. #endif
  5510. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5511. TEST_F(ServerTest, Brotli) {
  5512. Headers headers;
  5513. headers.emplace("Accept-Encoding", "br");
  5514. auto res = cli_.Get("/compress", headers);
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5518. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5519. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5520. "7890123456789012345678901234567890",
  5521. res->body);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. }
  5524. #endif
  5525. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5526. TEST_F(ServerTest, Zstd) {
  5527. Headers headers;
  5528. headers.emplace("Accept-Encoding", "zstd");
  5529. auto res = cli_.Get("/compress", headers);
  5530. ASSERT_TRUE(res);
  5531. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5533. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5534. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5535. "7890123456789012345678901234567890",
  5536. res->body);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. }
  5539. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5540. Headers headers;
  5541. headers.emplace("Accept-Encoding", "");
  5542. auto res = cli_.Get("/compress", headers);
  5543. ASSERT_TRUE(res);
  5544. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5548. "7890123456789012345678901234567890",
  5549. res->body);
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. }
  5552. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5553. Headers headers;
  5554. headers.emplace("Accept-Encoding", "zstd");
  5555. std::string body;
  5556. auto res = cli_.Get("/compress", headers,
  5557. [&](const char *data, uint64_t data_length) {
  5558. EXPECT_EQ(100U, data_length);
  5559. body.append(data, data_length);
  5560. return true;
  5561. });
  5562. ASSERT_TRUE(res);
  5563. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5565. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5566. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5567. "7890123456789012345678901234567890",
  5568. body);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. }
  5571. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5572. Headers headers;
  5573. headers.emplace("Accept-Encoding", "zstd");
  5574. cli_.set_decompress(false);
  5575. auto res = cli_.Get("/compress", headers);
  5576. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5577. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5578. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5579. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5580. ASSERT_TRUE(res);
  5581. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5583. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(26U, res->body.size());
  5586. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5587. 0);
  5588. }
  5589. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5590. Headers headers;
  5591. headers.emplace("Accept-Encoding", "");
  5592. std::string body;
  5593. auto res = cli_.Get("/compress", headers,
  5594. [&](const char *data, uint64_t data_length) {
  5595. EXPECT_EQ(100U, data_length);
  5596. body.append(data, data_length);
  5597. return true;
  5598. });
  5599. ASSERT_TRUE(res);
  5600. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5604. "7890123456789012345678901234567890",
  5605. body);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. }
  5608. TEST_F(ServerTest, NoZstd) {
  5609. Headers headers;
  5610. headers.emplace("Accept-Encoding", "zstd");
  5611. auto res = cli_.Get("/nocompress", headers);
  5612. ASSERT_TRUE(res);
  5613. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5614. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5617. "7890123456789012345678901234567890",
  5618. res->body);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5622. Headers headers;
  5623. headers.emplace("Accept-Encoding", "zstd");
  5624. std::string body;
  5625. auto res = cli_.Get("/nocompress", headers,
  5626. [&](const char *data, uint64_t data_length) {
  5627. EXPECT_EQ(100U, data_length);
  5628. body.append(data, data_length);
  5629. return true;
  5630. });
  5631. ASSERT_TRUE(res);
  5632. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5633. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5636. "7890123456789012345678901234567890",
  5637. body);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. }
  5640. // TODO: How to enable zstd ??
  5641. TEST_F(ServerTest, MultipartFormDataZstd) {
  5642. UploadFormDataItems items = {
  5643. {"key1", "test", "", ""},
  5644. {"key2", "--abcdefg123", "", ""},
  5645. };
  5646. Headers headers;
  5647. headers.emplace("Accept-Encoding", "zstd");
  5648. cli_.set_compress(true);
  5649. auto res = cli_.Post("/compress-multipart", headers, items);
  5650. ASSERT_TRUE(res);
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. }
  5653. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5654. Headers headers;
  5655. headers.emplace("Accept-Encoding", "zstd");
  5656. cli_.set_compress(true);
  5657. auto res = cli_.Put(
  5658. "/put", headers, 3,
  5659. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5660. sink.os << "PUT";
  5661. return true;
  5662. },
  5663. "text/plain");
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. EXPECT_EQ("PUT", res->body);
  5667. }
  5668. // Pre-compression logging tests
  5669. TEST_F(ServerTest, PreCompressionLogging) {
  5670. // Test data for compression (matches the actual /compress endpoint content)
  5671. const std::string test_content =
  5672. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5673. "3456789012345678901234567890";
  5674. // Variables to capture logging data
  5675. std::string pre_compression_body;
  5676. std::string pre_compression_content_type;
  5677. std::string pre_compression_content_encoding;
  5678. std::string post_compression_body;
  5679. std::string post_compression_content_type;
  5680. std::string post_compression_content_encoding;
  5681. // Set up pre-compression logger
  5682. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5683. const Response &res) {
  5684. pre_compression_body = res.body;
  5685. pre_compression_content_type = res.get_header_value("Content-Type");
  5686. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5687. });
  5688. // Set up post-compression logger
  5689. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5690. post_compression_body = res.body;
  5691. post_compression_content_type = res.get_header_value("Content-Type");
  5692. post_compression_content_encoding =
  5693. res.get_header_value("Content-Encoding");
  5694. });
  5695. // Test with gzip compression
  5696. Headers headers;
  5697. headers.emplace("Accept-Encoding", "gzip");
  5698. auto res = cli_.Get("/compress", headers);
  5699. // Verify response was compressed
  5700. ASSERT_TRUE(res);
  5701. EXPECT_EQ(StatusCode::OK_200, res->status);
  5702. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5703. // Verify pre-compression logger captured uncompressed content
  5704. EXPECT_EQ(test_content, pre_compression_body);
  5705. EXPECT_EQ("text/plain", pre_compression_content_type);
  5706. EXPECT_TRUE(pre_compression_content_encoding
  5707. .empty()); // No encoding header before compression
  5708. // Verify post-compression logger captured compressed content
  5709. EXPECT_NE(test_content,
  5710. post_compression_body); // Should be different after compression
  5711. EXPECT_EQ("text/plain", post_compression_content_type);
  5712. EXPECT_EQ("gzip", post_compression_content_encoding);
  5713. // Verify compressed content is smaller
  5714. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5715. }
  5716. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5717. const std::string test_content =
  5718. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5719. "3456789012345678901234567890";
  5720. std::string pre_compression_body;
  5721. std::string post_compression_body;
  5722. svr_.set_pre_compression_logger(
  5723. [&](const Request & /*req*/, const Response &res) {
  5724. pre_compression_body = res.body;
  5725. });
  5726. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5727. post_compression_body = res.body;
  5728. });
  5729. Headers headers;
  5730. headers.emplace("Accept-Encoding", "br");
  5731. auto res = cli_.Get("/compress", headers);
  5732. ASSERT_TRUE(res);
  5733. EXPECT_EQ(StatusCode::OK_200, res->status);
  5734. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5735. // Verify pre-compression content is uncompressed
  5736. EXPECT_EQ(test_content, pre_compression_body);
  5737. // Verify post-compression content is compressed
  5738. EXPECT_NE(test_content, post_compression_body);
  5739. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5740. }
  5741. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5742. const std::string test_content =
  5743. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5744. "3456789012345678901234567890";
  5745. std::string pre_compression_body;
  5746. std::string post_compression_body;
  5747. svr_.set_pre_compression_logger(
  5748. [&](const Request & /*req*/, const Response &res) {
  5749. pre_compression_body = res.body;
  5750. });
  5751. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5752. post_compression_body = res.body;
  5753. });
  5754. // Request without compression (use /nocompress endpoint)
  5755. Headers headers;
  5756. auto res = cli_.Get("/nocompress", headers);
  5757. ASSERT_TRUE(res);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5760. // Pre-compression logger should not be called when no compression is applied
  5761. EXPECT_TRUE(
  5762. pre_compression_body.empty()); // Pre-compression logger not called
  5763. EXPECT_EQ(
  5764. test_content,
  5765. post_compression_body); // Post-compression logger captures final content
  5766. }
  5767. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5768. const std::string test_content =
  5769. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5770. "3456789012345678901234567890";
  5771. std::string pre_compression_body;
  5772. bool pre_logger_called = false;
  5773. // Set only pre-compression logger
  5774. svr_.set_pre_compression_logger(
  5775. [&](const Request & /*req*/, const Response &res) {
  5776. pre_compression_body = res.body;
  5777. pre_logger_called = true;
  5778. });
  5779. Headers headers;
  5780. headers.emplace("Accept-Encoding", "gzip");
  5781. auto res = cli_.Get("/compress", headers);
  5782. ASSERT_TRUE(res);
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5785. // Verify pre-compression logger was called
  5786. EXPECT_TRUE(pre_logger_called);
  5787. EXPECT_EQ(test_content, pre_compression_body);
  5788. }
  5789. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5790. {
  5791. // Test with Expect: 100-continue header - success case
  5792. // Server returns 100 Continue, client sends body, server returns 200 OK
  5793. Request req;
  5794. req.method = "POST";
  5795. req.path = "/post-large";
  5796. req.set_header("Expect", "100-continue");
  5797. req.body = LARGE_DATA;
  5798. Response res;
  5799. auto error = Error::Success;
  5800. cli_.set_keep_alive(true);
  5801. auto ret = cli_.send(req, res, error);
  5802. EXPECT_TRUE(ret);
  5803. EXPECT_EQ(StatusCode::OK_200, res.status);
  5804. EXPECT_EQ(LARGE_DATA, res.body);
  5805. }
  5806. {
  5807. // Test with Expect: 100-continue header - error case
  5808. // Client should not send the body when server returns an error
  5809. Request req;
  5810. req.method = "POST";
  5811. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5812. req.set_header("Expect", "100-continue");
  5813. req.body = LARGE_DATA;
  5814. Response res;
  5815. auto error = Error::Success;
  5816. auto start = std::chrono::high_resolution_clock::now();
  5817. cli_.set_keep_alive(true);
  5818. auto ret = cli_.send(req, res, error);
  5819. auto end = std::chrono::high_resolution_clock::now();
  5820. auto elapsed =
  5821. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5822. .count();
  5823. // With Expect: 100-continue, request completes successfully but with error
  5824. EXPECT_TRUE(ret);
  5825. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5826. EXPECT_EQ("close", res.get_header_value("Connection"));
  5827. EXPECT_FALSE(cli_.is_socket_open());
  5828. EXPECT_LE(elapsed, 200);
  5829. }
  5830. {
  5831. // Send an extra GET request to ensure error recovery without hanging
  5832. Request req;
  5833. req.method = "GET";
  5834. req.path = "/hi";
  5835. auto start = std::chrono::high_resolution_clock::now();
  5836. auto res = cli_.send(req);
  5837. auto end = std::chrono::high_resolution_clock::now();
  5838. auto elapsed =
  5839. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5840. .count();
  5841. ASSERT_TRUE(res);
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. EXPECT_EQ("Hello World!", res->body);
  5844. EXPECT_LE(elapsed, 500);
  5845. }
  5846. }
  5847. TEST(ZstdDecompressor, ChunkedDecompression) {
  5848. std::string data;
  5849. for (size_t i = 0; i < 32 * 1024; ++i) {
  5850. data.push_back(static_cast<char>('a' + i % 26));
  5851. }
  5852. std::string compressed_data;
  5853. {
  5854. httplib::detail::zstd_compressor compressor;
  5855. bool result = compressor.compress(
  5856. data.data(), data.size(),
  5857. /*last=*/true,
  5858. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5859. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5860. compressed_data_size);
  5861. return true;
  5862. });
  5863. ASSERT_TRUE(result);
  5864. }
  5865. std::string decompressed_data;
  5866. {
  5867. httplib::detail::zstd_decompressor decompressor;
  5868. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5869. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5870. size_t chunk_size = 130;
  5871. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5872. chunk_begin += chunk_size) {
  5873. size_t current_chunk_size =
  5874. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5875. bool result = decompressor.decompress(
  5876. compressed_data.data() + chunk_begin, current_chunk_size,
  5877. [&](const char *decompressed_data_chunk,
  5878. size_t decompressed_data_chunk_size) {
  5879. decompressed_data.insert(decompressed_data.size(),
  5880. decompressed_data_chunk,
  5881. decompressed_data_chunk_size);
  5882. return true;
  5883. });
  5884. ASSERT_TRUE(result);
  5885. }
  5886. }
  5887. ASSERT_EQ(data, decompressed_data);
  5888. }
  5889. TEST(ZstdDecompressor, Decompress) {
  5890. std::string original_text = "Compressed with ZSTD";
  5891. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5892. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5893. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5894. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5895. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5896. std::string decompressed_data;
  5897. {
  5898. httplib::detail::zstd_decompressor decompressor;
  5899. bool result = decompressor.decompress(
  5900. compressed_data.data(), compressed_data.size(),
  5901. [&](const char *decompressed_data_chunk,
  5902. size_t decompressed_data_chunk_size) {
  5903. decompressed_data.insert(decompressed_data.size(),
  5904. decompressed_data_chunk,
  5905. decompressed_data_chunk_size);
  5906. return true;
  5907. });
  5908. ASSERT_TRUE(result);
  5909. }
  5910. ASSERT_EQ(original_text, decompressed_data);
  5911. }
  5912. #endif
  5913. // Sends a raw request to a server listening at HOST:PORT.
  5914. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5915. std::string *resp = nullptr) {
  5916. auto error = Error::Success;
  5917. auto client_sock = detail::create_client_socket(
  5918. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5919. /*connection_timeout_sec=*/5, 0,
  5920. /*read_timeout_sec=*/5, 0,
  5921. /*write_timeout_sec=*/5, 0, std::string(), error);
  5922. if (client_sock == INVALID_SOCKET) { return false; }
  5923. auto ret = detail::process_client_socket(
  5924. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5925. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5926. if (req.size() !=
  5927. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5928. return false;
  5929. }
  5930. char buf[512];
  5931. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5932. while (line_reader.getline()) {
  5933. if (resp) { *resp += line_reader.ptr(); }
  5934. }
  5935. return true;
  5936. });
  5937. detail::close_socket(client_sock);
  5938. return ret;
  5939. }
  5940. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5941. Server svr;
  5942. std::string header_value;
  5943. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5944. header_value = req.get_header_value("foo");
  5945. res.set_content("ok", "text/plain");
  5946. });
  5947. thread t = thread([&] { svr.listen(HOST, PORT); });
  5948. auto se = detail::scope_exit([&] {
  5949. svr.stop();
  5950. t.join();
  5951. ASSERT_FALSE(svr.is_running());
  5952. });
  5953. svr.wait_until_ready();
  5954. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5955. // like characters are not treated the same - use vertical tab and escape.
  5956. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5957. "foo: \t \v bar \x1B\t \r\n"
  5958. "Connection: close\r\n"
  5959. "\r\n";
  5960. std::string res;
  5961. ASSERT_TRUE(send_request(5, req, &res));
  5962. EXPECT_EQ(header_value, "");
  5963. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5964. }
  5965. // Sends a raw request and verifies that there isn't a crash or exception.
  5966. static void test_raw_request(const std::string &req,
  5967. std::string *out = nullptr) {
  5968. Server svr;
  5969. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5970. res.set_content("ok", "text/plain");
  5971. });
  5972. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5973. res.set_content("ok", "text/plain");
  5974. });
  5975. svr.Get("/header_field_value_check",
  5976. [&](const Request & /*req*/, Response &res) {
  5977. res.set_content("ok", "text/plain");
  5978. });
  5979. // Server read timeout must be longer than the client read timeout for the
  5980. // bug to reproduce, probably to force the server to process a request
  5981. // without a trailing blank line.
  5982. const time_t client_read_timeout_sec = 1;
  5983. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5984. bool listen_thread_ok = false;
  5985. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5986. auto se = detail::scope_exit([&] {
  5987. svr.stop();
  5988. t.join();
  5989. ASSERT_FALSE(svr.is_running());
  5990. EXPECT_TRUE(listen_thread_ok);
  5991. });
  5992. svr.wait_until_ready();
  5993. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5994. }
  5995. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5996. // A certain header line causes an exception if the header property is parsed
  5997. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5998. test_raw_request(
  5999. "GET /hi HTTP/1.1\r\n"
  6000. " : "
  6001. " "
  6002. " ");
  6003. }
  6004. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6005. // A certain header line causes an exception if the header property *name* is
  6006. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6007. // greedy matcher and requires backtracking when there are a lot of ":"
  6008. // characters.
  6009. // This occurs with libc++ but not libstdc++.
  6010. test_raw_request(
  6011. "GET /hi HTTP/1.1\r\n"
  6012. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6013. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6014. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6015. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6016. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6017. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6018. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6019. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6020. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6021. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6022. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6023. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6024. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6025. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6026. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6027. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6028. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6029. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6030. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6031. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6032. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6033. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6034. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6035. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6036. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6037. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6038. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6039. "&&&%%%");
  6040. }
  6041. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6042. // Make sure this doesn't crash the server.
  6043. // In a previous version of the header line regex, the "\r" rendered the line
  6044. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6045. // a new position where the leading white space ended and the field value
  6046. // began.
  6047. // The crash occurs with libc++ but not libstdc++.
  6048. test_raw_request("GET /hi HTTP/1.1\r\n"
  6049. "a:" +
  6050. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6051. "\r\n"
  6052. "\r\n");
  6053. }
  6054. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6055. std::string out;
  6056. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6057. "Content-Type: text/plain\r\n"
  6058. "Transfer-Encoding: chunked\r\n"
  6059. "\r\n"
  6060. "nothex\r\n",
  6061. &out);
  6062. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6063. }
  6064. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6065. std::string out;
  6066. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6067. "Content-Type: text/plain\r\n"
  6068. "Transfer-Encoding: chunked\r\n"
  6069. "\r\n"
  6070. "3\r\n"
  6071. "xyz\r\n"
  6072. "NaN\r\n",
  6073. &out);
  6074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6075. }
  6076. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6077. std::string out;
  6078. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6079. "Content-Type: text/plain\r\n"
  6080. "Transfer-Encoding: chunked\r\n"
  6081. "\r\n"
  6082. // Length is too large for 64 bits.
  6083. "1ffffffffffffffff\r\n"
  6084. "xyz\r\n",
  6085. &out);
  6086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6087. }
  6088. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6089. test_raw_request("GET /hi HTTP/1.1\r\n"
  6090. "Content-Type: text/plain\r\n\r");
  6091. }
  6092. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6093. std::string out;
  6094. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6095. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6096. }
  6097. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6098. Server svr;
  6099. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6100. EXPECT_TRUE(!req.remote_addr.empty());
  6101. });
  6102. thread t = thread([&] { svr.listen(HOST, PORT); });
  6103. auto se = detail::scope_exit([&] {
  6104. svr.stop();
  6105. t.join();
  6106. ASSERT_FALSE(svr.is_running());
  6107. });
  6108. svr.wait_until_ready();
  6109. // Send an invalid request line to trigger Bad Request
  6110. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6111. std::string out;
  6112. ASSERT_TRUE(send_request(5, bad_req, &out));
  6113. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6114. }
  6115. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6116. std::string out;
  6117. std::string request(
  6118. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6119. test_raw_request(request, &out);
  6120. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6121. }
  6122. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6123. std::string out;
  6124. std::string request(
  6125. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6126. test_raw_request(request, &out);
  6127. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6128. }
  6129. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6130. std::string out;
  6131. std::string request(
  6132. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6133. test_raw_request(request, &out);
  6134. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6135. }
  6136. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6137. std::string out;
  6138. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6139. "Test: \r\n\r\n",
  6140. &out);
  6141. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6142. }
  6143. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6144. Server svr;
  6145. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6146. res.set_header("Cache-Control", "no-cache");
  6147. res.set_chunked_content_provider(
  6148. "text/event-stream", [](size_t offset, DataSink &sink) {
  6149. std::string s = "data:";
  6150. s += std::to_string(offset);
  6151. s += "\n\n";
  6152. auto ret = sink.write(s.data(), s.size());
  6153. EXPECT_TRUE(ret);
  6154. std::this_thread::sleep_for(std::chrono::seconds(1));
  6155. return true;
  6156. });
  6157. });
  6158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6159. svr.wait_until_ready();
  6160. Client client(HOST, PORT);
  6161. const Headers headers = {{"Accept", "text/event-stream"}};
  6162. auto get_thread = std::thread([&client, &headers]() {
  6163. auto res = client.Get(
  6164. "/events", headers,
  6165. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6166. });
  6167. auto se = detail::scope_exit([&] {
  6168. svr.stop();
  6169. get_thread.join();
  6170. listen_thread.join();
  6171. ASSERT_FALSE(svr.is_running());
  6172. });
  6173. // Give GET time to get a few messages.
  6174. std::this_thread::sleep_for(std::chrono::seconds(2));
  6175. }
  6176. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6177. httplib::Server svr;
  6178. svr.Post("/hi",
  6179. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6180. res.status = StatusCode::OK_200;
  6181. });
  6182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6183. svr.wait_until_ready();
  6184. Client cli(HOST, PORT);
  6185. auto res = cli.Post("/hi", "data", "text/plain");
  6186. ASSERT_TRUE(res);
  6187. EXPECT_EQ(StatusCode::OK_200, res->status);
  6188. svr.stop();
  6189. thread.join();
  6190. ASSERT_FALSE(svr.is_running());
  6191. res = cli.Post("/hi", "data", "text/plain");
  6192. ASSERT_FALSE(res);
  6193. }
  6194. TEST(ServerStopTest, ListenFailure) {
  6195. Server svr;
  6196. auto t = thread([&]() {
  6197. auto ret = svr.listen("????", PORT);
  6198. EXPECT_FALSE(ret);
  6199. });
  6200. svr.wait_until_ready();
  6201. svr.stop();
  6202. t.join();
  6203. }
  6204. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6205. TEST(ServerStopTest, Decommision) {
  6206. Server svr;
  6207. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6208. for (int i = 0; i < 4; i++) {
  6209. auto is_even = !(i % 2);
  6210. std::thread t{[&] {
  6211. try {
  6212. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6213. if (is_even) {
  6214. throw std::runtime_error("Some thing that happens to go wrong.");
  6215. }
  6216. svr.listen(HOST, PORT);
  6217. } catch (...) { svr.decommission(); }
  6218. }};
  6219. svr.wait_until_ready();
  6220. // Server is up
  6221. {
  6222. Client cli(HOST, PORT);
  6223. auto res = cli.Get("/hi");
  6224. if (is_even) {
  6225. EXPECT_FALSE(res);
  6226. } else {
  6227. EXPECT_TRUE(res);
  6228. EXPECT_EQ("hi...", res->body);
  6229. }
  6230. }
  6231. svr.stop();
  6232. t.join();
  6233. // Server is down...
  6234. {
  6235. Client cli(HOST, PORT);
  6236. auto res = cli.Get("/hi");
  6237. EXPECT_FALSE(res);
  6238. }
  6239. }
  6240. }
  6241. #endif
  6242. // Helper function for string body upload progress tests
  6243. template <typename SetupHandler, typename ClientCall>
  6244. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6245. ClientCall &&client_call,
  6246. const string &body) {
  6247. Server svr;
  6248. setup_handler(svr);
  6249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6250. auto se = detail::scope_exit([&] {
  6251. svr.stop();
  6252. t.join();
  6253. });
  6254. svr.wait_until_ready();
  6255. Client cli(HOST, PORT);
  6256. vector<uint64_t> progress_values;
  6257. bool progress_called = false;
  6258. auto res =
  6259. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6260. progress_values.push_back(current);
  6261. progress_called = true;
  6262. return true;
  6263. });
  6264. ASSERT_TRUE(res);
  6265. EXPECT_EQ(200, res->status);
  6266. EXPECT_TRUE(progress_called);
  6267. }
  6268. TEST(UploadProgressTest, PostStringBodyBasic) {
  6269. TestStringBodyUploadProgress(
  6270. [](Server &svr) {
  6271. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6272. res.set_content("received", "text/plain");
  6273. });
  6274. },
  6275. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6276. return cli.Post("/test", body, "text/plain", progress_callback);
  6277. },
  6278. "test data for upload progress");
  6279. }
  6280. TEST(UploadProgressTest, PutStringBodyBasic) {
  6281. TestStringBodyUploadProgress(
  6282. [](Server &svr) {
  6283. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6284. res.set_content("put received", "text/plain");
  6285. });
  6286. },
  6287. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6288. return cli.Put("/test", body, "text/plain", progress_callback);
  6289. },
  6290. "put test data for upload progress");
  6291. }
  6292. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6293. TestStringBodyUploadProgress(
  6294. [](Server &svr) {
  6295. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6296. res.set_content("patch received", "text/plain");
  6297. });
  6298. },
  6299. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6300. return cli.Patch("/test", body, "text/plain", progress_callback);
  6301. },
  6302. "patch test data for upload progress");
  6303. }
  6304. // Helper function for content provider upload progress tests
  6305. template <typename SetupHandler, typename ClientCall>
  6306. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6307. ClientCall &&client_call) {
  6308. Server svr;
  6309. setup_handler(svr);
  6310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6311. auto se = detail::scope_exit([&] {
  6312. svr.stop();
  6313. t.join();
  6314. });
  6315. svr.wait_until_ready();
  6316. Client cli(HOST, PORT);
  6317. vector<uint64_t> progress_values;
  6318. auto res =
  6319. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6320. progress_values.push_back(current);
  6321. return true;
  6322. });
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(200, res->status);
  6325. EXPECT_FALSE(progress_values.empty());
  6326. }
  6327. TEST(UploadProgressTest, PostContentProviderProgress) {
  6328. TestContentProviderUploadProgress(
  6329. [](Server &svr) {
  6330. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6331. res.set_content("provider received", "text/plain");
  6332. });
  6333. },
  6334. [](Client &cli, UploadProgress progress_callback) {
  6335. return cli.Post(
  6336. "/test", 10,
  6337. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6338. sink.os << "test data";
  6339. return true;
  6340. },
  6341. "text/plain", progress_callback);
  6342. });
  6343. }
  6344. // Helper function for multipart upload progress tests
  6345. template <typename SetupHandler, typename ClientCall>
  6346. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6347. ClientCall &&client_call,
  6348. const string &endpoint) {
  6349. Server svr;
  6350. setup_handler(svr);
  6351. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6352. auto se = detail::scope_exit([&] {
  6353. svr.stop();
  6354. t.join();
  6355. });
  6356. svr.wait_until_ready();
  6357. Client cli(HOST, PORT);
  6358. vector<uint64_t> progress_values;
  6359. UploadFormDataItems items = {
  6360. {"field1", "value1", "", ""},
  6361. {"field2", "longer value for progress tracking test", "", ""},
  6362. {"file1", "file content data for upload progress", "test.txt",
  6363. "text/plain"}};
  6364. auto res = client_call(cli, endpoint, items,
  6365. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6366. progress_values.push_back(current);
  6367. return true;
  6368. });
  6369. ASSERT_TRUE(res);
  6370. EXPECT_EQ(200, res->status);
  6371. EXPECT_FALSE(progress_values.empty());
  6372. }
  6373. TEST(UploadProgressTest, PostMultipartProgress) {
  6374. TestMultipartUploadProgress(
  6375. [](Server &svr) {
  6376. svr.Post("/multipart", [](const Request &req, Response &res) {
  6377. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6378. res.set_content("multipart received", "text/plain");
  6379. });
  6380. },
  6381. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6382. UploadProgress progress_callback) {
  6383. return cli.Post(endpoint, items, progress_callback);
  6384. },
  6385. "/multipart");
  6386. }
  6387. // Helper function for basic download progress tests
  6388. template <typename SetupHandler, typename ClientCall>
  6389. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6390. ClientCall &&client_call, const string &endpoint,
  6391. size_t expected_content_size) {
  6392. Server svr;
  6393. setup_handler(svr);
  6394. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6395. auto se = detail::scope_exit([&] {
  6396. svr.stop();
  6397. t.join();
  6398. });
  6399. svr.wait_until_ready();
  6400. Client cli(HOST, PORT);
  6401. vector<uint64_t> progress_values;
  6402. auto res = client_call(cli, endpoint,
  6403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6404. progress_values.push_back(current);
  6405. return true;
  6406. });
  6407. ASSERT_TRUE(res);
  6408. EXPECT_EQ(200, res->status);
  6409. EXPECT_FALSE(progress_values.empty());
  6410. EXPECT_EQ(expected_content_size, res->body.size());
  6411. }
  6412. TEST(DownloadProgressTest, GetBasic) {
  6413. TestBasicDownloadProgress(
  6414. [](Server &svr) {
  6415. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6416. string content(1000, 'D');
  6417. res.set_content(content, "text/plain");
  6418. });
  6419. },
  6420. [](Client &cli, const string &endpoint,
  6421. DownloadProgress progress_callback) {
  6422. return cli.Get(endpoint, progress_callback);
  6423. },
  6424. "/download", 1000u);
  6425. }
  6426. // Helper function for content receiver download progress tests
  6427. template <typename SetupHandler, typename ClientCall>
  6428. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6429. ClientCall &&client_call,
  6430. const string &endpoint,
  6431. size_t expected_content_size) {
  6432. Server svr;
  6433. setup_handler(svr);
  6434. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6435. auto se = detail::scope_exit([&] {
  6436. svr.stop();
  6437. t.join();
  6438. });
  6439. svr.wait_until_ready();
  6440. Client cli(HOST, PORT);
  6441. vector<uint64_t> progress_values;
  6442. string received_body;
  6443. auto res = client_call(
  6444. cli, endpoint,
  6445. [&](const char *data, size_t data_length) -> bool {
  6446. received_body.append(data, data_length);
  6447. return true;
  6448. },
  6449. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6450. progress_values.push_back(current);
  6451. return true;
  6452. });
  6453. ASSERT_TRUE(res);
  6454. EXPECT_EQ(200, res->status);
  6455. EXPECT_FALSE(progress_values.empty());
  6456. EXPECT_EQ(expected_content_size, received_body.size());
  6457. EXPECT_TRUE(res->body.empty());
  6458. }
  6459. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6460. TestContentReceiverDownloadProgress(
  6461. [](Server &svr) {
  6462. svr.Get("/download-receiver",
  6463. [](const Request & /*req*/, Response &res) {
  6464. string content(2000, 'R');
  6465. res.set_content(content, "text/plain");
  6466. });
  6467. },
  6468. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6469. DownloadProgress progress_callback) {
  6470. return cli.Get(endpoint, content_receiver, progress_callback);
  6471. },
  6472. "/download-receiver", 2000u);
  6473. }
  6474. TEST(StreamingTest, NoContentLengthStreaming) {
  6475. Server svr;
  6476. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6477. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6478. if (offset < 6) {
  6479. sink.os << (offset < 3 ? "a" : "b");
  6480. } else {
  6481. sink.done();
  6482. }
  6483. return true;
  6484. });
  6485. });
  6486. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6487. auto listen_se = detail::scope_exit([&] {
  6488. svr.stop();
  6489. listen_thread.join();
  6490. ASSERT_FALSE(svr.is_running());
  6491. });
  6492. svr.wait_until_ready();
  6493. Client client(HOST, PORT);
  6494. auto get_thread = std::thread([&client]() {
  6495. std::string s;
  6496. auto res =
  6497. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6498. s += std::string(data, len);
  6499. return true;
  6500. });
  6501. ASSERT_TRUE(res);
  6502. EXPECT_EQ(StatusCode::OK_200, res->status);
  6503. EXPECT_EQ("aaabbb", s);
  6504. });
  6505. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6506. // Give GET time to get a few messages.
  6507. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6508. }
  6509. TEST(MountTest, Unmount) {
  6510. Server svr;
  6511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6512. auto se = detail::scope_exit([&] {
  6513. svr.stop();
  6514. listen_thread.join();
  6515. ASSERT_FALSE(svr.is_running());
  6516. });
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. svr.set_mount_point("/mount2", "./www2");
  6520. auto res = cli.Get("/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. res = cli.Get("/mount2/dir/test.html");
  6524. ASSERT_TRUE(res);
  6525. EXPECT_EQ(StatusCode::OK_200, res->status);
  6526. svr.set_mount_point("/", "./www");
  6527. res = cli.Get("/dir/");
  6528. ASSERT_TRUE(res);
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. svr.remove_mount_point("/");
  6531. res = cli.Get("/dir/");
  6532. ASSERT_TRUE(res);
  6533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6534. svr.remove_mount_point("/mount2");
  6535. res = cli.Get("/mount2/dir/test.html");
  6536. ASSERT_TRUE(res);
  6537. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6538. }
  6539. TEST(MountTest, Redicect) {
  6540. Server svr;
  6541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.set_mount_point("/", "./www");
  6548. svr.wait_until_ready();
  6549. Client cli("localhost", PORT);
  6550. auto res = cli.Get("/dir/");
  6551. ASSERT_TRUE(res);
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. res = cli.Get("/dir");
  6554. ASSERT_TRUE(res);
  6555. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6556. res = cli.Get("/file");
  6557. ASSERT_TRUE(res);
  6558. EXPECT_EQ(StatusCode::OK_200, res->status);
  6559. res = cli.Get("/file/");
  6560. ASSERT_TRUE(res);
  6561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6562. cli.set_follow_location(true);
  6563. res = cli.Get("/dir");
  6564. ASSERT_TRUE(res);
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. }
  6567. TEST(MountTest, MultibytesPathName) {
  6568. Server svr;
  6569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. listen_thread.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.set_mount_point("/", "./www");
  6576. svr.wait_until_ready();
  6577. Client cli("localhost", PORT);
  6578. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6579. ASSERT_TRUE(res);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6582. }
  6583. TEST(KeepAliveTest, ReadTimeout) {
  6584. Server svr;
  6585. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6586. std::this_thread::sleep_for(std::chrono::seconds(2));
  6587. res.set_content("a", "text/plain");
  6588. });
  6589. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6590. res.set_content("b", "text/plain");
  6591. });
  6592. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6593. auto se = detail::scope_exit([&] {
  6594. svr.stop();
  6595. listen_thread.join();
  6596. ASSERT_FALSE(svr.is_running());
  6597. });
  6598. svr.wait_until_ready();
  6599. Client cli("localhost", PORT);
  6600. cli.set_keep_alive(true);
  6601. cli.set_read_timeout(std::chrono::seconds(1));
  6602. auto resa = cli.Get("/a");
  6603. ASSERT_FALSE(resa);
  6604. EXPECT_EQ(Error::Read, resa.error());
  6605. auto resb = cli.Get("/b");
  6606. ASSERT_TRUE(resb);
  6607. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6608. EXPECT_EQ("b", resb->body);
  6609. }
  6610. TEST(KeepAliveTest, MaxCount) {
  6611. size_t keep_alive_max_count = 3;
  6612. Server svr;
  6613. svr.set_keep_alive_max_count(keep_alive_max_count);
  6614. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6615. res.set_content("Hello World!", "text/plain");
  6616. });
  6617. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6618. auto 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 cli(HOST, PORT);
  6625. cli.set_keep_alive(true);
  6626. for (size_t i = 0; i < 5; i++) {
  6627. auto result = cli.Get("/hi");
  6628. ASSERT_TRUE(result);
  6629. EXPECT_EQ(StatusCode::OK_200, result->status);
  6630. if (i == keep_alive_max_count - 1) {
  6631. EXPECT_EQ("close", result->get_header_value("Connection"));
  6632. } else {
  6633. EXPECT_FALSE(result->has_header("Connection"));
  6634. }
  6635. }
  6636. }
  6637. TEST(KeepAliveTest, Issue1041) {
  6638. Server svr;
  6639. svr.set_keep_alive_timeout(3);
  6640. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6641. res.set_content("Hello World!", "text/plain");
  6642. });
  6643. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6644. auto se = detail::scope_exit([&] {
  6645. svr.stop();
  6646. listen_thread.join();
  6647. ASSERT_FALSE(svr.is_running());
  6648. });
  6649. svr.wait_until_ready();
  6650. Client cli(HOST, PORT);
  6651. cli.set_keep_alive(true);
  6652. auto result = cli.Get("/hi");
  6653. ASSERT_TRUE(result);
  6654. EXPECT_EQ(StatusCode::OK_200, result->status);
  6655. std::this_thread::sleep_for(std::chrono::seconds(5));
  6656. result = cli.Get("/hi");
  6657. ASSERT_TRUE(result);
  6658. EXPECT_EQ(StatusCode::OK_200, result->status);
  6659. }
  6660. TEST(KeepAliveTest, Issue1959) {
  6661. Server svr;
  6662. svr.set_keep_alive_timeout(5);
  6663. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6664. res.set_content("a", "text/plain");
  6665. });
  6666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6667. auto se = detail::scope_exit([&] {
  6668. if (!svr.is_running()) return;
  6669. svr.stop();
  6670. listen_thread.join();
  6671. ASSERT_FALSE(svr.is_running());
  6672. });
  6673. svr.wait_until_ready();
  6674. Client cli("localhost", PORT);
  6675. cli.set_keep_alive(true);
  6676. using namespace std::chrono;
  6677. auto start = steady_clock::now();
  6678. cli.Get("/a");
  6679. svr.stop();
  6680. listen_thread.join();
  6681. auto end = steady_clock::now();
  6682. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6683. EXPECT_LT(elapsed, 5000);
  6684. }
  6685. #ifdef CPPHTTPLIB_SSL_ENABLED
  6686. TEST(KeepAliveTest, SSLClientReconnection) {
  6687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6688. ASSERT_TRUE(svr.is_valid());
  6689. svr.set_keep_alive_timeout(1);
  6690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6691. res.set_content("Hello World!", "text/plain");
  6692. });
  6693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6694. auto se = detail::scope_exit([&] {
  6695. svr.stop();
  6696. listen_thread.join();
  6697. ASSERT_FALSE(svr.is_running());
  6698. });
  6699. svr.wait_until_ready();
  6700. SSLClient cli(HOST, PORT);
  6701. cli.enable_server_certificate_verification(false);
  6702. cli.set_keep_alive(true);
  6703. auto result = cli.Get("/hi");
  6704. ASSERT_TRUE(result);
  6705. EXPECT_EQ(StatusCode::OK_200, result->status);
  6706. result = cli.Get("/hi");
  6707. ASSERT_TRUE(result);
  6708. EXPECT_EQ(StatusCode::OK_200, result->status);
  6709. std::this_thread::sleep_for(std::chrono::seconds(2));
  6710. // Recoonect
  6711. result = cli.Get("/hi");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(StatusCode::OK_200, result->status);
  6714. result = cli.Get("/hi");
  6715. ASSERT_TRUE(result);
  6716. EXPECT_EQ(StatusCode::OK_200, result->status);
  6717. }
  6718. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6720. ASSERT_TRUE(svr.is_valid());
  6721. svr.set_keep_alive_timeout(1);
  6722. std::string content = "reconnect";
  6723. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6724. res.set_content("Hello World!", "text/plain");
  6725. });
  6726. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6727. auto se = detail::scope_exit([&] {
  6728. svr.stop();
  6729. listen_thread.join();
  6730. ASSERT_FALSE(svr.is_running());
  6731. });
  6732. svr.wait_until_ready();
  6733. SSLClient cli(HOST, PORT);
  6734. cli.enable_server_certificate_verification(false);
  6735. cli.set_keep_alive(true);
  6736. auto result = cli.Post(
  6737. "/hi", content.size(),
  6738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6739. sink.write(content.c_str(), content.size());
  6740. return true;
  6741. },
  6742. "text/plain");
  6743. ASSERT_TRUE(result);
  6744. EXPECT_EQ(200, result->status);
  6745. std::this_thread::sleep_for(std::chrono::seconds(2));
  6746. // Recoonect
  6747. result = cli.Post(
  6748. "/hi", content.size(),
  6749. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6750. sink.write(content.c_str(), content.size());
  6751. return true;
  6752. },
  6753. "text/plain");
  6754. ASSERT_TRUE(result);
  6755. EXPECT_EQ(200, result->status);
  6756. result = cli.Post(
  6757. "/hi", content.size(),
  6758. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6759. sink.write(content.c_str(), content.size());
  6760. return true;
  6761. },
  6762. "text/plain");
  6763. ASSERT_TRUE(result);
  6764. EXPECT_EQ(200, result->status);
  6765. }
  6766. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6767. using namespace httplib::tls;
  6768. {
  6769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6770. ASSERT_TRUE(svr.is_valid());
  6771. svr.Get("/sni", [&](const Request &req, Response &res) {
  6772. std::string expected = req.sni();
  6773. EXPECT_EQ(expected, req.get_param_value("expected"));
  6774. res.set_content("ok", "text/plain");
  6775. });
  6776. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6777. auto se = detail::scope_exit([&] {
  6778. svr.stop();
  6779. listen_thread.join();
  6780. ASSERT_FALSE(svr.is_running());
  6781. });
  6782. svr.wait_until_ready();
  6783. {
  6784. SSLClient cli("localhost", PORT);
  6785. cli.enable_server_certificate_verification(false);
  6786. auto res = cli.Get("/sni?expected=localhost");
  6787. ASSERT_TRUE(res);
  6788. }
  6789. {
  6790. SSLClient cli("::1", PORT);
  6791. cli.enable_server_certificate_verification(false);
  6792. auto res = cli.Get("/sni?expected=");
  6793. // NOTE: This may fail if the server is listening on IPv4 only
  6794. // (e.g., when localhost resolves to 127.0.0.1 only)
  6795. if (res) {
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. } else {
  6798. EXPECT_EQ(Error::Connection, res.error());
  6799. }
  6800. }
  6801. }
  6802. }
  6803. #endif
  6804. TEST(ClientProblemDetectionTest, ContentProvider) {
  6805. Server svr;
  6806. size_t content_length = 1024 * 1024;
  6807. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content_provider(
  6809. content_length, "text/plain",
  6810. [&](size_t offset, size_t length, DataSink &sink) {
  6811. auto out_len = std::min(length, static_cast<size_t>(1024));
  6812. std::string out(out_len, '@');
  6813. sink.write(out.data(), out_len);
  6814. return offset < 4096;
  6815. },
  6816. [](bool success) { ASSERT_FALSE(success); });
  6817. });
  6818. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6819. res.set_content_provider(
  6820. 0, "text/plain",
  6821. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6822. EXPECT_TRUE(false);
  6823. return true;
  6824. },
  6825. [](bool success) { ASSERT_FALSE(success); });
  6826. });
  6827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6828. auto se = detail::scope_exit([&] {
  6829. svr.stop();
  6830. listen_thread.join();
  6831. ASSERT_FALSE(svr.is_running());
  6832. });
  6833. svr.wait_until_ready();
  6834. Client cli("localhost", PORT);
  6835. {
  6836. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6837. size_t /*data_length*/) { return false; });
  6838. ASSERT_FALSE(res);
  6839. }
  6840. {
  6841. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6842. size_t /*data_length*/) { return false; });
  6843. ASSERT_TRUE(res);
  6844. }
  6845. }
  6846. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6847. Server svr;
  6848. svr.set_error_handler([](Request const &, Response &res) -> void {
  6849. res.set_chunked_content_provider(
  6850. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6851. sink.os << "hello";
  6852. sink.os << "world";
  6853. sink.done();
  6854. return true;
  6855. });
  6856. });
  6857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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. Client cli("localhost", PORT);
  6865. auto res = cli.Get("/");
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6868. EXPECT_EQ("helloworld", res->body);
  6869. }
  6870. TEST(LongPollingTest, ClientCloseDetection) {
  6871. Server svr;
  6872. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6873. res.set_chunked_content_provider(
  6874. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6875. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6876. sink.os << "hello";
  6877. auto count = 10;
  6878. while (count > 0 && sink.is_writable()) {
  6879. this_thread::sleep_for(chrono::milliseconds(10));
  6880. count--;
  6881. }
  6882. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6883. return true;
  6884. });
  6885. });
  6886. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6887. auto se = detail::scope_exit([&] {
  6888. svr.stop();
  6889. listen_thread.join();
  6890. ASSERT_FALSE(svr.is_running());
  6891. });
  6892. svr.wait_until_ready();
  6893. Client cli("localhost", PORT);
  6894. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6895. EXPECT_EQ("hello", string(data, data_length));
  6896. return false; // close the socket immediately.
  6897. });
  6898. ASSERT_FALSE(res);
  6899. }
  6900. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6901. Server svr;
  6902. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6903. res.set_chunked_content_provider(
  6904. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6905. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6906. sink.os << "hello";
  6907. EXPECT_TRUE(sink.os.good());
  6908. // Wait for the client to close the connection
  6909. auto count = 10;
  6910. while (count > 0 && sink.is_writable()) {
  6911. this_thread::sleep_for(chrono::milliseconds(10));
  6912. count--;
  6913. }
  6914. // After client disconnect, write repeatedly until the socket
  6915. // write actually fails (small writes may be absorbed by the
  6916. // kernel buffer)
  6917. std::string chunk(1024, 'x');
  6918. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6919. sink.os << chunk;
  6920. }
  6921. EXPECT_TRUE(sink.os.fail());
  6922. return true;
  6923. });
  6924. });
  6925. auto port = svr.bind_to_any_port("localhost");
  6926. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6927. auto se = detail::scope_exit([&] {
  6928. svr.stop();
  6929. listen_thread.join();
  6930. ASSERT_FALSE(svr.is_running());
  6931. });
  6932. svr.wait_until_ready();
  6933. Client cli("localhost", port);
  6934. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6935. EXPECT_EQ("hello", string(data, data_length));
  6936. return false; // close the socket immediately.
  6937. });
  6938. ASSERT_FALSE(res);
  6939. }
  6940. TEST(GetWithParametersTest, GetWithParameters) {
  6941. Server svr;
  6942. svr.Get("/", [&](const Request &req, Response &) {
  6943. EXPECT_EQ("world", req.get_param_value("hello"));
  6944. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6945. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6946. });
  6947. svr.Get("/params", [&](const Request &req, Response &) {
  6948. EXPECT_EQ("world", req.get_param_value("hello"));
  6949. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6950. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6951. });
  6952. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6953. EXPECT_EQ("resource-id", req.matches[1]);
  6954. EXPECT_EQ("foo", req.get_param_value("param1"));
  6955. EXPECT_EQ("bar", req.get_param_value("param2"));
  6956. });
  6957. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6958. EXPECT_EQ("user-id", req.path_params.at("id"));
  6959. EXPECT_EQ("foo", req.get_param_value("param1"));
  6960. EXPECT_EQ("bar", req.get_param_value("param2"));
  6961. });
  6962. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6963. auto se = detail::scope_exit([&] {
  6964. svr.stop();
  6965. listen_thread.join();
  6966. ASSERT_FALSE(svr.is_running());
  6967. });
  6968. svr.wait_until_ready();
  6969. {
  6970. Client cli(HOST, PORT);
  6971. Params params;
  6972. params.emplace("hello", "world");
  6973. params.emplace("hello2", "world2");
  6974. params.emplace("hello3", "world3");
  6975. auto res = cli.Get("/", params, Headers{});
  6976. ASSERT_TRUE(res);
  6977. EXPECT_EQ(StatusCode::OK_200, res->status);
  6978. }
  6979. {
  6980. Client cli(HOST, PORT);
  6981. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6982. ASSERT_TRUE(res);
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. {
  6986. Client cli(HOST, PORT);
  6987. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6988. ASSERT_TRUE(res);
  6989. EXPECT_EQ(StatusCode::OK_200, res->status);
  6990. }
  6991. {
  6992. Client cli(HOST, PORT);
  6993. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6994. ASSERT_TRUE(res);
  6995. EXPECT_EQ(StatusCode::OK_200, res->status);
  6996. }
  6997. }
  6998. TEST(GetWithParametersTest, GetWithParameters2) {
  6999. Server svr;
  7000. svr.Get("/", [&](const Request &req, Response &res) {
  7001. auto text = req.get_param_value("hello");
  7002. res.set_content(text, "text/plain");
  7003. });
  7004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7005. auto se = detail::scope_exit([&] {
  7006. svr.stop();
  7007. listen_thread.join();
  7008. ASSERT_FALSE(svr.is_running());
  7009. });
  7010. svr.wait_until_ready();
  7011. Client cli("localhost", PORT);
  7012. Params params;
  7013. params.emplace("hello", "world");
  7014. std::string body;
  7015. auto res = cli.Get("/", params, Headers{},
  7016. [&](const char *data, size_t data_length) {
  7017. body.append(data, data_length);
  7018. return true;
  7019. });
  7020. ASSERT_TRUE(res);
  7021. EXPECT_EQ(StatusCode::OK_200, res->status);
  7022. EXPECT_EQ("world", body);
  7023. }
  7024. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7025. auto host = "httpbingo.org";
  7026. auto path = std::string{"/range/32"};
  7027. #ifdef CPPHTTPLIB_SSL_ENABLED
  7028. SSLClient cli(host);
  7029. #else
  7030. Client cli(host);
  7031. #endif
  7032. cli.set_default_headers({make_range_header({{1, 10}})});
  7033. cli.set_connection_timeout(5);
  7034. {
  7035. auto res = cli.Get(path);
  7036. ASSERT_TRUE(res);
  7037. EXPECT_EQ("bcdefghijk", res->body);
  7038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7039. }
  7040. {
  7041. auto res = cli.Get(path);
  7042. ASSERT_TRUE(res);
  7043. EXPECT_EQ("bcdefghijk", res->body);
  7044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7045. }
  7046. }
  7047. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7048. Server svr;
  7049. svr.set_default_headers({{"Hello", "World"}});
  7050. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7051. res.set_content("ok", "text/plain");
  7052. });
  7053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7054. auto se = detail::scope_exit([&] {
  7055. svr.stop();
  7056. listen_thread.join();
  7057. ASSERT_FALSE(svr.is_running());
  7058. });
  7059. svr.wait_until_ready();
  7060. Client cli("localhost", PORT);
  7061. auto res = cli.Get("/");
  7062. ASSERT_TRUE(res);
  7063. EXPECT_EQ(StatusCode::OK_200, res->status);
  7064. EXPECT_EQ("ok", res->body);
  7065. EXPECT_EQ("World", res->get_header_value("Hello"));
  7066. }
  7067. #ifdef CPPHTTPLIB_SSL_ENABLED
  7068. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7070. ASSERT_TRUE(svr.is_valid());
  7071. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7072. std::this_thread::sleep_for(std::chrono::seconds(2));
  7073. res.set_content("a", "text/plain");
  7074. });
  7075. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7076. res.set_content("b", "text/plain");
  7077. });
  7078. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7079. auto se = detail::scope_exit([&] {
  7080. svr.stop();
  7081. listen_thread.join();
  7082. ASSERT_FALSE(svr.is_running());
  7083. });
  7084. svr.wait_until_ready();
  7085. SSLClient cli("localhost", PORT);
  7086. cli.enable_server_certificate_verification(false);
  7087. cli.set_keep_alive(true);
  7088. cli.set_read_timeout(std::chrono::seconds(1));
  7089. auto resa = cli.Get("/a");
  7090. ASSERT_TRUE(!resa);
  7091. EXPECT_EQ(Error::Read, resa.error());
  7092. auto resb = cli.Get("/b");
  7093. ASSERT_TRUE(resb);
  7094. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7095. EXPECT_EQ("b", resb->body);
  7096. }
  7097. #endif
  7098. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7099. protected:
  7100. ServerTestWithAI_PASSIVE()
  7101. : cli_(HOST, PORT)
  7102. #ifdef CPPHTTPLIB_SSL_ENABLED
  7103. ,
  7104. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7105. #endif
  7106. {
  7107. #ifdef CPPHTTPLIB_SSL_ENABLED
  7108. cli_.enable_server_certificate_verification(false);
  7109. #endif
  7110. }
  7111. virtual void SetUp() {
  7112. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7113. res.set_content("Hello World!", "text/plain");
  7114. });
  7115. t_ = thread(
  7116. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7117. svr_.wait_until_ready();
  7118. }
  7119. virtual void TearDown() {
  7120. svr_.stop();
  7121. t_.join();
  7122. }
  7123. #ifdef CPPHTTPLIB_SSL_ENABLED
  7124. SSLClient cli_;
  7125. SSLServer svr_;
  7126. #else
  7127. Client cli_;
  7128. Server svr_;
  7129. #endif
  7130. thread t_;
  7131. };
  7132. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7133. auto res = cli_.Get("/hi");
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7137. EXPECT_EQ("Hello World!", res->body);
  7138. }
  7139. class ServerUpDownTest : public ::testing::Test {
  7140. protected:
  7141. ServerUpDownTest() : cli_(HOST, PORT) {}
  7142. virtual void SetUp() {
  7143. t_ = thread([&]() {
  7144. svr_.bind_to_any_port(HOST);
  7145. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7146. ASSERT_TRUE(svr_.listen_after_bind());
  7147. });
  7148. svr_.wait_until_ready();
  7149. }
  7150. virtual void TearDown() {
  7151. svr_.stop();
  7152. t_.join();
  7153. }
  7154. Client cli_;
  7155. Server svr_;
  7156. thread t_;
  7157. };
  7158. TEST_F(ServerUpDownTest, QuickStartStop) {
  7159. // Should not crash, especially when run with
  7160. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7161. }
  7162. class PayloadMaxLengthTest : public ::testing::Test {
  7163. protected:
  7164. PayloadMaxLengthTest()
  7165. : cli_(HOST, PORT)
  7166. #ifdef CPPHTTPLIB_SSL_ENABLED
  7167. ,
  7168. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7169. #endif
  7170. {
  7171. #ifdef CPPHTTPLIB_SSL_ENABLED
  7172. cli_.enable_server_certificate_verification(false);
  7173. #endif
  7174. }
  7175. virtual void SetUp() {
  7176. svr_.set_payload_max_length(8);
  7177. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7178. res.set_content("test", "text/plain");
  7179. });
  7180. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7181. svr_.wait_until_ready();
  7182. }
  7183. virtual void TearDown() {
  7184. svr_.stop();
  7185. t_.join();
  7186. }
  7187. #ifdef CPPHTTPLIB_SSL_ENABLED
  7188. SSLClient cli_;
  7189. SSLServer svr_;
  7190. #else
  7191. Client cli_;
  7192. Server svr_;
  7193. #endif
  7194. thread t_;
  7195. };
  7196. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7197. auto res = cli_.Post("/test", "123456789", "text/plain");
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7200. res = cli_.Post("/test", "12345678", "text/plain");
  7201. ASSERT_TRUE(res);
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. }
  7204. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7205. // Test chunked encoding with payload exceeding the 8-byte limit
  7206. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7207. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7208. ASSERT_TRUE(res);
  7209. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7210. }
  7211. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7212. // Test chunked encoding with payload within the 8-byte limit
  7213. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7214. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7215. ASSERT_TRUE(res);
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7219. // Test using send_request to send chunked data exceeding payload limit
  7220. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7221. "Host: " +
  7222. std::string(HOST) + ":" + std::to_string(PORT) +
  7223. "\r\n"
  7224. "Transfer-Encoding: chunked\r\n"
  7225. "Connection: close\r\n"
  7226. "\r\n"
  7227. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7228. "0123456789\r\n"
  7229. "0\r\n" // End chunk
  7230. "\r\n";
  7231. std::string response;
  7232. bool result = send_request(1, chunked_request, &response);
  7233. if (!result) {
  7234. // If send_request fails, it might be because the server closed the
  7235. // connection due to payload limit enforcement, which is acceptable
  7236. SUCCEED()
  7237. << "Server rejected oversized chunked request (connection closed)";
  7238. } else {
  7239. // If we got a response, check if it's an error response or connection was
  7240. // closed early Short response length indicates connection was closed due to
  7241. // payload limit
  7242. if (response.length() <= 10) {
  7243. SUCCEED() << "Server closed connection for oversized chunked request";
  7244. } else {
  7245. // Check for error status codes
  7246. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7247. response.find("Payload Too Large") != std::string::npos ||
  7248. response.find("400") != std::string::npos);
  7249. }
  7250. }
  7251. }
  7252. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7253. // Test request without Content-Length header exceeding payload limit
  7254. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7255. "Host: " +
  7256. std::string(HOST) + ":" +
  7257. std::to_string(PORT) +
  7258. "\r\n"
  7259. "Connection: close\r\n"
  7260. "\r\n";
  7261. // Add payload exceeding the 8-byte limit
  7262. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7263. request_without_content_length += large_payload;
  7264. std::string response;
  7265. bool result = send_request(1, request_without_content_length, &response);
  7266. if (!result) {
  7267. // If send_request fails, server likely closed connection due to payload
  7268. // limit
  7269. SUCCEED() << "Server rejected oversized request without Content-Length "
  7270. "(connection closed)";
  7271. } else {
  7272. // Check if server responded with error or closed connection early
  7273. if (response.length() <= 10) {
  7274. SUCCEED() << "Server closed connection for oversized request without "
  7275. "Content-Length";
  7276. } else {
  7277. // Check for error status codes
  7278. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7279. response.find("Payload Too Large") != std::string::npos ||
  7280. response.find("400") != std::string::npos);
  7281. }
  7282. }
  7283. }
  7284. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7285. // Test request without Content-Length header within payload limit
  7286. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7287. "Host: " +
  7288. std::string(HOST) + ":" +
  7289. std::to_string(PORT) +
  7290. "\r\n"
  7291. "Connection: close\r\n"
  7292. "\r\n";
  7293. // Add payload within the 8-byte limit
  7294. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7295. request_without_content_length += small_payload;
  7296. std::string response;
  7297. bool result = send_request(1, request_without_content_length, &response);
  7298. // For requests without Content-Length, the server may have different behavior
  7299. // The key is that it should not reject due to payload limit for small
  7300. // payloads
  7301. if (result) {
  7302. // Check for any HTTP response (success or error, but not connection closed)
  7303. if (response.length() > 10) {
  7304. SUCCEED()
  7305. << "Server processed request without Content-Length within limit";
  7306. } else {
  7307. // Short response might indicate connection closed, which is acceptable
  7308. SUCCEED() << "Server closed connection for request without "
  7309. "Content-Length (acceptable behavior)";
  7310. }
  7311. } else {
  7312. // Connection failure might be due to protocol requirements
  7313. SUCCEED() << "Connection issue with request without Content-Length "
  7314. "(environment-specific)";
  7315. }
  7316. }
  7317. class LargePayloadMaxLengthTest : public ::testing::Test {
  7318. protected:
  7319. LargePayloadMaxLengthTest()
  7320. : cli_(HOST, PORT)
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. ,
  7323. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7324. #endif
  7325. {
  7326. #ifdef CPPHTTPLIB_SSL_ENABLED
  7327. cli_.enable_server_certificate_verification(false);
  7328. #endif
  7329. }
  7330. virtual void SetUp() {
  7331. // Set 10MB payload limit
  7332. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7333. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7334. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7335. res.set_content("Large payload test", "text/plain");
  7336. });
  7337. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7338. svr_.wait_until_ready();
  7339. }
  7340. virtual void TearDown() {
  7341. svr_.stop();
  7342. t_.join();
  7343. }
  7344. #ifdef CPPHTTPLIB_SSL_ENABLED
  7345. SSLClient cli_;
  7346. SSLServer svr_;
  7347. #else
  7348. Client cli_;
  7349. Server svr_;
  7350. #endif
  7351. thread t_;
  7352. };
  7353. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7354. // Test chunked encoding with payload within 10MB limit
  7355. std::string medium_payload(5 * 1024 * 1024,
  7356. 'A'); // 5MB payload, within 10MB limit
  7357. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7358. ASSERT_TRUE(res);
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. }
  7361. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7362. // Test chunked encoding with payload exceeding 10MB limit
  7363. std::string large_payload(12 * 1024 * 1024,
  7364. 'B'); // 12MB payload, exceeds 10MB limit
  7365. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7366. // Server may either return 413 or close the connection
  7367. if (res) {
  7368. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7369. } else {
  7370. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7371. }
  7372. }
  7373. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7374. // Test request without Content-Length header within 10MB limit
  7375. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7376. "Host: " +
  7377. std::string(HOST) + ":" +
  7378. std::to_string(PORT) +
  7379. "\r\n"
  7380. "Connection: close\r\n"
  7381. "\r\n";
  7382. // Add 1MB payload (within 10MB limit)
  7383. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7384. request_without_content_length += medium_payload;
  7385. std::string response;
  7386. bool result = send_request(5, request_without_content_length, &response);
  7387. if (result) {
  7388. // Should get a proper HTTP response for payloads within limit
  7389. if (response.length() > 10) {
  7390. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7391. "10MB limit";
  7392. } else {
  7393. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7394. "Content-Length)";
  7395. }
  7396. } else {
  7397. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7398. }
  7399. }
  7400. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7401. // Test request without Content-Length header exceeding 10MB limit
  7402. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7403. "Host: " +
  7404. std::string(HOST) + ":" +
  7405. std::to_string(PORT) +
  7406. "\r\n"
  7407. "Connection: close\r\n"
  7408. "\r\n";
  7409. // Add 12MB payload (exceeds 10MB limit)
  7410. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7411. request_without_content_length += large_payload;
  7412. std::string response;
  7413. bool result = send_request(10, request_without_content_length, &response);
  7414. if (!result) {
  7415. // Server should close connection due to payload limit
  7416. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7417. "(connection closed)";
  7418. } else {
  7419. // Check for error response
  7420. if (response.length() <= 10) {
  7421. SUCCEED()
  7422. << "Server closed connection for 12MB request exceeding 10MB limit";
  7423. } else {
  7424. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7425. response.find("Payload Too Large") != std::string::npos ||
  7426. response.find("400") != std::string::npos);
  7427. }
  7428. }
  7429. }
  7430. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7431. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7432. // path.
  7433. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7434. Server svr;
  7435. const size_t LIMIT = 64 * 1024; // 64KB
  7436. svr.set_payload_max_length(LIMIT);
  7437. size_t total = 0;
  7438. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7439. const ContentReader &content_reader) {
  7440. content_reader([&](const char * /*data*/, size_t len) {
  7441. total += len;
  7442. return true;
  7443. });
  7444. res.status = 200;
  7445. res.set_content("stream_ok", "text/plain");
  7446. });
  7447. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7448. auto se = detail::scope_exit([&] {
  7449. svr.stop();
  7450. thread.join();
  7451. ASSERT_FALSE(svr.is_running());
  7452. });
  7453. svr.wait_until_ready();
  7454. // Prepare 256KB raw data and gzip-compress it
  7455. std::string raw(256 * 1024, 'A');
  7456. std::string gz;
  7457. {
  7458. z_stream zs{};
  7459. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7460. Z_DEFAULT_STRATEGY);
  7461. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7462. zs.avail_in = static_cast<uInt>(raw.size());
  7463. char outbuf[4096];
  7464. int ret;
  7465. do {
  7466. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7467. zs.avail_out = sizeof(outbuf);
  7468. ret = deflate(&zs, Z_FINISH);
  7469. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7470. } while (ret != Z_STREAM_END);
  7471. deflateEnd(&zs);
  7472. }
  7473. Client cli(HOST, PORT);
  7474. cli.set_connection_timeout(std::chrono::seconds(5));
  7475. Headers headers = {{"Content-Encoding", "gzip"}};
  7476. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7477. "application/octet-stream");
  7478. ASSERT_TRUE(res);
  7479. // Server must reject oversized decompressed payloads with 413.
  7480. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7481. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7482. EXPECT_LE(total, LIMIT);
  7483. }
  7484. #endif
  7485. // Regression test for DoS vulnerability: a malicious server sending a response
  7486. // without Content-Length header must not cause unbounded memory consumption on
  7487. // the client side. The client should stop reading after a reasonable limit,
  7488. // similar to the server-side set_payload_max_length protection.
  7489. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7490. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7491. #ifndef _WIN32
  7492. signal(SIGPIPE, SIG_IGN);
  7493. #endif
  7494. auto server_thread = std::thread([] {
  7495. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7496. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7497. default_socket_options(srv);
  7498. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7499. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7500. sockaddr_in addr{};
  7501. addr.sin_family = AF_INET;
  7502. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7504. int opt = 1;
  7505. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7506. #ifdef _WIN32
  7507. reinterpret_cast<const char *>(&opt),
  7508. #else
  7509. &opt,
  7510. #endif
  7511. sizeof(opt));
  7512. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7513. ::listen(srv, 1);
  7514. sockaddr_in cli_addr{};
  7515. socklen_t cli_len = sizeof(cli_addr);
  7516. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7517. if (cli != INVALID_SOCKET) {
  7518. char buf[4096];
  7519. ::recv(cli, buf, sizeof(buf), 0);
  7520. // Malicious response: no Content-Length, no chunked encoding
  7521. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7522. "Connection: close\r\n"
  7523. "\r\n";
  7524. ::send(cli,
  7525. #ifdef _WIN32
  7526. static_cast<const char *>(response_header.c_str()),
  7527. static_cast<int>(response_header.size()),
  7528. #else
  7529. response_header.c_str(), response_header.size(),
  7530. #endif
  7531. 0);
  7532. // Send 10MB of data
  7533. std::string chunk(64 * 1024, 'A');
  7534. size_t total_sent = 0;
  7535. while (total_sent < MALICIOUS_DATA_SIZE) {
  7536. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7537. auto sent = ::send(cli,
  7538. #ifdef _WIN32
  7539. static_cast<const char *>(chunk.c_str()),
  7540. static_cast<int>(to_send),
  7541. #else
  7542. chunk.c_str(), to_send,
  7543. #endif
  7544. 0);
  7545. if (sent <= 0) break;
  7546. total_sent += static_cast<size_t>(sent);
  7547. }
  7548. detail::close_socket(cli);
  7549. }
  7550. detail::close_socket(srv);
  7551. });
  7552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7553. size_t total_read = 0;
  7554. {
  7555. Client cli("127.0.0.1", PORT + 2);
  7556. cli.set_read_timeout(5, 0);
  7557. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7558. auto stream = cli.open_stream("GET", "/malicious");
  7559. ASSERT_TRUE(stream.is_valid());
  7560. char buffer[64 * 1024];
  7561. ssize_t n;
  7562. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7563. total_read += static_cast<size_t>(n);
  7564. }
  7565. } // StreamHandle and Client destroyed here, closing the socket
  7566. server_thread.join();
  7567. // With set_payload_max_length, the client must stop reading before consuming
  7568. // all 10MB. The read loop should be cut off at or near the configured limit.
  7569. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7570. << "Client read " << total_read << " bytes, exceeding the configured "
  7571. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7572. }
  7573. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7574. // the entire response body without truncation.
  7575. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7576. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7577. #ifndef _WIN32
  7578. signal(SIGPIPE, SIG_IGN);
  7579. #endif
  7580. auto server_thread = std::thread([] {
  7581. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7582. default_socket_options(srv);
  7583. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7584. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7585. sockaddr_in addr{};
  7586. addr.sin_family = AF_INET;
  7587. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7588. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7589. int opt = 1;
  7590. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7591. #ifdef _WIN32
  7592. reinterpret_cast<const char *>(&opt),
  7593. #else
  7594. &opt,
  7595. #endif
  7596. sizeof(opt));
  7597. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7598. ::listen(srv, 1);
  7599. sockaddr_in cli_addr{};
  7600. socklen_t cli_len = sizeof(cli_addr);
  7601. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7602. if (cli != INVALID_SOCKET) {
  7603. char buf[4096];
  7604. ::recv(cli, buf, sizeof(buf), 0);
  7605. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7606. "Connection: close\r\n"
  7607. "\r\n";
  7608. ::send(cli,
  7609. #ifdef _WIN32
  7610. static_cast<const char *>(response_header.c_str()),
  7611. static_cast<int>(response_header.size()),
  7612. #else
  7613. response_header.c_str(), response_header.size(),
  7614. #endif
  7615. 0);
  7616. std::string chunk(64 * 1024, 'A');
  7617. size_t total_sent = 0;
  7618. while (total_sent < DATA_SIZE) {
  7619. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7620. auto sent = ::send(cli,
  7621. #ifdef _WIN32
  7622. static_cast<const char *>(chunk.c_str()),
  7623. static_cast<int>(to_send),
  7624. #else
  7625. chunk.c_str(), to_send,
  7626. #endif
  7627. 0);
  7628. if (sent <= 0) break;
  7629. total_sent += static_cast<size_t>(sent);
  7630. }
  7631. #ifdef _WIN32
  7632. ::shutdown(cli, SD_SEND);
  7633. #else
  7634. ::shutdown(cli, SHUT_WR);
  7635. #endif
  7636. // Drain until the client closes its end, ensuring all data is delivered
  7637. char drain[1024];
  7638. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7639. detail::close_socket(cli);
  7640. }
  7641. detail::close_socket(srv);
  7642. });
  7643. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7644. size_t total_read = 0;
  7645. {
  7646. Client cli("127.0.0.1", PORT + 2);
  7647. cli.set_read_timeout(5, 0);
  7648. cli.set_payload_max_length(0); // 0 means no limit
  7649. auto stream = cli.open_stream("GET", "/data");
  7650. ASSERT_TRUE(stream.is_valid());
  7651. char buffer[64 * 1024];
  7652. ssize_t n;
  7653. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7654. total_read += static_cast<size_t>(n);
  7655. }
  7656. }
  7657. server_thread.join();
  7658. EXPECT_EQ(total_read, DATA_SIZE)
  7659. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7660. << " bytes without truncation, but only read " << total_read << " bytes.";
  7661. }
  7662. // Verify that content_receiver bypasses the default payload_max_length,
  7663. // allowing streaming downloads larger than 100MB without requiring an explicit
  7664. // set_payload_max_length call.
  7665. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7666. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7667. #ifndef _WIN32
  7668. signal(SIGPIPE, SIG_IGN);
  7669. #endif
  7670. auto server_thread = std::thread([] {
  7671. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7672. default_socket_options(srv);
  7673. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7674. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7675. sockaddr_in addr{};
  7676. addr.sin_family = AF_INET;
  7677. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7678. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7679. int opt = 1;
  7680. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7681. #ifdef _WIN32
  7682. reinterpret_cast<const char *>(&opt),
  7683. #else
  7684. &opt,
  7685. #endif
  7686. sizeof(opt));
  7687. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7688. ::listen(srv, 1);
  7689. sockaddr_in cli_addr{};
  7690. socklen_t cli_len = sizeof(cli_addr);
  7691. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7692. if (cli != INVALID_SOCKET) {
  7693. char buf[4096];
  7694. ::recv(cli, buf, sizeof(buf), 0);
  7695. // Response with Content-Length larger than default 100MB limit
  7696. auto content_length = std::to_string(DATA_SIZE);
  7697. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7698. "Content-Length: " +
  7699. content_length +
  7700. "\r\n"
  7701. "Connection: close\r\n"
  7702. "\r\n";
  7703. ::send(cli,
  7704. #ifdef _WIN32
  7705. static_cast<const char *>(response_header.c_str()),
  7706. static_cast<int>(response_header.size()),
  7707. #else
  7708. response_header.c_str(), response_header.size(),
  7709. #endif
  7710. 0);
  7711. std::string chunk(64 * 1024, 'A');
  7712. size_t total_sent = 0;
  7713. while (total_sent < DATA_SIZE) {
  7714. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7715. auto sent = ::send(cli,
  7716. #ifdef _WIN32
  7717. static_cast<const char *>(chunk.c_str()),
  7718. static_cast<int>(to_send),
  7719. #else
  7720. chunk.c_str(), to_send,
  7721. #endif
  7722. 0);
  7723. if (sent <= 0) break;
  7724. total_sent += static_cast<size_t>(sent);
  7725. }
  7726. detail::close_socket(cli);
  7727. }
  7728. detail::close_socket(srv);
  7729. });
  7730. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7731. size_t total_received = 0;
  7732. {
  7733. Client cli("127.0.0.1", PORT + 2);
  7734. cli.set_read_timeout(10, 0);
  7735. // Do NOT call set_payload_max_length — use the default 100MB limit
  7736. auto res =
  7737. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7738. total_received += data_length;
  7739. return true;
  7740. });
  7741. ASSERT_TRUE(res);
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. }
  7744. server_thread.join();
  7745. EXPECT_EQ(total_received, DATA_SIZE)
  7746. << "With content_receiver, the client should read all " << DATA_SIZE
  7747. << " bytes despite the default 100MB payload_max_length, but only read "
  7748. << total_received << " bytes.";
  7749. }
  7750. // Verify that an explicit set_payload_max_length smaller than the response is
  7751. // enforced even when a content_receiver is used.
  7752. TEST(ClientVulnerabilityTest,
  7753. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7754. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7755. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7756. #ifndef _WIN32
  7757. signal(SIGPIPE, SIG_IGN);
  7758. #endif
  7759. auto server_thread = std::thread([] {
  7760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7761. default_socket_options(srv);
  7762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7764. sockaddr_in addr{};
  7765. addr.sin_family = AF_INET;
  7766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7768. int opt = 1;
  7769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7770. #ifdef _WIN32
  7771. reinterpret_cast<const char *>(&opt),
  7772. #else
  7773. &opt,
  7774. #endif
  7775. sizeof(opt));
  7776. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7777. ::listen(srv, 1);
  7778. sockaddr_in cli_addr{};
  7779. socklen_t cli_len = sizeof(cli_addr);
  7780. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7781. if (cli != INVALID_SOCKET) {
  7782. char buf[4096];
  7783. ::recv(cli, buf, sizeof(buf), 0);
  7784. auto content_length = std::to_string(DATA_SIZE);
  7785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7786. "Content-Length: " +
  7787. content_length +
  7788. "\r\n"
  7789. "Connection: close\r\n"
  7790. "\r\n";
  7791. ::send(cli,
  7792. #ifdef _WIN32
  7793. static_cast<const char *>(response_header.c_str()),
  7794. static_cast<int>(response_header.size()),
  7795. #else
  7796. response_header.c_str(), response_header.size(),
  7797. #endif
  7798. 0);
  7799. std::string chunk(64 * 1024, 'A');
  7800. size_t total_sent = 0;
  7801. while (total_sent < DATA_SIZE) {
  7802. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7803. auto sent = ::send(cli,
  7804. #ifdef _WIN32
  7805. static_cast<const char *>(chunk.c_str()),
  7806. static_cast<int>(to_send),
  7807. #else
  7808. chunk.c_str(), to_send,
  7809. #endif
  7810. 0);
  7811. if (sent <= 0) break;
  7812. total_sent += static_cast<size_t>(sent);
  7813. }
  7814. detail::close_socket(cli);
  7815. }
  7816. detail::close_socket(srv);
  7817. });
  7818. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7819. size_t total_received = 0;
  7820. {
  7821. Client cli("127.0.0.1", PORT + 2);
  7822. cli.set_read_timeout(10, 0);
  7823. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7824. auto res =
  7825. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7826. total_received += data_length;
  7827. return true;
  7828. });
  7829. // Should fail because 200MB exceeds the explicit 150MB limit
  7830. EXPECT_FALSE(res);
  7831. }
  7832. server_thread.join();
  7833. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7834. << "Client with content_receiver should respect the explicit "
  7835. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7836. << total_received << " bytes.";
  7837. }
  7838. // Verify that an explicit set_payload_max_length larger than the response
  7839. // allows the content_receiver to read all data successfully.
  7840. TEST(ClientVulnerabilityTest,
  7841. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7842. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7843. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7844. #ifndef _WIN32
  7845. signal(SIGPIPE, SIG_IGN);
  7846. #endif
  7847. auto server_thread = std::thread([] {
  7848. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7849. default_socket_options(srv);
  7850. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7851. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7852. sockaddr_in addr{};
  7853. addr.sin_family = AF_INET;
  7854. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7856. int opt = 1;
  7857. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7858. #ifdef _WIN32
  7859. reinterpret_cast<const char *>(&opt),
  7860. #else
  7861. &opt,
  7862. #endif
  7863. sizeof(opt));
  7864. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7865. ::listen(srv, 1);
  7866. sockaddr_in cli_addr{};
  7867. socklen_t cli_len = sizeof(cli_addr);
  7868. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7869. if (cli != INVALID_SOCKET) {
  7870. char buf[4096];
  7871. ::recv(cli, buf, sizeof(buf), 0);
  7872. auto content_length = std::to_string(DATA_SIZE);
  7873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7874. "Content-Length: " +
  7875. content_length +
  7876. "\r\n"
  7877. "Connection: close\r\n"
  7878. "\r\n";
  7879. ::send(cli,
  7880. #ifdef _WIN32
  7881. static_cast<const char *>(response_header.c_str()),
  7882. static_cast<int>(response_header.size()),
  7883. #else
  7884. response_header.c_str(), response_header.size(),
  7885. #endif
  7886. 0);
  7887. std::string chunk(64 * 1024, 'A');
  7888. size_t total_sent = 0;
  7889. while (total_sent < DATA_SIZE) {
  7890. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7891. auto sent = ::send(cli,
  7892. #ifdef _WIN32
  7893. static_cast<const char *>(chunk.c_str()),
  7894. static_cast<int>(to_send),
  7895. #else
  7896. chunk.c_str(), to_send,
  7897. #endif
  7898. 0);
  7899. if (sent <= 0) break;
  7900. total_sent += static_cast<size_t>(sent);
  7901. }
  7902. #ifdef _WIN32
  7903. ::shutdown(cli, SD_SEND);
  7904. #else
  7905. ::shutdown(cli, SHUT_WR);
  7906. #endif
  7907. char drain[1024];
  7908. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7909. detail::close_socket(cli);
  7910. }
  7911. detail::close_socket(srv);
  7912. });
  7913. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7914. size_t total_received = 0;
  7915. {
  7916. Client cli("127.0.0.1", PORT + 2);
  7917. cli.set_read_timeout(10, 0);
  7918. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7919. auto res =
  7920. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7921. total_received += data_length;
  7922. return true;
  7923. });
  7924. ASSERT_TRUE(res);
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. }
  7927. server_thread.join();
  7928. EXPECT_EQ(total_received, DATA_SIZE)
  7929. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7930. << " bytes (larger than " << DATA_SIZE
  7931. << " bytes response), content_receiver should read all data, but only "
  7932. "read "
  7933. << total_received << " bytes.";
  7934. }
  7935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7936. // Regression test for "zip bomb" attack on the client side: a malicious server
  7937. // sends a small gzip-compressed response that decompresses to a huge payload.
  7938. // The client must enforce payload_max_length on the decompressed size.
  7939. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7940. constexpr size_t DECOMPRESSED_SIZE =
  7941. 10 * 1024 * 1024; // 10MB after decompression
  7942. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7943. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7944. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7945. std::string compressed;
  7946. {
  7947. httplib::detail::gzip_compressor compressor;
  7948. bool ok =
  7949. compressor.compress(uncompressed.data(), uncompressed.size(),
  7950. /*last=*/true, [&](const char *buf, size_t len) {
  7951. compressed.append(buf, len);
  7952. return true;
  7953. });
  7954. ASSERT_TRUE(ok);
  7955. }
  7956. // Sanity: compressed data should be much smaller than the decompressed size
  7957. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7958. #ifndef _WIN32
  7959. signal(SIGPIPE, SIG_IGN);
  7960. #endif
  7961. // Set up the listening socket in the main thread so the server is guaranteed
  7962. // to be ready before the client connects (eliminates race condition).
  7963. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7964. default_socket_options(srv);
  7965. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7966. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7967. sockaddr_in addr{};
  7968. addr.sin_family = AF_INET;
  7969. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7970. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7971. int opt = 1;
  7972. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7973. #ifdef _WIN32
  7974. reinterpret_cast<const char *>(&opt),
  7975. #else
  7976. &opt,
  7977. #endif
  7978. sizeof(opt));
  7979. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7980. ASSERT_EQ(0, ::listen(srv, 1));
  7981. auto server_thread = std::thread([&compressed, srv] {
  7982. sockaddr_in cli_addr{};
  7983. socklen_t cli_len = sizeof(cli_addr);
  7984. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7985. if (cli != INVALID_SOCKET) {
  7986. // Read the full HTTP request (until \r\n\r\n)
  7987. char buf[4096];
  7988. size_t total = 0;
  7989. while (total < sizeof(buf)) {
  7990. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7991. if (n <= 0) break;
  7992. total += static_cast<size_t>(n);
  7993. // Check for end of headers
  7994. if (total >= 4) {
  7995. std::string req(buf, total);
  7996. if (req.find("\r\n\r\n") != std::string::npos) break;
  7997. }
  7998. }
  7999. // Malicious response: gzip-compressed body, no Content-Length
  8000. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8001. "Content-Encoding: gzip\r\n"
  8002. "Connection: close\r\n"
  8003. "\r\n";
  8004. ::send(cli,
  8005. #ifdef _WIN32
  8006. static_cast<const char *>(response_header.c_str()),
  8007. static_cast<int>(response_header.size()),
  8008. #else
  8009. response_header.c_str(), response_header.size(),
  8010. #endif
  8011. 0);
  8012. // Send the compressed payload (small on the wire, huge when decompressed)
  8013. size_t total_sent = 0;
  8014. while (total_sent < compressed.size()) {
  8015. auto to_send = std::min(compressed.size() - total_sent,
  8016. static_cast<size_t>(64 * 1024));
  8017. auto sent =
  8018. ::send(cli,
  8019. #ifdef _WIN32
  8020. static_cast<const char *>(compressed.c_str() + total_sent),
  8021. static_cast<int>(to_send),
  8022. #else
  8023. compressed.c_str() + total_sent, to_send,
  8024. #endif
  8025. 0);
  8026. if (sent <= 0) break;
  8027. total_sent += static_cast<size_t>(sent);
  8028. }
  8029. detail::close_socket(cli);
  8030. }
  8031. });
  8032. auto se = detail::scope_exit([&] {
  8033. detail::close_socket(srv);
  8034. server_thread.join();
  8035. });
  8036. size_t total_decompressed = 0;
  8037. {
  8038. Client cli("127.0.0.1", PORT + 3);
  8039. cli.set_read_timeout(5, 0);
  8040. cli.set_decompress(true);
  8041. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8042. auto stream = cli.open_stream("GET", "/zipbomb");
  8043. ASSERT_TRUE(stream.is_valid());
  8044. char buffer[64 * 1024];
  8045. ssize_t n;
  8046. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8047. total_decompressed += static_cast<size_t>(n);
  8048. }
  8049. }
  8050. // The decompressed size must be capped by payload_max_length. Without
  8051. // protection, the client would decompress the full 10MB from a tiny
  8052. // compressed payload, enabling a zip bomb DoS attack.
  8053. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8054. << "Client decompressed " << total_decompressed
  8055. << " bytes from a gzip response. The decompressed size should be "
  8056. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8057. }
  8058. #endif
  8059. TEST(HostAndPortPropertiesTest, NoSSL) {
  8060. httplib::Client cli("www.google.com", 1234);
  8061. ASSERT_EQ("www.google.com", cli.host());
  8062. ASSERT_EQ(1234, cli.port());
  8063. }
  8064. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8065. httplib::Client cli("www.google.com:1234");
  8066. ASSERT_EQ("www.google.com", cli.host());
  8067. ASSERT_EQ(1234, cli.port());
  8068. }
  8069. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8070. // Port number that overflows int — should not crash, client becomes invalid
  8071. httplib::Client cli("http://www.google.com:99999999999999999999");
  8072. ASSERT_FALSE(cli.is_valid());
  8073. }
  8074. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8075. // Port 99999 exceeds valid range (1-65535) — should not crash
  8076. httplib::Client cli("http://www.google.com:99999");
  8077. ASSERT_FALSE(cli.is_valid());
  8078. }
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. TEST(HostAndPortPropertiesTest, SSL) {
  8081. httplib::SSLClient cli("www.google.com");
  8082. ASSERT_EQ("www.google.com", cli.host());
  8083. ASSERT_EQ(443, cli.port());
  8084. }
  8085. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8086. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8087. std::string cert;
  8088. read_file(CA_CERT_FILE, cert);
  8089. httplib::SSLClient httplib_client("www.google.com");
  8090. // Load CA store first time
  8091. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8092. // Load CA store second time (update)
  8093. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8094. // Verify client is still valid and can make connections
  8095. httplib_client.enable_server_certificate_verification(true);
  8096. auto res = httplib_client.Get("/");
  8097. ASSERT_TRUE(res);
  8098. // Google may return 200 or 301 depending on various factors
  8099. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8100. res->status == StatusCode::MovedPermanently_301);
  8101. }
  8102. TEST(SSLClientTest, ServerNameIndication_Online) {
  8103. auto host = "httpbingo.org";
  8104. auto path = std::string{"/get"};
  8105. SSLClient cli(host, 443);
  8106. auto res = cli.Get(path);
  8107. ASSERT_TRUE(res);
  8108. ASSERT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8111. // Use a site that will cause SSL verification failure due to self-signed cert
  8112. SSLClient cli("self-signed.badssl.com", 443);
  8113. cli.enable_server_certificate_verification(true);
  8114. auto res = cli.Get("/");
  8115. ASSERT_TRUE(!res);
  8116. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8117. // Verify backend error is captured for SSLServerVerification
  8118. // This occurs when certificate verification fails
  8119. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8120. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8121. EXPECT_NE(0UL, res.ssl_backend_error());
  8122. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8123. // For OpenSSL, ssl_error is 0 for verification errors
  8124. EXPECT_EQ(0, res.ssl_error());
  8125. #if !defined(_WIN32) || \
  8126. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8127. // On non-Windows or when Windows Schannel is disabled, the error comes
  8128. // from OpenSSL's verification
  8129. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8130. res.ssl_backend_error());
  8131. #endif
  8132. #endif
  8133. }
  8134. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8135. // Use a site where hostname doesn't match the certificate
  8136. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8137. SSLClient cli("wrong.host.badssl.com", 443);
  8138. cli.enable_server_certificate_verification(true);
  8139. cli.enable_server_hostname_verification(true);
  8140. auto res = cli.Get("/");
  8141. ASSERT_TRUE(!res);
  8142. // The error type depends on when hostname verification occurs:
  8143. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8144. // - Mbed TLS: SSLServerVerification (during handshake)
  8145. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8146. res.error() == Error::SSLServerVerification);
  8147. // Verify backend error is captured for hostname verification failure
  8148. EXPECT_NE(0UL, res.ssl_backend_error());
  8149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8150. // For OpenSSL, ssl_error is 0 for verification errors
  8151. EXPECT_EQ(0, res.ssl_error());
  8152. #if !defined(_WIN32) || \
  8153. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8154. // On non-Windows or when Windows Schannel is disabled, the error comes
  8155. // from OpenSSL's hostname verification
  8156. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8157. res.ssl_backend_error());
  8158. #endif
  8159. #endif
  8160. }
  8161. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8162. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8163. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8164. SSLClient cli("www.google.com", 443);
  8165. cli.enable_server_certificate_verification(true);
  8166. auto res = cli.Get("/");
  8167. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8168. }
  8169. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8170. SSLClient cli("www.google.com", 443);
  8171. cli.enable_server_certificate_verification(true);
  8172. cli.enable_windows_certificate_verification(false);
  8173. auto res = cli.Get("/");
  8174. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8175. }
  8176. #endif
  8177. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8178. Client cli("https://google.com");
  8179. auto res = cli.Get("/");
  8180. ASSERT_TRUE(res);
  8181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8182. }
  8183. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8184. SSLClient cli("google.com");
  8185. cli.set_ca_cert_path(CA_CERT_FILE);
  8186. auto res = cli.Get("/");
  8187. ASSERT_TRUE(res);
  8188. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8189. }
  8190. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8191. SSLClient cli("google.com");
  8192. cli.enable_server_certificate_verification(true);
  8193. cli.set_ca_cert_path("hello");
  8194. auto res = cli.Get("/");
  8195. ASSERT_TRUE(!res);
  8196. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8197. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8198. // should be set
  8199. EXPECT_EQ(0, res.ssl_error());
  8200. // Verify backend error is captured for SSLLoadingCerts
  8201. // This error occurs when loading CA certificates fails
  8202. EXPECT_NE(0UL, res.ssl_backend_error());
  8203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8204. // OpenSSL specific error codes:
  8205. // > openssl errstr 0x80000002
  8206. // error:80000002:system library::No such file or directory
  8207. // > openssl errstr 0xA000126
  8208. // error:0A000126:SSL routines::unexpected eof while reading
  8209. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8210. res.ssl_backend_error() == 0xA000126);
  8211. #endif
  8212. }
  8213. TEST(SSLClientTest, ServerCertificateVerification4) {
  8214. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8215. ASSERT_TRUE(svr.is_valid());
  8216. svr.Get("/test", [&](const Request &, Response &res) {
  8217. res.set_content("test", "text/plain");
  8218. svr.stop();
  8219. ASSERT_TRUE(true);
  8220. });
  8221. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8222. auto se = detail::scope_exit([&] {
  8223. t.join();
  8224. ASSERT_FALSE(svr.is_running());
  8225. });
  8226. svr.wait_until_ready();
  8227. SSLClient cli("127.0.0.1", PORT);
  8228. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8229. cli.enable_server_certificate_verification(true);
  8230. cli.set_connection_timeout(30);
  8231. auto res = cli.Get("/test");
  8232. ASSERT_TRUE(res);
  8233. ASSERT_EQ(StatusCode::OK_200, res->status);
  8234. }
  8235. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8236. std::string cert;
  8237. read_file(CA_CERT_FILE, cert);
  8238. SSLClient cli("google.com");
  8239. cli.load_ca_cert_store(cert.data(), cert.size());
  8240. const auto res = cli.Get("/");
  8241. ASSERT_TRUE(res);
  8242. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8243. }
  8244. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8245. // clang-format off
  8246. static constexpr char cert[] =
  8247. "GlobalSign Root CA\n"
  8248. "==================\n"
  8249. "-----BEGIN CERTIFICATE-----\n"
  8250. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8251. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8252. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8253. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8254. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8255. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8256. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8257. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8258. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8259. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8260. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8261. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8262. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8263. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8264. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8265. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8266. "-----END CERTIFICATE-----\n";
  8267. // clang-format on
  8268. SSLClient cli("google.com");
  8269. cli.load_ca_cert_store(cert, sizeof(cert));
  8270. const auto res = cli.Get("/");
  8271. ASSERT_TRUE(res);
  8272. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8273. }
  8274. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8275. SSLClient cli("www.youtube.com");
  8276. cli.set_ca_cert_path(CA_CERT_FILE);
  8277. cli.enable_server_certificate_verification(true);
  8278. cli.set_follow_location(true);
  8279. auto res = cli.Get("/");
  8280. ASSERT_TRUE(res);
  8281. ASSERT_EQ(StatusCode::OK_200, res->status);
  8282. }
  8283. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8284. SSLClient cli("wWw.YouTube.Com");
  8285. cli.set_ca_cert_path(CA_CERT_FILE);
  8286. cli.enable_server_certificate_verification(true);
  8287. cli.enable_server_hostname_verification(true);
  8288. cli.set_follow_location(true);
  8289. auto res = cli.Get("/");
  8290. ASSERT_TRUE(res);
  8291. ASSERT_EQ(StatusCode::OK_200, res->status);
  8292. }
  8293. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8294. SSLClient cli("gOoGlE.COm");
  8295. cli.enable_server_certificate_verification(true);
  8296. cli.enable_server_hostname_verification(true);
  8297. cli.set_follow_location(true);
  8298. auto res = cli.Get("/");
  8299. ASSERT_TRUE(res);
  8300. ASSERT_EQ(StatusCode::OK_200, res->status);
  8301. }
  8302. TEST(SSLClientTest, Issue2004_Online) {
  8303. Client client("https://google.com");
  8304. client.set_follow_location(true);
  8305. auto res = client.Get("/");
  8306. ASSERT_TRUE(res);
  8307. ASSERT_EQ(StatusCode::OK_200, res->status);
  8308. auto body = res->body;
  8309. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8310. }
  8311. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8312. // Create SSLClient with invalid cert/key to make is_valid() return false
  8313. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8314. "nonexistent_key.pem");
  8315. // is_valid() should be false due to cert loading failure
  8316. ASSERT_FALSE(cli.is_valid());
  8317. auto res = cli.Get("/");
  8318. ASSERT_FALSE(res);
  8319. EXPECT_EQ(Error::SSLConnection, res.error());
  8320. }
  8321. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8322. // Test for Issue #2251: SSL error not properly reported when client cert
  8323. // and key paths are swapped or mismatched
  8324. // This simulates the scenario where user accidentally swaps the cert and key
  8325. // files
  8326. // Using client cert file as private key and vice versa (completely wrong)
  8327. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8328. // Should fail validation due to cert/key mismatch
  8329. ASSERT_FALSE(cli.is_valid());
  8330. // Attempt to make a request should fail with proper error
  8331. auto res = cli.Get("/");
  8332. ASSERT_FALSE(res);
  8333. EXPECT_EQ(Error::SSLConnection, res.error());
  8334. // SSL error should be recorded in the Result object (this is the key fix for
  8335. // Issue #2251)
  8336. auto backend_error = res.ssl_backend_error();
  8337. EXPECT_NE(0u, backend_error);
  8338. }
  8339. // Tests cert/key mismatch detection at the TLS context level
  8340. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8341. // Test that using mismatched cert/key causes connection failure.
  8342. // We verify this at the SSLClient level rather than through internal
  8343. // TLS API functions.
  8344. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8345. cli.enable_server_certificate_verification(false);
  8346. cli.set_connection_timeout(2);
  8347. // The mismatch should cause a connection or handshake error
  8348. auto res = cli.Get("/test");
  8349. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8350. // Either way, the request should fail
  8351. EXPECT_FALSE(res);
  8352. }
  8353. #endif
  8354. #if 0
  8355. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8356. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8357. ASSERT_TRUE(cli != nullptr);
  8358. cli->set_address_family(AF_INET6);
  8359. cli->set_interface("en0");
  8360. auto res = cli->Get("/get");
  8361. ASSERT_TRUE(res);
  8362. ASSERT_EQ(StatusCode::OK_200, res->status);
  8363. }
  8364. #endif
  8365. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8366. #ifdef CPPHTTPLIB_SSL_ENABLED
  8367. void ClientCertPresent(
  8368. const std::string &client_cert_file,
  8369. const std::string &client_private_key_file,
  8370. const std::string &client_encrypted_private_key_pass = std::string()) {
  8371. using namespace httplib::tls;
  8372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8373. CLIENT_CA_CERT_DIR);
  8374. ASSERT_TRUE(svr.is_valid());
  8375. svr.Get("/test", [&](const Request &req, Response &res) {
  8376. res.set_content("test", "text/plain");
  8377. auto cert = req.peer_cert();
  8378. ASSERT_TRUE(static_cast<bool>(cert));
  8379. std::string common_name = cert.subject_cn();
  8380. EXPECT_EQ("Common Name", common_name);
  8381. });
  8382. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8383. auto se = detail::scope_exit([&] {
  8384. svr.stop();
  8385. t.join();
  8386. ASSERT_FALSE(svr.is_running());
  8387. });
  8388. svr.wait_until_ready();
  8389. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8390. client_encrypted_private_key_pass);
  8391. cli.enable_server_certificate_verification(false);
  8392. cli.set_connection_timeout(30);
  8393. auto res = cli.Get("/test");
  8394. ASSERT_TRUE(res);
  8395. ASSERT_EQ(StatusCode::OK_200, res->status);
  8396. }
  8397. TEST(SSLClientServerTest, ClientCertPresent) {
  8398. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8399. }
  8400. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8401. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8402. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8403. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8404. }
  8405. // PEM memory-based constructor tests (works with all TLS backends)
  8406. void PemMemoryClientCertPresent(
  8407. const std::string &client_cert_file,
  8408. const std::string &client_private_key_file,
  8409. const std::string &client_encrypted_private_key_pass = std::string()) {
  8410. // Read PEM files into memory
  8411. std::string server_cert_pem, server_key_pem;
  8412. std::string client_ca_pem;
  8413. std::string client_cert_pem, client_key_pem;
  8414. read_file(SERVER_CERT_FILE, server_cert_pem);
  8415. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8416. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8417. read_file(client_cert_file, client_cert_pem);
  8418. read_file(client_private_key_file, client_key_pem);
  8419. // Create server with PEM memory
  8420. SSLServer::PemMemory server_pem = {
  8421. server_cert_pem.c_str(),
  8422. server_cert_pem.size(),
  8423. server_key_pem.c_str(),
  8424. server_key_pem.size(),
  8425. client_ca_pem.c_str(),
  8426. client_ca_pem.size(),
  8427. nullptr // no password for server key
  8428. };
  8429. SSLServer svr(server_pem);
  8430. ASSERT_TRUE(svr.is_valid());
  8431. svr.Get("/test", [&](const Request &, Response &res) {
  8432. res.set_content("test", "text/plain");
  8433. });
  8434. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8435. auto se = detail::scope_exit([&] {
  8436. svr.stop();
  8437. t.join();
  8438. ASSERT_FALSE(svr.is_running());
  8439. });
  8440. svr.wait_until_ready();
  8441. // Create client with PEM memory
  8442. const char *password = client_encrypted_private_key_pass.empty()
  8443. ? nullptr
  8444. : client_encrypted_private_key_pass.c_str();
  8445. SSLClient::PemMemory client_pem = {
  8446. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8447. client_key_pem.size(), password};
  8448. SSLClient cli(HOST, PORT, client_pem);
  8449. cli.enable_server_certificate_verification(false);
  8450. cli.set_connection_timeout(30);
  8451. auto res = cli.Get("/test");
  8452. ASSERT_TRUE(res);
  8453. ASSERT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8456. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8457. }
  8458. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8459. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8460. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8461. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8462. }
  8463. TEST(SSLClientServerTest, ClientCertMissing) {
  8464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8465. CLIENT_CA_CERT_DIR);
  8466. ASSERT_TRUE(svr.is_valid());
  8467. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8469. auto se = detail::scope_exit([&] {
  8470. svr.stop();
  8471. t.join();
  8472. ASSERT_FALSE(svr.is_running());
  8473. });
  8474. svr.wait_until_ready();
  8475. SSLClient cli(HOST, PORT);
  8476. cli.set_connection_timeout(30);
  8477. auto res = cli.Get("/test");
  8478. ASSERT_TRUE(!res);
  8479. // When client cert is missing and server requires it, connection fails
  8480. // Error type depends on backend implementation
  8481. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8482. res.error() == Error::SSLConnection);
  8483. // Verify backend error is captured
  8484. // Note: This test may have different error codes depending on the exact
  8485. // verification failure
  8486. EXPECT_NE(0UL, res.ssl_backend_error());
  8487. }
  8488. TEST(SSLClientServerTest, TrustDirOptional) {
  8489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8490. ASSERT_TRUE(svr.is_valid());
  8491. svr.Get("/test", [&](const Request &, Response &res) {
  8492. res.set_content("test", "text/plain");
  8493. });
  8494. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8495. auto se = detail::scope_exit([&] {
  8496. svr.stop();
  8497. t.join();
  8498. ASSERT_FALSE(svr.is_running());
  8499. });
  8500. svr.wait_until_ready();
  8501. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8502. cli.enable_server_certificate_verification(false);
  8503. cli.set_connection_timeout(30);
  8504. auto res = cli.Get("/test");
  8505. ASSERT_TRUE(res);
  8506. ASSERT_EQ(StatusCode::OK_200, res->status);
  8507. }
  8508. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8509. class NoListenSSLServer : public SSLServer {
  8510. public:
  8511. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8512. const char *client_ca_cert_file_path,
  8513. const char *client_ca_cert_dir_path = nullptr)
  8514. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8515. client_ca_cert_dir_path),
  8516. stop_(false) {}
  8517. std::atomic_bool stop_;
  8518. private:
  8519. bool process_and_close_socket(socket_t /*sock*/) override {
  8520. // Don't create SSL context
  8521. while (!stop_.load()) {
  8522. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8523. }
  8524. return true;
  8525. }
  8526. };
  8527. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8528. CLIENT_CA_CERT_FILE);
  8529. ASSERT_TRUE(svr.is_valid());
  8530. svr.Get("/test", [&](const Request &, Response &res) {
  8531. res.set_content("test", "text/plain");
  8532. });
  8533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8534. auto se = detail::scope_exit([&] {
  8535. svr.stop_ = true;
  8536. svr.stop();
  8537. t.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8542. cli.enable_server_certificate_verification(false);
  8543. cli.set_connection_timeout(1);
  8544. auto res = cli.Get("/test");
  8545. ASSERT_TRUE(!res);
  8546. EXPECT_EQ(Error::SSLConnection, res.error());
  8547. // Timeout results in WantRead error code (maps to backend-specific value)
  8548. EXPECT_NE(0, res.ssl_error());
  8549. }
  8550. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8551. // Test SSLServer with client certificate verification using the standard
  8552. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8554. CLIENT_CA_CERT_DIR);
  8555. ASSERT_TRUE(svr.is_valid());
  8556. svr.Get("/test", [&](const Request &req, Response &res) {
  8557. res.set_content("test", "text/plain");
  8558. auto cert = req.peer_cert();
  8559. ASSERT_TRUE(static_cast<bool>(cert));
  8560. auto common_name = cert.subject_cn();
  8561. EXPECT_EQ("Common Name", common_name);
  8562. });
  8563. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8564. auto se = detail::scope_exit([&] {
  8565. svr.stop();
  8566. t.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8571. cli.enable_server_certificate_verification(false);
  8572. cli.set_connection_timeout(30);
  8573. auto res = cli.Get("/test");
  8574. ASSERT_TRUE(res);
  8575. ASSERT_EQ(StatusCode::OK_200, res->status);
  8576. }
  8577. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8578. // Verifies that wildcard matching and exact matching work consistently
  8579. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8580. using namespace httplib::tls;
  8581. // We need a running server to test against
  8582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8583. ASSERT_TRUE(svr.is_valid());
  8584. svr.Get("/test", [](const Request &, Response &res) {
  8585. res.set_content("ok", "text/plain");
  8586. });
  8587. thread t([&]() { svr.listen(HOST, PORT); });
  8588. auto se = detail::scope_exit([&] {
  8589. svr.stop();
  8590. t.join();
  8591. });
  8592. svr.wait_until_ready();
  8593. bool verify_callback_called = false;
  8594. bool verify_result_wrong = false;
  8595. SSLClient cli(HOST, PORT);
  8596. cli.enable_server_certificate_verification(true);
  8597. cli.set_ca_cert_path(CA_CERT_FILE);
  8598. cli.set_connection_timeout(5);
  8599. // Note: Test certificate has CN="Common Name", not "localhost"
  8600. bool verify_result_cn = false;
  8601. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8602. verify_callback_called = true;
  8603. if (!ctx.cert) return false;
  8604. // Test 1: "Common Name" should match (our test server cert CN)
  8605. verify_result_cn = ctx.check_hostname("Common Name");
  8606. // Test 2: wrong hostname should not match
  8607. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8608. return true; // Accept for the purpose of this test
  8609. });
  8610. auto res = cli.Get("/test");
  8611. // The request may succeed or fail depending on cert configuration
  8612. // but the callback should have been called
  8613. ASSERT_TRUE(verify_callback_called)
  8614. << "Verify callback should have been called";
  8615. // CN="Common Name" should match our test certificate
  8616. EXPECT_TRUE(verify_result_cn)
  8617. << "verify_hostname should match 'Common Name' (certificate CN)";
  8618. // Wrong hostname should not match
  8619. EXPECT_FALSE(verify_result_wrong)
  8620. << "verify_hostname should not match 'wronghost.example.com'";
  8621. }
  8622. #endif
  8623. // mbedTLS-specific callback constructor test
  8624. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8625. #ifdef CPPHTTPLIB_SSL_ENABLED
  8626. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8628. ASSERT_TRUE(svr.is_valid());
  8629. // Set up a handler to verify client certificate is present
  8630. bool client_cert_verified = false;
  8631. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8632. // Verify that client certificate was provided
  8633. client_cert_verified = true;
  8634. res.set_content("success", "text/plain");
  8635. });
  8636. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8637. auto se = detail::scope_exit([&] {
  8638. svr.stop();
  8639. t.join();
  8640. ASSERT_FALSE(svr.is_running());
  8641. });
  8642. svr.wait_until_ready();
  8643. // Client with certificate
  8644. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8645. cli.enable_server_certificate_verification(false);
  8646. cli.set_connection_timeout(30);
  8647. auto res = cli.Get("/test");
  8648. ASSERT_TRUE(res);
  8649. ASSERT_EQ(StatusCode::OK_200, res->status);
  8650. ASSERT_TRUE(client_cert_verified);
  8651. EXPECT_EQ("success", res->body);
  8652. }
  8653. #endif
  8654. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8655. // backends
  8656. #ifdef CPPHTTPLIB_SSL_ENABLED
  8657. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8658. using namespace httplib::tls;
  8659. // Test that when client CA cert file is provided,
  8660. // the server properly requests and validates client certificates
  8661. // Create a server with client authentication
  8662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8663. ASSERT_TRUE(svr.is_valid());
  8664. bool handler_called = false;
  8665. svr.Get("/test", [&](const Request &req, Response &res) {
  8666. handler_called = true;
  8667. // Verify that a client certificate was provided
  8668. auto cert = req.peer_cert();
  8669. ASSERT_TRUE(static_cast<bool>(cert));
  8670. // Get the issuer name
  8671. std::string issuer_str = cert.issuer_name();
  8672. ASSERT_FALSE(issuer_str.empty());
  8673. // The client certificate should be issued by our test CA
  8674. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8675. res.set_content("authenticated", "text/plain");
  8676. });
  8677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8678. auto se = detail::scope_exit([&] {
  8679. svr.stop();
  8680. t.join();
  8681. ASSERT_FALSE(svr.is_running());
  8682. });
  8683. svr.wait_until_ready();
  8684. // Connect with a client certificate issued by the CA
  8685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8686. cli.enable_server_certificate_verification(false);
  8687. cli.set_connection_timeout(30);
  8688. auto res = cli.Get("/test");
  8689. ASSERT_TRUE(res);
  8690. ASSERT_EQ(StatusCode::OK_200, res->status);
  8691. ASSERT_TRUE(handler_called);
  8692. EXPECT_EQ("authenticated", res->body);
  8693. }
  8694. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8695. using namespace httplib::tls;
  8696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8697. ASSERT_TRUE(svr.is_valid());
  8698. svr.Get("/test", [](const Request &, Response &res) {
  8699. res.set_content("ok", "text/plain");
  8700. });
  8701. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8702. auto se = detail::scope_exit([&] {
  8703. svr.stop();
  8704. t.join();
  8705. });
  8706. svr.wait_until_ready();
  8707. SSLClient cli(HOST, PORT);
  8708. cli.enable_server_certificate_verification(false);
  8709. cli.set_connection_timeout(30);
  8710. bool cert_checked = false;
  8711. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8712. if (ctx.cert) {
  8713. auto sans = ctx.sans();
  8714. // Test certificate may or may not have SANs - just verify the API
  8715. // works If SANs exist, verify the types are valid
  8716. for (const auto &san : sans) {
  8717. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8718. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8719. san.type == SanType::OTHER);
  8720. EXPECT_FALSE(san.value.empty());
  8721. }
  8722. cert_checked = true;
  8723. }
  8724. return true;
  8725. });
  8726. auto res = cli.Get("/test");
  8727. ASSERT_TRUE(res);
  8728. EXPECT_TRUE(cert_checked);
  8729. }
  8730. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8731. using namespace httplib::tls;
  8732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8733. ASSERT_TRUE(svr.is_valid());
  8734. svr.Get("/test", [](const Request &, Response &res) {
  8735. res.set_content("ok", "text/plain");
  8736. });
  8737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8738. auto se = detail::scope_exit([&] {
  8739. svr.stop();
  8740. t.join();
  8741. });
  8742. svr.wait_until_ready();
  8743. SSLClient cli(HOST, PORT);
  8744. cli.enable_server_certificate_verification(false);
  8745. cli.set_connection_timeout(30);
  8746. bool validity_checked = false;
  8747. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8748. if (ctx.cert) {
  8749. time_t not_before = 0, not_after = 0;
  8750. bool result = ctx.validity(not_before, not_after);
  8751. EXPECT_TRUE(result);
  8752. // Verify that not_before < now < not_after for a valid cert
  8753. time_t now = time(nullptr);
  8754. EXPECT_LT(not_before, now);
  8755. EXPECT_GT(not_after, now);
  8756. validity_checked = true;
  8757. }
  8758. return true;
  8759. });
  8760. auto res = cli.Get("/test");
  8761. ASSERT_TRUE(res);
  8762. EXPECT_TRUE(validity_checked);
  8763. }
  8764. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8765. using namespace httplib::tls;
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8767. ASSERT_TRUE(svr.is_valid());
  8768. svr.Get("/test", [](const Request &, Response &res) {
  8769. res.set_content("ok", "text/plain");
  8770. });
  8771. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. });
  8776. svr.wait_until_ready();
  8777. SSLClient cli(HOST, PORT);
  8778. cli.enable_server_certificate_verification(false);
  8779. cli.set_connection_timeout(30);
  8780. bool serial_checked = false;
  8781. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8782. if (ctx.cert) {
  8783. std::string serial = ctx.serial();
  8784. EXPECT_FALSE(serial.empty());
  8785. // Serial should be a hex string
  8786. for (char c : serial) {
  8787. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8788. (c >= 'a' && c <= 'f'));
  8789. }
  8790. serial_checked = true;
  8791. }
  8792. return true;
  8793. });
  8794. auto res = cli.Get("/test");
  8795. ASSERT_TRUE(res);
  8796. EXPECT_TRUE(serial_checked);
  8797. }
  8798. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8799. // Test 1: Valid CA file - no error should be recorded
  8800. {
  8801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8802. CLIENT_CA_CERT_FILE);
  8803. ASSERT_TRUE(svr.is_valid());
  8804. // With valid setup, last_ssl_error should be 0
  8805. EXPECT_EQ(0, svr.ssl_last_error());
  8806. }
  8807. // Test 2: Invalid CA file content
  8808. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8809. {
  8810. // Create a temporary file with completely invalid content
  8811. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8812. {
  8813. std::ofstream ofs(temp_invalid_ca);
  8814. ofs << "This is not a certificate file at all\n";
  8815. ofs << "Just plain text content\n";
  8816. }
  8817. // Create server with invalid CA file
  8818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8819. // Clean up temporary file
  8820. std::remove(temp_invalid_ca);
  8821. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8822. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8823. // Note: SSL_CTX_load_verify_locations typically fails first,
  8824. // but our error handling code path is still exercised
  8825. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8826. }
  8827. }
  8828. TEST(VerifyCallbackTest, VerifyContextFields) {
  8829. using namespace httplib::tls;
  8830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8831. ASSERT_TRUE(svr.is_valid());
  8832. svr.Get("/test", [](const Request &, Response &res) {
  8833. res.set_content("ok", "text/plain");
  8834. });
  8835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8836. auto se = detail::scope_exit([&] {
  8837. svr.stop();
  8838. t.join();
  8839. });
  8840. svr.wait_until_ready();
  8841. SSLClient cli(HOST, PORT);
  8842. cli.enable_server_certificate_verification(false);
  8843. cli.set_connection_timeout(30);
  8844. int callback_count = 0;
  8845. bool saw_leaf_cert = false;
  8846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8847. if (ctx.cert) {
  8848. callback_count++;
  8849. // We should see at least one certificate (the leaf)
  8850. std::string cn = ctx.subject_cn();
  8851. if (!cn.empty()) { saw_leaf_cert = true; }
  8852. // Verify context fields are populated
  8853. EXPECT_NE(ctx.session, nullptr);
  8854. EXPECT_GE(ctx.depth, 0);
  8855. }
  8856. return true;
  8857. });
  8858. auto res = cli.Get("/test");
  8859. ASSERT_TRUE(res);
  8860. EXPECT_GT(callback_count, 0);
  8861. EXPECT_TRUE(saw_leaf_cert);
  8862. }
  8863. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8864. using httplib::tls::TlsError;
  8865. // Test that verify_error_to_string returns empty for success
  8866. std::string success_str = TlsError::verify_error_to_string(0);
  8867. EXPECT_TRUE(success_str.empty());
  8868. // Test that verify_error_to_string returns non-empty for error codes
  8869. // Using a common error code (certificate expired)
  8870. std::string error_str =
  8871. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8872. EXPECT_FALSE(error_str.empty());
  8873. }
  8874. TEST(SessionVerifierTest, CertificateAccepted) {
  8875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8876. ASSERT_TRUE(svr.is_valid());
  8877. svr.Get("/test", [](const Request &, Response &res) {
  8878. res.set_content("ok", "text/plain");
  8879. });
  8880. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8881. auto se = detail::scope_exit([&] {
  8882. svr.stop();
  8883. t.join();
  8884. });
  8885. svr.wait_until_ready();
  8886. SSLClient cli(HOST, PORT);
  8887. cli.enable_server_certificate_verification(false);
  8888. cli.set_connection_timeout(30);
  8889. bool callback_called = false;
  8890. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8891. EXPECT_NE(session, nullptr);
  8892. callback_called = true;
  8893. return SSLVerifierResponse::CertificateAccepted;
  8894. });
  8895. auto res = cli.Get("/test");
  8896. ASSERT_TRUE(res);
  8897. EXPECT_EQ(200, res->status);
  8898. EXPECT_TRUE(callback_called);
  8899. }
  8900. TEST(SessionVerifierTest, CertificateRejected) {
  8901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8902. ASSERT_TRUE(svr.is_valid());
  8903. svr.Get("/test", [](const Request &, Response &res) {
  8904. res.set_content("ok", "text/plain");
  8905. });
  8906. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8907. auto se = detail::scope_exit([&] {
  8908. svr.stop();
  8909. t.join();
  8910. });
  8911. svr.wait_until_ready();
  8912. SSLClient cli(HOST, PORT);
  8913. cli.enable_server_certificate_verification(false);
  8914. cli.set_connection_timeout(30);
  8915. bool callback_called = false;
  8916. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8917. EXPECT_NE(session, nullptr);
  8918. callback_called = true;
  8919. return SSLVerifierResponse::CertificateRejected;
  8920. });
  8921. auto res = cli.Get("/test");
  8922. EXPECT_FALSE(res);
  8923. EXPECT_TRUE(callback_called);
  8924. }
  8925. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8927. ASSERT_TRUE(svr.is_valid());
  8928. svr.Get("/test", [](const Request &, Response &res) {
  8929. res.set_content("ok", "text/plain");
  8930. });
  8931. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. });
  8936. svr.wait_until_ready();
  8937. // NoDecisionMade with verification disabled should succeed (no default check)
  8938. SSLClient cli(HOST, PORT);
  8939. cli.enable_server_certificate_verification(false);
  8940. cli.set_connection_timeout(30);
  8941. bool callback_called = false;
  8942. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8943. EXPECT_NE(session, nullptr);
  8944. callback_called = true;
  8945. return SSLVerifierResponse::NoDecisionMade;
  8946. });
  8947. auto res = cli.Get("/test");
  8948. ASSERT_TRUE(res);
  8949. EXPECT_EQ(200, res->status);
  8950. EXPECT_TRUE(callback_called);
  8951. }
  8952. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8954. ASSERT_TRUE(svr.is_valid());
  8955. svr.Get("/test", [](const Request &, Response &res) {
  8956. res.set_content("ok", "text/plain");
  8957. });
  8958. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8959. auto se = detail::scope_exit([&] {
  8960. svr.stop();
  8961. t.join();
  8962. });
  8963. svr.wait_until_ready();
  8964. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8965. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8966. // so we only check that the request fails, not whether the callback was
  8967. // called.
  8968. SSLClient cli(HOST, PORT);
  8969. cli.enable_server_certificate_verification(true);
  8970. cli.set_connection_timeout(30);
  8971. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8972. EXPECT_NE(session, nullptr);
  8973. return SSLVerifierResponse::NoDecisionMade;
  8974. });
  8975. auto res = cli.Get("/test");
  8976. EXPECT_FALSE(res);
  8977. }
  8978. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8979. // Test SSL server using PemMemory constructor with client CA certificates
  8980. // Read PEM files
  8981. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8982. read_file(SERVER_CERT_FILE, server_cert_pem);
  8983. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8984. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8985. // Create SSLServer with PemMemory constructor including client CA
  8986. SSLServer::PemMemory server_pem = {
  8987. server_cert_pem.c_str(),
  8988. server_cert_pem.size(),
  8989. server_key_pem.c_str(),
  8990. server_key_pem.size(),
  8991. client_ca_pem.c_str(),
  8992. client_ca_pem.size(),
  8993. nullptr // no password for server key
  8994. };
  8995. SSLServer svr(server_pem);
  8996. ASSERT_TRUE(svr.is_valid());
  8997. // No SSL error should be recorded for valid setup
  8998. EXPECT_EQ(0, svr.ssl_last_error());
  8999. // Set up server endpoints
  9000. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9001. res.set_content("ok", "text/plain");
  9002. });
  9003. // Start server in a thread
  9004. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9005. svr.wait_until_ready();
  9006. // Connect with client certificate (using constructor with paths)
  9007. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9008. cli.enable_server_certificate_verification(false);
  9009. auto res = cli.Get("/test-pem-ca");
  9010. ASSERT_TRUE(res);
  9011. EXPECT_EQ(200, res->status);
  9012. EXPECT_EQ("ok", res->body);
  9013. svr.stop();
  9014. server_thread.join();
  9015. }
  9016. #endif
  9017. #ifdef _WIN32
  9018. TEST(CleanupTest, WSACleanup) {
  9019. int ret = WSACleanup();
  9020. ASSERT_EQ(0, ret);
  9021. }
  9022. #endif
  9023. #ifndef CPPHTTPLIB_SSL_ENABLED
  9024. TEST(NoSSLSupport, SimpleInterface) {
  9025. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9026. }
  9027. #endif
  9028. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9029. TEST(InvalidScheme, SimpleInterface) {
  9030. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9031. }
  9032. #endif
  9033. TEST(NoScheme, SimpleInterface) {
  9034. Client cli("yahoo.com:80");
  9035. ASSERT_TRUE(cli.is_valid());
  9036. }
  9037. TEST(SendAPI, SimpleInterface_Online) {
  9038. Client cli("http://yahoo.com");
  9039. Request req;
  9040. req.method = "GET";
  9041. req.path = "/";
  9042. auto res = cli.send(req);
  9043. ASSERT_TRUE(res);
  9044. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9045. }
  9046. TEST(SendAPI, WithParamsInRequest) {
  9047. Server svr;
  9048. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9049. EXPECT_TRUE(req.has_param("test"));
  9050. EXPECT_EQ("test_value", req.get_param_value("test"));
  9051. });
  9052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9053. auto se = detail::scope_exit([&] {
  9054. svr.stop();
  9055. t.join();
  9056. ASSERT_FALSE(svr.is_running());
  9057. });
  9058. svr.wait_until_ready();
  9059. Client cli(HOST, PORT);
  9060. {
  9061. Request req;
  9062. req.method = "GET";
  9063. req.path = "/";
  9064. req.params.emplace("test", "test_value");
  9065. auto res = cli.send(req);
  9066. ASSERT_TRUE(res);
  9067. }
  9068. {
  9069. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9070. ASSERT_TRUE(res);
  9071. }
  9072. }
  9073. TEST(ClientImplMethods, GetSocketTest) {
  9074. httplib::Server svr;
  9075. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9076. res.status = StatusCode::OK_200;
  9077. });
  9078. auto port = svr.bind_to_any_port("127.0.0.1");
  9079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9080. auto se = detail::scope_exit([&] {
  9081. svr.stop();
  9082. thread.join();
  9083. ASSERT_FALSE(svr.is_running());
  9084. });
  9085. svr.wait_until_ready();
  9086. {
  9087. httplib::Client cli("127.0.0.1", port);
  9088. cli.set_keep_alive(true);
  9089. // Use the behavior of cpp-httplib of opening the connection
  9090. // only when the first request happens. If that changes,
  9091. // this test would be obsolete.
  9092. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9093. // This also implicitly tests the server. But other tests would fail much
  9094. // earlier than this one to be considered.
  9095. auto res = cli.Get("/");
  9096. ASSERT_TRUE(res);
  9097. EXPECT_EQ(StatusCode::OK_200, res->status);
  9098. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9099. }
  9100. }
  9101. #ifdef CPPHTTPLIB_SSL_ENABLED
  9102. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9103. Client cli("http://yahoo.com");
  9104. auto res = cli.Get("/");
  9105. ASSERT_TRUE(res);
  9106. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9107. cli.set_follow_location(true);
  9108. res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9112. }
  9113. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9114. Client cli("https://yahoo.com");
  9115. auto res = cli.Get("/");
  9116. ASSERT_TRUE(res);
  9117. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9118. cli.set_follow_location(true);
  9119. res = cli.Get("/");
  9120. ASSERT_TRUE(res);
  9121. EXPECT_EQ(StatusCode::OK_200, res->status);
  9122. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9123. }
  9124. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9125. Client cli("https://yahoo.com");
  9126. auto res = cli.Get("/");
  9127. ASSERT_TRUE(res);
  9128. ASSERT_FALSE(!res);
  9129. ASSERT_TRUE(res);
  9130. ASSERT_FALSE(res == nullptr);
  9131. ASSERT_TRUE(res != nullptr);
  9132. EXPECT_EQ(Error::Success, res.error());
  9133. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9134. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9135. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9136. cli.set_follow_location(true);
  9137. res = cli.Get("/");
  9138. ASSERT_TRUE(res);
  9139. EXPECT_EQ(Error::Success, res.error());
  9140. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9141. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9142. EXPECT_EQ(StatusCode::OK_200, res->status);
  9143. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9144. }
  9145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9146. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9147. Client cli("https://cdnjs.cloudflare.com");
  9148. auto res =
  9149. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9150. ASSERT_TRUE(res);
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ(287630U, res->body.size());
  9153. EXPECT_EQ("application/javascript; charset=utf-8",
  9154. res->get_header_value("Content-Type"));
  9155. }
  9156. #endif
  9157. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9158. #undef REDIR_HOST // Silence compiler warning
  9159. #define REDIR_HOST "https://httpbingo.org"
  9160. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9161. Client cli(REDIR_HOST);
  9162. cli.set_follow_location(true);
  9163. auto res =
  9164. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9165. ASSERT_TRUE(res);
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9169. Client cli(REDIR_HOST);
  9170. cli.set_follow_location(true);
  9171. Params params;
  9172. params.emplace("url", "http://example.com");
  9173. params.emplace("status_code", "302");
  9174. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9175. ASSERT_TRUE(res);
  9176. EXPECT_EQ(StatusCode::OK_200, res->status);
  9177. }
  9178. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9179. Client cli(REDIR_HOST);
  9180. cli.set_follow_location(true);
  9181. Params params;
  9182. params.emplace("url", "http://example.com");
  9183. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9184. ASSERT_TRUE(res);
  9185. EXPECT_EQ(StatusCode::OK_200, res->status);
  9186. }
  9187. TEST(HttpToHttpsRedirectTest, CertFile) {
  9188. auto ssl_port = PORT + 1;
  9189. Server svr;
  9190. ASSERT_TRUE(svr.is_valid());
  9191. svr.Get("/index", [&](const Request &, Response &res) {
  9192. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9193. "/index");
  9194. svr.stop();
  9195. });
  9196. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9197. ASSERT_TRUE(ssl_svr.is_valid());
  9198. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9199. res.set_content("test", "text/plain");
  9200. ssl_svr.stop();
  9201. });
  9202. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9203. thread t2 =
  9204. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9205. auto se = detail::scope_exit([&] {
  9206. t2.join();
  9207. t.join();
  9208. ASSERT_FALSE(svr.is_running());
  9209. });
  9210. svr.wait_until_ready();
  9211. ssl_svr.wait_until_ready();
  9212. Client cli("127.0.0.1", PORT);
  9213. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9214. cli.enable_server_certificate_verification(true);
  9215. cli.set_follow_location(true);
  9216. cli.set_connection_timeout(30);
  9217. auto res = cli.Get("/index");
  9218. ASSERT_TRUE(res);
  9219. ASSERT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. TEST(SSLClientRedirectTest, CertFile) {
  9222. auto ssl_port = PORT + 1;
  9223. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9224. ASSERT_TRUE(ssl_svr1.is_valid());
  9225. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9226. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9227. "/index");
  9228. ssl_svr1.stop();
  9229. });
  9230. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9231. ASSERT_TRUE(ssl_svr2.is_valid());
  9232. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9233. res.set_content("test", "text/plain");
  9234. ssl_svr2.stop();
  9235. });
  9236. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9237. thread t2 =
  9238. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9239. auto se = detail::scope_exit([&] {
  9240. t2.join();
  9241. t.join();
  9242. ASSERT_FALSE(ssl_svr1.is_running());
  9243. });
  9244. ssl_svr1.wait_until_ready();
  9245. ssl_svr2.wait_until_ready();
  9246. SSLClient cli("127.0.0.1", PORT);
  9247. std::string cert;
  9248. read_file(SERVER_CERT2_FILE, cert);
  9249. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9250. cli.enable_server_certificate_verification(true);
  9251. cli.set_follow_location(true);
  9252. cli.set_connection_timeout(30);
  9253. auto res = cli.Get("/index");
  9254. ASSERT_TRUE(res);
  9255. ASSERT_EQ(StatusCode::OK_200, res->status);
  9256. }
  9257. #endif
  9258. #ifdef CPPHTTPLIB_SSL_ENABLED
  9259. // Test that set_ca_cert_store() skips system certs (consistent with
  9260. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9261. // should be trusted - system certs should NOT be loaded.
  9262. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9263. // Load a specific cert that is NOT a system CA cert
  9264. std::string cert;
  9265. read_file(SERVER_CERT2_FILE, cert);
  9266. SSLClient cli("google.com");
  9267. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9268. cli.enable_server_certificate_verification(true);
  9269. // This should FAIL because:
  9270. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9271. // 2. System certs should NOT be loaded when custom store is set
  9272. // If system certs WERE loaded, this would succeed
  9273. auto res = cli.Get("/");
  9274. ASSERT_FALSE(res);
  9275. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9276. }
  9277. TEST(MultipartFormDataTest, LargeData) {
  9278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9279. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9280. const ContentReader &content_reader) {
  9281. if (req.is_multipart_form_data()) {
  9282. std::vector<FormData> items;
  9283. content_reader(
  9284. [&](const FormData &file) {
  9285. items.push_back(file);
  9286. return true;
  9287. },
  9288. [&](const char *data, size_t data_length) {
  9289. items.back().content.append(data, data_length);
  9290. return true;
  9291. });
  9292. EXPECT_TRUE(std::string(items[0].name) == "document");
  9293. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9294. EXPECT_TRUE(items[0].filename == "2MB_data");
  9295. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9296. EXPECT_TRUE(items[1].name == "hello");
  9297. EXPECT_TRUE(items[1].content == "world");
  9298. EXPECT_TRUE(items[1].filename == "");
  9299. EXPECT_TRUE(items[1].content_type == "");
  9300. } else {
  9301. std::string body;
  9302. content_reader([&](const char *data, size_t data_length) {
  9303. body.append(data, data_length);
  9304. return true;
  9305. });
  9306. }
  9307. });
  9308. auto port = svr.bind_to_any_port(HOST);
  9309. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9310. auto se = detail::scope_exit([&] {
  9311. svr.stop();
  9312. t.join();
  9313. ASSERT_FALSE(svr.is_running());
  9314. });
  9315. svr.wait_until_ready();
  9316. {
  9317. std::string data(1024 * 1024 * 2, '.');
  9318. std::stringstream buffer;
  9319. buffer << data;
  9320. SSLClient cli(HOST, port);
  9321. cli.enable_server_certificate_verification(false);
  9322. UploadFormDataItems items{
  9323. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9324. {"hello", "world", "", ""},
  9325. };
  9326. auto res = cli.Post("/post", items);
  9327. ASSERT_TRUE(res);
  9328. ASSERT_EQ(StatusCode::OK_200, res->status);
  9329. }
  9330. }
  9331. TEST(MultipartFormDataTest, DataProviderItems) {
  9332. std::random_device seed_gen;
  9333. std::mt19937 random(seed_gen());
  9334. std::string rand1;
  9335. rand1.resize(1000);
  9336. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9337. std::string rand2;
  9338. rand2.resize(3000);
  9339. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9341. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9342. const ContentReader &content_reader) {
  9343. ASSERT_FALSE(req.is_multipart_form_data());
  9344. std::string body;
  9345. content_reader([&](const char *data, size_t data_length) {
  9346. body.append(data, data_length);
  9347. return true;
  9348. });
  9349. EXPECT_EQ(body, "");
  9350. });
  9351. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9352. const ContentReader &content_reader) {
  9353. ASSERT_TRUE(req.is_multipart_form_data());
  9354. std::vector<FormData> items;
  9355. content_reader(
  9356. [&](const FormData &file) {
  9357. items.push_back(file);
  9358. return true;
  9359. },
  9360. [&](const char *data, size_t data_length) {
  9361. items.back().content.append(data, data_length);
  9362. return true;
  9363. });
  9364. ASSERT_TRUE(items.size() == 2);
  9365. EXPECT_EQ(std::string(items[0].name), "name1");
  9366. EXPECT_EQ(items[0].content, "Testing123");
  9367. EXPECT_EQ(items[0].filename, "filename1");
  9368. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9369. EXPECT_EQ(items[1].name, "name2");
  9370. EXPECT_EQ(items[1].content, "Testing456");
  9371. EXPECT_EQ(items[1].filename, "");
  9372. EXPECT_EQ(items[1].content_type, "");
  9373. });
  9374. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9375. const ContentReader &content_reader) {
  9376. ASSERT_TRUE(req.is_multipart_form_data());
  9377. std::vector<FormData> items;
  9378. content_reader(
  9379. [&](const FormData &file) {
  9380. items.push_back(file);
  9381. return true;
  9382. },
  9383. [&](const char *data, size_t data_length) {
  9384. items.back().content.append(data, data_length);
  9385. return true;
  9386. });
  9387. ASSERT_TRUE(items.size() == 2);
  9388. EXPECT_EQ(items[0].name, "name3");
  9389. EXPECT_EQ(items[0].content, rand1);
  9390. EXPECT_EQ(items[0].filename, "filename3");
  9391. EXPECT_EQ(items[0].content_type, "");
  9392. EXPECT_EQ(items[1].name, "name4");
  9393. EXPECT_EQ(items[1].content, rand2);
  9394. EXPECT_EQ(items[1].filename, "filename4");
  9395. EXPECT_EQ(items[1].content_type, "");
  9396. });
  9397. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9398. const ContentReader &content_reader) {
  9399. ASSERT_TRUE(req.is_multipart_form_data());
  9400. std::vector<FormData> items;
  9401. content_reader(
  9402. [&](const FormData &file) {
  9403. items.push_back(file);
  9404. return true;
  9405. },
  9406. [&](const char *data, size_t data_length) {
  9407. items.back().content.append(data, data_length);
  9408. return true;
  9409. });
  9410. ASSERT_TRUE(items.size() == 4);
  9411. EXPECT_EQ(std::string(items[0].name), "name1");
  9412. EXPECT_EQ(items[0].content, "Testing123");
  9413. EXPECT_EQ(items[0].filename, "filename1");
  9414. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9415. EXPECT_EQ(items[1].name, "name2");
  9416. EXPECT_EQ(items[1].content, "Testing456");
  9417. EXPECT_EQ(items[1].filename, "");
  9418. EXPECT_EQ(items[1].content_type, "");
  9419. EXPECT_EQ(items[2].name, "name3");
  9420. EXPECT_EQ(items[2].content, rand1);
  9421. EXPECT_EQ(items[2].filename, "filename3");
  9422. EXPECT_EQ(items[2].content_type, "");
  9423. EXPECT_EQ(items[3].name, "name4");
  9424. EXPECT_EQ(items[3].content, rand2);
  9425. EXPECT_EQ(items[3].filename, "filename4");
  9426. EXPECT_EQ(items[3].content_type, "");
  9427. });
  9428. auto port = svr.bind_to_any_port("localhost");
  9429. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9430. auto se = detail::scope_exit([&] {
  9431. svr.stop();
  9432. t.join();
  9433. ASSERT_FALSE(svr.is_running());
  9434. });
  9435. svr.wait_until_ready();
  9436. {
  9437. SSLClient cli("localhost", port);
  9438. cli.enable_server_certificate_verification(false);
  9439. UploadFormDataItems items{
  9440. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9441. {"name2", "Testing456", "", ""}, // not a file
  9442. };
  9443. {
  9444. auto res = cli.Post("/post-none", {}, {}, {});
  9445. ASSERT_TRUE(res);
  9446. ASSERT_EQ(StatusCode::OK_200, res->status);
  9447. }
  9448. FormDataProviderItems providers;
  9449. {
  9450. auto res =
  9451. cli.Post("/post-items", {}, items, providers); // empty providers
  9452. ASSERT_TRUE(res);
  9453. ASSERT_EQ(StatusCode::OK_200, res->status);
  9454. }
  9455. providers.push_back({"name3",
  9456. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9457. // test the offset is given correctly at each step
  9458. if (!offset)
  9459. sink.os.write(rand1.data(), 30);
  9460. else if (offset == 30)
  9461. sink.os.write(rand1.data() + 30, 300);
  9462. else if (offset == 330)
  9463. sink.os.write(rand1.data() + 330, 670);
  9464. else if (offset == rand1.size())
  9465. sink.done();
  9466. return true;
  9467. },
  9468. "filename3",
  9469. {}});
  9470. providers.push_back({"name4",
  9471. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9472. // test the offset is given correctly at each step
  9473. if (!offset)
  9474. sink.os.write(rand2.data(), 2000);
  9475. else if (offset == 2000)
  9476. sink.os.write(rand2.data() + 2000, 1);
  9477. else if (offset == 2001)
  9478. sink.os.write(rand2.data() + 2001, 999);
  9479. else if (offset == rand2.size())
  9480. sink.done();
  9481. return true;
  9482. },
  9483. "filename4",
  9484. {}});
  9485. {
  9486. auto res = cli.Post("/post-providers", {}, {}, providers);
  9487. ASSERT_TRUE(res);
  9488. ASSERT_EQ(StatusCode::OK_200, res->status);
  9489. }
  9490. {
  9491. auto res = cli.Post("/post-both", {}, items, providers);
  9492. ASSERT_TRUE(res);
  9493. ASSERT_EQ(StatusCode::OK_200, res->status);
  9494. }
  9495. }
  9496. }
  9497. TEST(MultipartFormDataTest, BadHeader) {
  9498. Server svr;
  9499. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9500. res.set_content("ok", "text/plain");
  9501. });
  9502. thread t = thread([&] { svr.listen(HOST, PORT); });
  9503. auto se = detail::scope_exit([&] {
  9504. svr.stop();
  9505. t.join();
  9506. ASSERT_FALSE(svr.is_running());
  9507. });
  9508. svr.wait_until_ready();
  9509. const std::string body =
  9510. "This is the preamble. It is to be ignored, though it\r\n"
  9511. "is a handy place for composition agents to include an\r\n"
  9512. "explanatory note to non-MIME conformant readers.\r\n"
  9513. "\r\n"
  9514. "\r\n"
  9515. "--simple boundary\r\n"
  9516. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9517. ": BAD...\r\n"
  9518. "\r\n"
  9519. "value1\r\n"
  9520. "--simple boundary\r\n"
  9521. "Content-Disposition: form-data; name=\"field2\"; "
  9522. "filename=\"example.txt\"\r\n"
  9523. "\r\n"
  9524. "value2\r\n"
  9525. "--simple boundary--\r\n"
  9526. "This is the epilogue. It is also to be ignored.\r\n";
  9527. std::string content_type =
  9528. R"(multipart/form-data; boundary="simple boundary")";
  9529. Client cli(HOST, PORT);
  9530. auto res = cli.Post("/post", body, content_type.c_str());
  9531. ASSERT_TRUE(res);
  9532. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9533. }
  9534. TEST(MultipartFormDataTest, WithPreamble) {
  9535. Server svr;
  9536. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9537. res.set_content("ok", "text/plain");
  9538. });
  9539. thread t = thread([&] { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. const std::string body =
  9547. "This is the preamble. It is to be ignored, though it\r\n"
  9548. "is a handy place for composition agents to include an\r\n"
  9549. "explanatory note to non-MIME conformant readers.\r\n"
  9550. "\r\n"
  9551. "\r\n"
  9552. "--simple boundary\r\n"
  9553. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9554. "\r\n"
  9555. "value1\r\n"
  9556. "--simple boundary\r\n"
  9557. "Content-Disposition: form-data; name=\"field2\"; "
  9558. "filename=\"example.txt\"\r\n"
  9559. "\r\n"
  9560. "value2\r\n"
  9561. "--simple boundary--\r\n"
  9562. "This is the epilogue. It is also to be ignored.\r\n";
  9563. std::string content_type =
  9564. R"(multipart/form-data; boundary="simple boundary")";
  9565. Client cli(HOST, PORT);
  9566. auto res = cli.Post("/post", body, content_type.c_str());
  9567. ASSERT_TRUE(res);
  9568. EXPECT_EQ(StatusCode::OK_200, res->status);
  9569. }
  9570. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9572. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9573. const ContentReader &content_reader) {
  9574. if (req.is_multipart_form_data()) {
  9575. std::vector<FormData> items;
  9576. content_reader(
  9577. [&](const FormData &file) {
  9578. items.push_back(file);
  9579. return true;
  9580. },
  9581. [&](const char *data, size_t data_length) {
  9582. items.back().content.append(data, data_length);
  9583. return true;
  9584. });
  9585. EXPECT_TRUE(std::string(items[0].name) == "document");
  9586. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9587. EXPECT_TRUE(items[0].filename == "2MB_data");
  9588. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9589. EXPECT_TRUE(items[1].name == "hello");
  9590. EXPECT_TRUE(items[1].content == "world");
  9591. EXPECT_TRUE(items[1].filename == "");
  9592. EXPECT_TRUE(items[1].content_type == "");
  9593. } else {
  9594. std::string body;
  9595. content_reader([&](const char *data, size_t data_length) {
  9596. body.append(data, data_length);
  9597. return true;
  9598. });
  9599. }
  9600. });
  9601. auto port = svr.bind_to_any_port("localhost");
  9602. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. ASSERT_FALSE(svr.is_running());
  9607. });
  9608. svr.wait_until_ready();
  9609. {
  9610. std::string data(1024 * 1024 * 2, '.');
  9611. std::stringstream buffer;
  9612. buffer << data;
  9613. SSLClient cli("localhost", port);
  9614. cli.enable_server_certificate_verification(false);
  9615. UploadFormDataItems items{
  9616. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9617. {"hello", "world", "", ""},
  9618. };
  9619. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9620. ASSERT_TRUE(res);
  9621. ASSERT_EQ(StatusCode::OK_200, res->status);
  9622. }
  9623. }
  9624. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9625. std::string data(1024 * 1024 * 2, '&');
  9626. std::stringstream buffer;
  9627. buffer << data;
  9628. Client cli("https://localhost:8080");
  9629. UploadFormDataItems items{
  9630. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9631. {"hello", "world", "", ""},
  9632. };
  9633. for (const char &c : " \t\r\n") {
  9634. auto res =
  9635. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9636. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9637. ASSERT_FALSE(res);
  9638. }
  9639. }
  9640. TEST(MultipartFormDataTest, PutFormData) {
  9641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9642. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9643. const ContentReader &content_reader) {
  9644. if (req.is_multipart_form_data()) {
  9645. std::vector<FormData> items;
  9646. content_reader(
  9647. [&](const FormData &file) {
  9648. items.push_back(file);
  9649. return true;
  9650. },
  9651. [&](const char *data, size_t data_length) {
  9652. items.back().content.append(data, data_length);
  9653. return true;
  9654. });
  9655. EXPECT_TRUE(std::string(items[0].name) == "document");
  9656. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9657. EXPECT_TRUE(items[0].filename == "2MB_data");
  9658. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9659. EXPECT_TRUE(items[1].name == "hello");
  9660. EXPECT_TRUE(items[1].content == "world");
  9661. EXPECT_TRUE(items[1].filename == "");
  9662. EXPECT_TRUE(items[1].content_type == "");
  9663. } else {
  9664. std::string body;
  9665. content_reader([&](const char *data, size_t data_length) {
  9666. body.append(data, data_length);
  9667. return true;
  9668. });
  9669. }
  9670. });
  9671. auto port = svr.bind_to_any_port("localhost");
  9672. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9673. auto se = detail::scope_exit([&] {
  9674. svr.stop();
  9675. t.join();
  9676. ASSERT_FALSE(svr.is_running());
  9677. });
  9678. svr.wait_until_ready();
  9679. {
  9680. std::string data(1024 * 1024 * 2, '&');
  9681. std::stringstream buffer;
  9682. buffer << data;
  9683. SSLClient cli("localhost", port);
  9684. cli.enable_server_certificate_verification(false);
  9685. UploadFormDataItems items{
  9686. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9687. {"hello", "world", "", ""},
  9688. };
  9689. auto res = cli.Put("/put", items);
  9690. ASSERT_TRUE(res);
  9691. ASSERT_EQ(StatusCode::OK_200, res->status);
  9692. }
  9693. }
  9694. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9696. svr.Put("/put_customboundary",
  9697. [&](const Request &req, const Response & /*res*/,
  9698. const ContentReader &content_reader) {
  9699. if (req.is_multipart_form_data()) {
  9700. std::vector<FormData> items;
  9701. content_reader(
  9702. [&](const FormData &file) {
  9703. items.push_back(file);
  9704. return true;
  9705. },
  9706. [&](const char *data, size_t data_length) {
  9707. items.back().content.append(data, data_length);
  9708. return true;
  9709. });
  9710. EXPECT_TRUE(std::string(items[0].name) == "document");
  9711. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9712. EXPECT_TRUE(items[0].filename == "2MB_data");
  9713. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9714. EXPECT_TRUE(items[1].name == "hello");
  9715. EXPECT_TRUE(items[1].content == "world");
  9716. EXPECT_TRUE(items[1].filename == "");
  9717. EXPECT_TRUE(items[1].content_type == "");
  9718. } else {
  9719. std::string body;
  9720. content_reader([&](const char *data, size_t data_length) {
  9721. body.append(data, data_length);
  9722. return true;
  9723. });
  9724. }
  9725. });
  9726. auto port = svr.bind_to_any_port("localhost");
  9727. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9728. auto se = detail::scope_exit([&] {
  9729. svr.stop();
  9730. t.join();
  9731. ASSERT_FALSE(svr.is_running());
  9732. });
  9733. svr.wait_until_ready();
  9734. {
  9735. std::string data(1024 * 1024 * 2, '&');
  9736. std::stringstream buffer;
  9737. buffer << data;
  9738. SSLClient cli("localhost", port);
  9739. cli.enable_server_certificate_verification(false);
  9740. UploadFormDataItems items{
  9741. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9742. {"hello", "world", "", ""},
  9743. };
  9744. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9745. ASSERT_TRUE(res);
  9746. ASSERT_EQ(StatusCode::OK_200, res->status);
  9747. }
  9748. }
  9749. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9750. std::string data(1024 * 1024 * 2, '&');
  9751. std::stringstream buffer;
  9752. buffer << data;
  9753. Client cli("https://localhost:8080");
  9754. cli.enable_server_certificate_verification(false);
  9755. UploadFormDataItems items{
  9756. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9757. {"hello", "world", "", ""},
  9758. };
  9759. for (const char &c : " \t\r\n") {
  9760. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9761. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9762. ASSERT_FALSE(res);
  9763. }
  9764. }
  9765. TEST(MultipartFormDataTest, AlternateFilename) {
  9766. auto handled = false;
  9767. Server svr;
  9768. svr.Post("/test", [&](const Request &req, Response &res) {
  9769. ASSERT_EQ(2u, req.form.files.size());
  9770. ASSERT_EQ(1u, req.form.fields.size());
  9771. // Test files
  9772. const auto &file1 = req.form.get_file("file1");
  9773. ASSERT_EQ("file1", file1.name);
  9774. ASSERT_EQ("A.txt", file1.filename);
  9775. ASSERT_EQ("text/plain", file1.content_type);
  9776. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9777. const auto &file2 = req.form.get_file("file2");
  9778. ASSERT_EQ("file2", file2.name);
  9779. ASSERT_EQ("a.html", file2.filename);
  9780. ASSERT_EQ("text/html", file2.content_type);
  9781. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9782. file2.content);
  9783. // Test text field
  9784. const auto &text = req.form.get_field("text");
  9785. ASSERT_EQ("text default", text);
  9786. res.set_content("ok", "text/plain");
  9787. handled = true;
  9788. });
  9789. thread t = thread([&] { svr.listen(HOST, PORT); });
  9790. auto se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. t.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. ASSERT_TRUE(handled);
  9795. });
  9796. svr.wait_until_ready();
  9797. auto req = "POST /test HTTP/1.1\r\n"
  9798. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9799. "Content-Length: 399\r\n"
  9800. "\r\n"
  9801. "----------\r\n"
  9802. "Content-Disposition: form-data; name=\"text\"\r\n"
  9803. "\r\n"
  9804. "text default\r\n"
  9805. "----------\r\n"
  9806. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9807. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9808. "Content-Type: text/plain\r\n"
  9809. "\r\n"
  9810. "Content of a.txt.\r\n"
  9811. "\r\n"
  9812. "----------\r\n"
  9813. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9814. "\"a.html\"\r\n"
  9815. "Content-Type: text/html\r\n"
  9816. "\r\n"
  9817. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9818. "\r\n"
  9819. "------------\r\n";
  9820. ASSERT_TRUE(send_request(1, req));
  9821. }
  9822. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9823. auto handled = false;
  9824. Server svr;
  9825. svr.Post("/test", [&](const Request &req, Response &res) {
  9826. // Case-insensitive "utf-8''" prefix with a long value
  9827. const auto &file = req.form.get_file("file1");
  9828. ASSERT_EQ("file1", file.name);
  9829. // 8000 chars exercises both the Content-Disposition parser and the
  9830. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9831. // Prior to the fix, std::regex_match on this header would cause O(N)
  9832. // stack recursion in libstdc++, leading to SIGSEGV.
  9833. std::string expected_filename(8000, 'A');
  9834. ASSERT_EQ(expected_filename, file.filename);
  9835. res.set_content("ok", "text/plain");
  9836. handled = true;
  9837. });
  9838. thread t = thread([&] { svr.listen(HOST, PORT); });
  9839. auto se = detail::scope_exit([&] {
  9840. svr.stop();
  9841. t.join();
  9842. ASSERT_FALSE(svr.is_running());
  9843. ASSERT_TRUE(handled);
  9844. });
  9845. svr.wait_until_ready();
  9846. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9847. // Regression test for GHSA-qq6v-r583-3h69
  9848. std::string long_filename(8000, 'A');
  9849. std::string body = "----------\r\n"
  9850. "Content-Disposition: form-data; name=\"file1\"; "
  9851. "filename*=\"Utf-8''" +
  9852. long_filename +
  9853. "\"\r\n"
  9854. "\r\n"
  9855. "hello\r\n"
  9856. "------------\r\n";
  9857. auto req = "POST /test HTTP/1.1\r\n"
  9858. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9859. "Content-Length: " +
  9860. std::to_string(body.size()) + "\r\n\r\n" + body;
  9861. ASSERT_TRUE(send_request(1, req));
  9862. }
  9863. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9864. auto handled = false;
  9865. Server svr;
  9866. svr.Post("/test", [&](const Request &req, Response &) {
  9867. ASSERT_EQ(2u, req.form.fields.size());
  9868. const auto &text1 = req.form.get_field("text1");
  9869. ASSERT_EQ("text1", text1);
  9870. const auto &text2 = req.form.get_field("text2");
  9871. ASSERT_EQ("text2", text2);
  9872. handled = true;
  9873. });
  9874. thread t = thread([&] { svr.listen(HOST, PORT); });
  9875. auto se = detail::scope_exit([&] {
  9876. svr.stop();
  9877. t.join();
  9878. ASSERT_FALSE(svr.is_running());
  9879. ASSERT_TRUE(handled);
  9880. });
  9881. svr.wait_until_ready();
  9882. auto req = "POST /test HTTP/1.1\r\n"
  9883. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9884. "Content-Length: 146\r\n"
  9885. "\r\n----------\r\n"
  9886. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9887. "\r\n"
  9888. "text1"
  9889. "\r\n----------\r\n"
  9890. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9891. "\r\n"
  9892. "text2"
  9893. "\r\n------------";
  9894. std::string response;
  9895. ASSERT_TRUE(send_request(1, req, &response));
  9896. ASSERT_EQ("200", response.substr(9, 3));
  9897. }
  9898. TEST(MultipartFormDataTest, ContentLength) {
  9899. auto handled = false;
  9900. Server svr;
  9901. svr.Post("/test", [&](const Request &req, Response &) {
  9902. ASSERT_EQ(2u, req.form.fields.size());
  9903. const auto &text1 = req.form.get_field("text1");
  9904. ASSERT_EQ("text1", text1);
  9905. const auto &text2 = req.form.get_field("text2");
  9906. ASSERT_EQ("text2", text2);
  9907. handled = true;
  9908. });
  9909. thread t = thread([&] { svr.listen(HOST, PORT); });
  9910. auto se = detail::scope_exit([&] {
  9911. svr.stop();
  9912. t.join();
  9913. ASSERT_FALSE(svr.is_running());
  9914. ASSERT_TRUE(handled);
  9915. });
  9916. svr.wait_until_ready();
  9917. auto req = "POST /test HTTP/1.1\r\n"
  9918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9919. "Content-Length: 167\r\n"
  9920. "\r\n----------\r\n"
  9921. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9922. "Content-Length: 5\r\n"
  9923. "\r\n"
  9924. "text1"
  9925. "\r\n----------\r\n"
  9926. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9927. "\r\n"
  9928. "text2"
  9929. "\r\n------------\r\n";
  9930. std::string response;
  9931. ASSERT_TRUE(send_request(1, req, &response));
  9932. ASSERT_EQ("200", response.substr(9, 3));
  9933. }
  9934. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9935. auto handled = false;
  9936. Server svr;
  9937. svr.Post("/test", [&](const Request &req, Response &) {
  9938. ASSERT_EQ(2u, req.form.fields.size());
  9939. const auto &text1 = req.form.get_field("text1");
  9940. ASSERT_EQ("text1", text1);
  9941. // TODO: Add header access for text fields if needed
  9942. const auto &text2 = req.form.get_field("text2");
  9943. ASSERT_EQ("text2", text2);
  9944. // TODO: Header access for text fields needs to be implemented
  9945. // auto &headers = it->second.headers;
  9946. // ASSERT_EQ(3U, headers.size());
  9947. // auto custom_header = headers.find("x-whatever");
  9948. // ASSERT_TRUE(custom_header != headers.end());
  9949. // ASSERT_NE("customvalue", custom_header->second);
  9950. // ASSERT_EQ("CustomValue", custom_header->second);
  9951. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9952. handled = true;
  9953. });
  9954. thread t = thread([&] { svr.listen(HOST, PORT); });
  9955. auto se = detail::scope_exit([&] {
  9956. svr.stop();
  9957. t.join();
  9958. ASSERT_FALSE(svr.is_running());
  9959. ASSERT_TRUE(handled);
  9960. });
  9961. svr.wait_until_ready();
  9962. auto req = "POST /test HTTP/1.1\r\n"
  9963. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9964. "Content-Length: 232\r\n"
  9965. "\r\n----------\r\n"
  9966. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9967. "Content-Length: 5\r\n"
  9968. "X-Test: 1\r\n"
  9969. "\r\n"
  9970. "text1"
  9971. "\r\n----------\r\n"
  9972. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9973. "Content-Type: text/plain\r\n"
  9974. "X-Whatever: CustomValue\r\n"
  9975. "\r\n"
  9976. "text2"
  9977. "\r\n------------\r\n"
  9978. "That should be disregarded. Not even read";
  9979. std::string response;
  9980. ASSERT_TRUE(send_request(1, req, &response));
  9981. ASSERT_EQ("200", response.substr(9, 3));
  9982. }
  9983. TEST(MultipartFormDataTest, LargeHeader) {
  9984. auto handled = false;
  9985. Server svr;
  9986. svr.Post("/test", [&](const Request &req, Response &) {
  9987. ASSERT_EQ(1u, req.form.fields.size());
  9988. const auto &text = req.form.get_field("name1");
  9989. ASSERT_EQ("text1", text);
  9990. handled = true;
  9991. });
  9992. thread t = thread([&] { svr.listen(HOST, PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. t.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. ASSERT_TRUE(handled);
  9998. });
  9999. svr.wait_until_ready();
  10000. auto boundary = std::string("cpp-httplib-multipart-data");
  10001. std::string content = "--" + boundary +
  10002. "\r\n"
  10003. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10004. "\r\n"
  10005. "text1\r\n"
  10006. "--" +
  10007. boundary + "--\r\n";
  10008. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10009. "Content-Type: multipart/form-data;boundary=" +
  10010. boundary +
  10011. "\r\n"
  10012. "Content-Length: " +
  10013. std::to_string(content.size()) +
  10014. "\r\n"
  10015. "Dummy-Header: ";
  10016. std::string header_suffix = "\r\n"
  10017. "\r\n";
  10018. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10019. size_t header_dummy_size =
  10020. read_buff_size -
  10021. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10022. auto header_dummy = std::string(header_dummy_size, '@');
  10023. auto req = header_prefix + header_dummy + header_suffix + content;
  10024. std::string response;
  10025. ASSERT_TRUE(send_request(1, req, &response));
  10026. ASSERT_EQ("200", response.substr(9, 3));
  10027. }
  10028. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10029. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10030. // (not chunked Transfer-Encoding) after the streaming refactor.
  10031. auto handled = false;
  10032. Server svr;
  10033. svr.Post("/upload", [&](const Request &req, Response &res) {
  10034. auto cl_it = req.headers.find("Content-Length");
  10035. EXPECT_TRUE(cl_it != req.headers.end());
  10036. auto te_it = req.headers.find("Transfer-Encoding");
  10037. EXPECT_TRUE(te_it == req.headers.end());
  10038. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10039. res.set_content("ok", "text/plain");
  10040. handled = true;
  10041. });
  10042. auto port = svr.bind_to_any_port(HOST);
  10043. auto t = thread([&] { svr.listen_after_bind(); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. t.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. ASSERT_TRUE(handled);
  10049. });
  10050. svr.wait_until_ready();
  10051. UploadFormDataItems items = {
  10052. {"field1", "hello", "", "text/plain"},
  10053. {"file1", "world", "test.txt", "application/octet-stream"},
  10054. };
  10055. Client cli(HOST, port);
  10056. auto res = cli.Post("/upload", {}, items);
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::OK_200, res->status);
  10059. }
  10060. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10061. // Verify that make_multipart_content_provider coalesces many small segments
  10062. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10063. constexpr size_t kItemCount = 1000;
  10064. UploadFormDataItems items;
  10065. items.reserve(kItemCount);
  10066. for (size_t i = 0; i < kItemCount; i++) {
  10067. items.push_back(
  10068. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10069. }
  10070. const std::string boundary = "----test-boundary";
  10071. auto content_length = detail::get_multipart_content_length(items, boundary);
  10072. auto provider = detail::make_multipart_content_provider(items, boundary);
  10073. // Drive the provider the same way write_content_with_progress does
  10074. size_t write_count = 0;
  10075. size_t total_bytes = 0;
  10076. DataSink sink;
  10077. size_t offset = 0;
  10078. sink.write = [&](const char *d, size_t l) -> bool {
  10079. (void)d;
  10080. write_count++;
  10081. total_bytes += l;
  10082. offset += l;
  10083. return true;
  10084. };
  10085. sink.is_writable = []() -> bool { return true; };
  10086. while (offset < content_length) {
  10087. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10088. }
  10089. EXPECT_EQ(content_length, total_bytes);
  10090. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10091. // With buffering into 64KB blocks, write_count should be much smaller.
  10092. auto segment_count = 3 * kItemCount + 1;
  10093. EXPECT_LT(write_count, segment_count / 10);
  10094. }
  10095. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10096. // Integration test: send many UploadFormDataItems and verify the server
  10097. // receives all of them correctly (#2410).
  10098. constexpr size_t kItemCount = 500;
  10099. auto handled = false;
  10100. Server svr;
  10101. svr.Post("/upload", [&](const Request &req, Response &res) {
  10102. EXPECT_EQ(kItemCount, req.form.fields.size());
  10103. for (size_t i = 0; i < kItemCount; i++) {
  10104. auto key = "field" + std::to_string(i);
  10105. auto val = "value" + std::to_string(i);
  10106. auto it = req.form.fields.find(key);
  10107. if (it != req.form.fields.end()) {
  10108. EXPECT_EQ(val, it->second.content);
  10109. } else {
  10110. ADD_FAILURE() << "Missing field: " << key;
  10111. }
  10112. }
  10113. res.set_content("ok", "text/plain");
  10114. handled = true;
  10115. });
  10116. auto port = svr.bind_to_any_port(HOST);
  10117. auto t = thread([&] { svr.listen_after_bind(); });
  10118. auto se = detail::scope_exit([&] {
  10119. svr.stop();
  10120. t.join();
  10121. ASSERT_FALSE(svr.is_running());
  10122. ASSERT_TRUE(handled);
  10123. });
  10124. svr.wait_until_ready();
  10125. UploadFormDataItems items;
  10126. items.reserve(kItemCount);
  10127. for (size_t i = 0; i < kItemCount; i++) {
  10128. items.push_back(
  10129. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10130. }
  10131. Client cli(HOST, port);
  10132. auto res = cli.Post("/upload", items);
  10133. ASSERT_TRUE(res);
  10134. EXPECT_EQ(StatusCode::OK_200, res->status);
  10135. }
  10136. TEST(MultipartFormDataTest, MakeFileProvider) {
  10137. // Verify make_file_provider sends a file's contents correctly.
  10138. const std::string file_content(4096, 'Z');
  10139. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10140. {
  10141. std::ofstream ofs(tmp_path, std::ios::binary);
  10142. ofs.write(file_content.data(),
  10143. static_cast<std::streamsize>(file_content.size()));
  10144. }
  10145. auto handled = false;
  10146. Server svr;
  10147. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10148. const ContentReader &content_reader) {
  10149. ASSERT_TRUE(req.is_multipart_form_data());
  10150. std::vector<FormData> items;
  10151. content_reader(
  10152. [&](const FormData &file) {
  10153. items.push_back(file);
  10154. return true;
  10155. },
  10156. [&](const char *data, size_t data_length) {
  10157. items.back().content.append(data, data_length);
  10158. return true;
  10159. });
  10160. ASSERT_EQ(1u, items.size());
  10161. EXPECT_EQ("myfile", items[0].name);
  10162. EXPECT_EQ("data.bin", items[0].filename);
  10163. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10164. EXPECT_EQ(file_content, items[0].content);
  10165. handled = true;
  10166. });
  10167. auto port = svr.bind_to_any_port(HOST);
  10168. auto t = thread([&] { svr.listen_after_bind(); });
  10169. auto se = detail::scope_exit([&] {
  10170. svr.stop();
  10171. t.join();
  10172. ASSERT_FALSE(svr.is_running());
  10173. ASSERT_TRUE(handled);
  10174. std::remove(tmp_path.c_str());
  10175. });
  10176. svr.wait_until_ready();
  10177. FormDataProviderItems providers;
  10178. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10179. "application/octet-stream"));
  10180. Client cli(HOST, port);
  10181. auto res = cli.Post("/upload", {}, {}, providers);
  10182. ASSERT_TRUE(res);
  10183. EXPECT_EQ(StatusCode::OK_200, res->status);
  10184. }
  10185. TEST(MakeFileBodyTest, Basic) {
  10186. const std::string file_content(4096, 'Z');
  10187. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10188. {
  10189. std::ofstream ofs(tmp_path, std::ios::binary);
  10190. ofs.write(file_content.data(),
  10191. static_cast<std::streamsize>(file_content.size()));
  10192. }
  10193. auto handled = false;
  10194. Server svr;
  10195. svr.Post("/upload", [&](const Request &req, Response &res) {
  10196. EXPECT_EQ(file_content, req.body);
  10197. handled = true;
  10198. res.status = StatusCode::OK_200;
  10199. });
  10200. auto port = svr.bind_to_any_port(HOST);
  10201. auto t = thread([&] { svr.listen_after_bind(); });
  10202. auto se = detail::scope_exit([&] {
  10203. svr.stop();
  10204. t.join();
  10205. ASSERT_FALSE(svr.is_running());
  10206. ASSERT_TRUE(handled);
  10207. std::remove(tmp_path.c_str());
  10208. });
  10209. svr.wait_until_ready();
  10210. auto fb = make_file_body(tmp_path);
  10211. ASSERT_GT(fb.first, 0u);
  10212. Client cli(HOST, port);
  10213. auto res =
  10214. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10215. ASSERT_TRUE(res);
  10216. EXPECT_EQ(StatusCode::OK_200, res->status);
  10217. }
  10218. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10219. static constexpr unsigned int number_of_tasks{1000000};
  10220. std::atomic_uint count{0};
  10221. std::unique_ptr<TaskQueue> task_queue{
  10222. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10223. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10224. auto queued = task_queue->enqueue(
  10225. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10226. EXPECT_TRUE(queued);
  10227. }
  10228. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10229. task_queue->shutdown();
  10230. #else
  10231. EXPECT_NO_THROW(task_queue->shutdown());
  10232. #endif
  10233. EXPECT_EQ(number_of_tasks, count.load());
  10234. }
  10235. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10236. static constexpr unsigned int number_of_tasks{1000000};
  10237. static constexpr unsigned int qlimit{2};
  10238. unsigned int queued_count{0};
  10239. std::atomic_uint count{0};
  10240. std::unique_ptr<TaskQueue> task_queue{
  10241. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10242. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10243. if (task_queue->enqueue(
  10244. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10245. queued_count++;
  10246. }
  10247. }
  10248. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10249. task_queue->shutdown();
  10250. #else
  10251. EXPECT_NO_THROW(task_queue->shutdown());
  10252. #endif
  10253. EXPECT_EQ(queued_count, count.load());
  10254. EXPECT_TRUE(queued_count <= number_of_tasks);
  10255. EXPECT_TRUE(queued_count >= qlimit);
  10256. }
  10257. TEST(TaskQueueTest, MaxQueuedRequests) {
  10258. static constexpr unsigned int qlimit{3};
  10259. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10260. std::condition_variable sem_cv;
  10261. std::mutex sem_mtx;
  10262. int credits = 0;
  10263. bool queued;
  10264. /* Fill up the queue with tasks that will block until we give them credits to
  10265. * complete. */
  10266. for (unsigned int n = 0; n <= qlimit;) {
  10267. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10268. std::unique_lock<std::mutex> lock(sem_mtx);
  10269. while (credits <= 0) {
  10270. sem_cv.wait(lock);
  10271. }
  10272. /* Consume the credit and signal the test code if they are all gone. */
  10273. if (--credits == 0) { sem_cv.notify_one(); }
  10274. });
  10275. if (n < qlimit) {
  10276. /* The first qlimit enqueues must succeed. */
  10277. EXPECT_TRUE(queued);
  10278. } else {
  10279. /* The last one will succeed only when the worker thread
  10280. * starts and dequeues the first blocking task. Although
  10281. * not necessary for the correctness of this test, we sleep for
  10282. * a short while to avoid busy waiting. */
  10283. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10284. }
  10285. if (queued) { n++; }
  10286. }
  10287. /* Further enqueues must fail since the queue is full. */
  10288. for (auto i = 0; i < 4; i++) {
  10289. queued = task_queue->enqueue([] {});
  10290. EXPECT_FALSE(queued);
  10291. }
  10292. /* Give the credits to allow the previous tasks to complete. */
  10293. {
  10294. std::unique_lock<std::mutex> lock(sem_mtx);
  10295. credits += qlimit + 1;
  10296. }
  10297. sem_cv.notify_all();
  10298. /* Wait for all the credits to be consumed. */
  10299. {
  10300. std::unique_lock<std::mutex> lock(sem_mtx);
  10301. while (credits > 0) {
  10302. sem_cv.wait(lock);
  10303. }
  10304. }
  10305. /* Check that we are able again to enqueue at least qlimit tasks. */
  10306. for (unsigned int i = 0; i < qlimit; i++) {
  10307. queued = task_queue->enqueue([] {});
  10308. EXPECT_TRUE(queued);
  10309. }
  10310. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10311. task_queue->shutdown();
  10312. #else
  10313. EXPECT_NO_THROW(task_queue->shutdown());
  10314. #endif
  10315. }
  10316. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10317. Server svr;
  10318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10319. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10320. });
  10321. svr.Get("/hello", [](const Request &req, Response &res) {
  10322. res.set_content(req.get_param_value("key"), "text/plain");
  10323. });
  10324. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10325. auto se = detail::scope_exit([&] {
  10326. svr.stop();
  10327. thread.join();
  10328. ASSERT_FALSE(svr.is_running());
  10329. });
  10330. svr.wait_until_ready();
  10331. {
  10332. Client cli(HOST, PORT);
  10333. cli.set_follow_location(true);
  10334. auto res = cli.Get("/");
  10335. ASSERT_TRUE(res);
  10336. EXPECT_EQ(StatusCode::OK_200, res->status);
  10337. EXPECT_EQ("val&key2=val2", res->body);
  10338. }
  10339. }
  10340. #endif
  10341. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10342. Server svr;
  10343. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10344. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10345. });
  10346. svr.Get("/hello", [](const Request &req, Response &res) {
  10347. res.set_content(req.get_param_value("key"), "text/plain");
  10348. });
  10349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10350. auto se = detail::scope_exit([&] {
  10351. svr.stop();
  10352. thread.join();
  10353. ASSERT_FALSE(svr.is_running());
  10354. });
  10355. svr.wait_until_ready();
  10356. {
  10357. Client cli(HOST, PORT);
  10358. cli.set_follow_location(true);
  10359. auto res = cli.Get("/");
  10360. ASSERT_TRUE(res);
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10363. }
  10364. }
  10365. #ifdef CPPHTTPLIB_SSL_ENABLED
  10366. TEST(RedirectTest, Issue2185_Online) {
  10367. SSLClient client("github.com");
  10368. client.set_follow_location(true);
  10369. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10370. "Coollab-Windows.zip");
  10371. ASSERT_TRUE(res);
  10372. EXPECT_EQ(StatusCode::OK_200, res->status);
  10373. EXPECT_EQ(9920427U, res->body.size());
  10374. }
  10375. #endif
  10376. TEST(VulnerabilityTest, CRLFInjection) {
  10377. Server svr;
  10378. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10379. res.set_content("Hello 1", "text/plain");
  10380. });
  10381. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10382. res.set_content("Hello 2", "text/plain");
  10383. });
  10384. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10385. res.set_content("Hello 3", "text/plain");
  10386. });
  10387. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10388. res.set_content("Hello 4", "text/plain");
  10389. });
  10390. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10391. for (const auto &x : req.headers) {
  10392. auto key = x.first;
  10393. EXPECT_STRNE("evil", key.c_str());
  10394. }
  10395. });
  10396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10397. auto se = detail::scope_exit([&] {
  10398. svr.stop();
  10399. thread.join();
  10400. ASSERT_FALSE(svr.is_running());
  10401. });
  10402. svr.wait_until_ready();
  10403. {
  10404. Client cli(HOST, PORT);
  10405. cli.Post("/test1", "A=B",
  10406. "application/x-www-form-urlencoded\r\nevil: hello1");
  10407. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10408. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10409. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10410. }
  10411. }
  10412. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10413. auto server_thread = std::thread([] {
  10414. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10415. default_socket_options(srv);
  10416. sockaddr_in addr{};
  10417. addr.sin_family = AF_INET;
  10418. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10419. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10420. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10421. ::listen(srv, 1);
  10422. sockaddr_in cli_addr{};
  10423. socklen_t cli_len = sizeof(cli_addr);
  10424. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10425. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10426. std::string buf_all;
  10427. char buf[2048];
  10428. ssize_t n;
  10429. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10430. buf_all.append(buf, static_cast<size_t>(n));
  10431. size_t pos;
  10432. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10433. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10434. auto e = request_block.find("\r\n");
  10435. if (e != std::string::npos) {
  10436. auto request_line = request_block.substr(0, e);
  10437. std::string msg =
  10438. "CRLF injection detected in request line: '" + request_line + "'";
  10439. EXPECT_FALSE(true) << msg;
  10440. }
  10441. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10442. ::send(cli,
  10443. #ifdef _WIN32
  10444. static_cast<const char *>(resp.c_str()),
  10445. static_cast<int>(resp.size()),
  10446. #else
  10447. resp.c_str(), resp.size(),
  10448. #endif
  10449. 0);
  10450. buf_all.erase(0, pos + 4);
  10451. }
  10452. }
  10453. detail::close_socket(cli);
  10454. detail::close_socket(srv);
  10455. });
  10456. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10457. auto cli = Client("127.0.0.1", PORT + 1);
  10458. auto headers = Headers{
  10459. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10460. {"Connection", "keep-alive"}};
  10461. auto res = cli.Get("/hi", headers);
  10462. EXPECT_FALSE(res);
  10463. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10464. server_thread.join();
  10465. }
  10466. TEST(PathParamsTest, StaticMatch) {
  10467. const auto pattern = "/users/all";
  10468. detail::PathParamsMatcher matcher(pattern);
  10469. Request request;
  10470. request.path = "/users/all";
  10471. ASSERT_TRUE(matcher.match(request));
  10472. std::unordered_map<std::string, std::string> expected_params = {};
  10473. EXPECT_EQ(request.path_params, expected_params);
  10474. }
  10475. TEST(PathParamsTest, StaticMismatch) {
  10476. const auto pattern = "/users/all";
  10477. detail::PathParamsMatcher matcher(pattern);
  10478. Request request;
  10479. request.path = "/users/1";
  10480. ASSERT_FALSE(matcher.match(request));
  10481. }
  10482. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10483. const auto pattern = "/users/:id/subscriptions";
  10484. detail::PathParamsMatcher matcher(pattern);
  10485. Request request;
  10486. request.path = "/users/42/subscriptions";
  10487. ASSERT_TRUE(matcher.match(request));
  10488. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10489. EXPECT_EQ(request.path_params, expected_params);
  10490. }
  10491. TEST(PathParamsTest, SingleParamInTheEnd) {
  10492. const auto pattern = "/users/:id";
  10493. detail::PathParamsMatcher matcher(pattern);
  10494. Request request;
  10495. request.path = "/users/24";
  10496. ASSERT_TRUE(matcher.match(request));
  10497. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10498. EXPECT_EQ(request.path_params, expected_params);
  10499. }
  10500. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10501. const auto pattern = "/users/:id/";
  10502. detail::PathParamsMatcher matcher(pattern);
  10503. Request request;
  10504. request.path = "/users/42/";
  10505. ASSERT_TRUE(matcher.match(request));
  10506. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10507. EXPECT_EQ(request.path_params, expected_params);
  10508. }
  10509. TEST(PathParamsTest, EmptyParam) {
  10510. const auto pattern = "/users/:id/";
  10511. detail::PathParamsMatcher matcher(pattern);
  10512. Request request;
  10513. request.path = "/users//";
  10514. ASSERT_TRUE(matcher.match(request));
  10515. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10516. EXPECT_EQ(request.path_params, expected_params);
  10517. }
  10518. TEST(PathParamsTest, FragmentMismatch) {
  10519. const auto pattern = "/users/:id/";
  10520. detail::PathParamsMatcher matcher(pattern);
  10521. Request request;
  10522. request.path = "/admins/24/";
  10523. ASSERT_FALSE(matcher.match(request));
  10524. }
  10525. TEST(PathParamsTest, ExtraFragments) {
  10526. const auto pattern = "/users/:id";
  10527. detail::PathParamsMatcher matcher(pattern);
  10528. Request request;
  10529. request.path = "/users/42/subscriptions";
  10530. ASSERT_FALSE(matcher.match(request));
  10531. }
  10532. TEST(PathParamsTest, MissingTrailingParam) {
  10533. const auto pattern = "/users/:id";
  10534. detail::PathParamsMatcher matcher(pattern);
  10535. Request request;
  10536. request.path = "/users";
  10537. ASSERT_FALSE(matcher.match(request));
  10538. }
  10539. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10540. const auto pattern = "/users/:id/subscriptions";
  10541. detail::PathParamsMatcher matcher(pattern);
  10542. Request request;
  10543. request.path = "/users/subscriptions";
  10544. ASSERT_FALSE(matcher.match(request));
  10545. }
  10546. TEST(PathParamsTest, MultipleParams) {
  10547. const auto pattern = "/users/:userid/subscriptions/:subid";
  10548. detail::PathParamsMatcher matcher(pattern);
  10549. Request request;
  10550. request.path = "/users/42/subscriptions/2";
  10551. ASSERT_TRUE(matcher.match(request));
  10552. std::unordered_map<std::string, std::string> expected_params = {
  10553. {"userid", "42"}, {"subid", "2"}};
  10554. EXPECT_EQ(request.path_params, expected_params);
  10555. }
  10556. TEST(PathParamsTest, SequenceOfParams) {
  10557. const auto pattern = "/values/:x/:y/:z";
  10558. detail::PathParamsMatcher matcher(pattern);
  10559. Request request;
  10560. request.path = "/values/1/2/3";
  10561. ASSERT_TRUE(matcher.match(request));
  10562. std::unordered_map<std::string, std::string> expected_params = {
  10563. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10564. EXPECT_EQ(request.path_params, expected_params);
  10565. }
  10566. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10567. const auto pattern = "/prefix:suffix";
  10568. detail::PathParamsMatcher matcher(pattern);
  10569. Request request;
  10570. request.path = "/prefix:suffix";
  10571. ASSERT_TRUE(matcher.match(request));
  10572. const std::unordered_map<std::string, std::string> expected_params = {};
  10573. EXPECT_EQ(request.path_params, expected_params);
  10574. }
  10575. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10576. // If ipv6 regex working, regex match codepath is taken.
  10577. // else port will default to 80 in Client impl
  10578. int clientImplMagicPort = 80;
  10579. int port = 4321;
  10580. // above ports must be different to avoid false negative
  10581. EXPECT_NE(clientImplMagicPort, port);
  10582. std::string ipV6TestURL = "http://[ff06::c3]";
  10583. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10584. CLIENT_PRIVATE_KEY_FILE);
  10585. EXPECT_EQ(cli.port(), port);
  10586. }
  10587. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10588. auto file_path = "./www/dir/index.html";
  10589. auto dir_path = "./www/dir";
  10590. detail::FileStat stat_file(file_path);
  10591. EXPECT_TRUE(stat_file.is_file());
  10592. EXPECT_FALSE(stat_file.is_dir());
  10593. detail::FileStat stat_dir(dir_path);
  10594. EXPECT_FALSE(stat_dir.is_file());
  10595. EXPECT_TRUE(stat_dir.is_dir());
  10596. }
  10597. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10598. // IPv4 with default HTTP port (80)
  10599. EXPECT_EQ("example.com",
  10600. detail::make_host_and_port_string("example.com", 80, false));
  10601. // IPv4 with default HTTPS port (443)
  10602. EXPECT_EQ("example.com",
  10603. detail::make_host_and_port_string("example.com", 443, true));
  10604. // IPv4 with non-default HTTP port
  10605. EXPECT_EQ("example.com:8080",
  10606. detail::make_host_and_port_string("example.com", 8080, false));
  10607. // IPv4 with non-default HTTPS port
  10608. EXPECT_EQ("example.com:8443",
  10609. detail::make_host_and_port_string("example.com", 8443, true));
  10610. // IPv6 with default HTTP port (80)
  10611. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10612. // IPv6 with default HTTPS port (443)
  10613. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10614. // IPv6 with non-default HTTP port
  10615. EXPECT_EQ("[::1]:8080",
  10616. detail::make_host_and_port_string("::1", 8080, false));
  10617. // IPv6 with non-default HTTPS port
  10618. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10619. // IPv6 full address with default port
  10620. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10621. detail::make_host_and_port_string(
  10622. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10623. // IPv6 full address with non-default port
  10624. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10625. detail::make_host_and_port_string(
  10626. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10627. // IPv6 localhost with non-default port
  10628. EXPECT_EQ("[::1]:3000",
  10629. detail::make_host_and_port_string("::1", 3000, false));
  10630. // IPv6 with zone ID (link-local address) with default port
  10631. EXPECT_EQ("[fe80::1%eth0]",
  10632. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10633. // IPv6 with zone ID (link-local address) with non-default port
  10634. EXPECT_EQ("[fe80::1%eth0]:8080",
  10635. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10636. // Edge case: Port 443 with is_ssl=false (should add port)
  10637. EXPECT_EQ("example.com:443",
  10638. detail::make_host_and_port_string("example.com", 443, false));
  10639. // Edge case: Port 80 with is_ssl=true (should add port)
  10640. EXPECT_EQ("example.com:80",
  10641. detail::make_host_and_port_string("example.com", 80, true));
  10642. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10643. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10644. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10645. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10646. // Security fix: Already bracketed IPv6 should not get double brackets
  10647. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10648. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10649. EXPECT_EQ("[::1]:8080",
  10650. detail::make_host_and_port_string("[::1]", 8080, false));
  10651. EXPECT_EQ("[2001:db8::1]:8080",
  10652. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10653. EXPECT_EQ("[fe80::1%eth0]",
  10654. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10655. EXPECT_EQ("[fe80::1%eth0]:8080",
  10656. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10657. // Edge case: Empty host (should return as-is)
  10658. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10659. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10660. // This is a known limitation but shouldn't crash
  10661. EXPECT_EQ("[host:name]",
  10662. detail::make_host_and_port_string("host:name", 80, false));
  10663. // Port number edge cases (no validation, but should not crash)
  10664. EXPECT_EQ("example.com:0",
  10665. detail::make_host_and_port_string("example.com", 0, false));
  10666. EXPECT_EQ("example.com:-1",
  10667. detail::make_host_and_port_string("example.com", -1, false));
  10668. EXPECT_EQ("example.com:65535",
  10669. detail::make_host_and_port_string("example.com", 65535, false));
  10670. EXPECT_EQ("example.com:65536",
  10671. detail::make_host_and_port_string("example.com", 65536, false));
  10672. }
  10673. #ifdef CPPHTTPLIB_SSL_ENABLED
  10674. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10675. httplib::SSLClient cli("roblox.com", 443);
  10676. cli.set_follow_location(true);
  10677. auto res = cli.Get("/");
  10678. ASSERT_TRUE(res);
  10679. EXPECT_EQ(StatusCode::OK_200, res->status);
  10680. }
  10681. #endif
  10682. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10683. Server svr;
  10684. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10685. EXPECT_EQ(res.status, 400);
  10686. });
  10687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10688. auto se = detail::scope_exit([&] {
  10689. svr.stop();
  10690. thread.join();
  10691. ASSERT_FALSE(svr.is_running());
  10692. });
  10693. svr.wait_until_ready();
  10694. Client cli(HOST, PORT);
  10695. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10696. }
  10697. TEST(InvalidHeaderCharsTest, is_field_name) {
  10698. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10699. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10700. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10701. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10702. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10703. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10704. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10705. EXPECT_FALSE(detail::fields::is_field_name(""));
  10706. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10707. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10708. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10709. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10710. }
  10711. TEST(InvalidHeaderCharsTest, is_field_value) {
  10712. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10713. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10714. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10715. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10716. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10717. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10718. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10719. EXPECT_TRUE(detail::fields::is_field_value(""));
  10720. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10721. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10722. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10723. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10724. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10725. }
  10726. TEST(InvalidHeaderCharsTest, OnServer) {
  10727. Server svr;
  10728. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10729. std::string header = "Not Set";
  10730. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10731. res.set_header(header, "value");
  10732. res.set_content("Page Content Page Content", "text/plain");
  10733. });
  10734. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10735. std::string header = "Not Set";
  10736. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10737. res.set_header("X-Test", header);
  10738. res.set_content("Page Content Page Content", "text/plain");
  10739. });
  10740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10741. auto se = detail::scope_exit([&] {
  10742. svr.stop();
  10743. thread.join();
  10744. ASSERT_FALSE(svr.is_running());
  10745. });
  10746. svr.wait_until_ready();
  10747. Client cli(HOST, PORT);
  10748. {
  10749. auto res = cli.Get(
  10750. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10751. ASSERT_TRUE(res);
  10752. EXPECT_EQ("Page Content Page Content", res->body);
  10753. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10754. }
  10755. {
  10756. auto res = cli.Get(
  10757. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10758. ASSERT_TRUE(res);
  10759. EXPECT_EQ("Page Content Page Content", res->body);
  10760. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10761. }
  10762. }
  10763. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10764. auto handled = false;
  10765. Server svr;
  10766. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10767. thread t = thread([&] { svr.listen(HOST, PORT); });
  10768. auto se = detail::scope_exit([&] {
  10769. svr.stop();
  10770. t.join();
  10771. ASSERT_FALSE(svr.is_running());
  10772. ASSERT_FALSE(handled);
  10773. });
  10774. svr.wait_until_ready();
  10775. auto req = "POST /test HTTP/1.1\r\n"
  10776. "Content-Length: x\r\n"
  10777. "\r\n";
  10778. std::string response;
  10779. ASSERT_TRUE(send_request(1, req, &response));
  10780. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10781. response.substr(0, response.find("\r\n")));
  10782. }
  10783. #ifndef _WIN32
  10784. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10785. static constexpr char reject[] = "Unauthorized";
  10786. static constexpr char accept[] = "Upload accepted";
  10787. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10788. Server svr;
  10789. svr.set_expect_100_continue_handler(
  10790. [](const Request & /*req*/, Response &res) {
  10791. res.status = StatusCode::Unauthorized_401;
  10792. res.set_content(reject, "text/plain");
  10793. return res.status;
  10794. });
  10795. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10796. res.set_content(accept, "text/plain");
  10797. });
  10798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10799. auto se = detail::scope_exit([&] {
  10800. svr.stop();
  10801. thread.join();
  10802. ASSERT_FALSE(svr.is_running());
  10803. });
  10804. svr.wait_until_ready();
  10805. {
  10806. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10807. curl_easy_init(), &curl_easy_cleanup};
  10808. ASSERT_NE(curl, nullptr);
  10809. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10810. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10811. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10812. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10813. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10814. &curl_slist_free_all};
  10815. ASSERT_NE(list, nullptr);
  10816. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10817. struct read_data {
  10818. size_t read_size;
  10819. size_t total_size;
  10820. } data = {0, total_size};
  10821. using read_callback_t =
  10822. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10823. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10824. void *userdata) -> size_t {
  10825. read_data *data = (read_data *)userdata;
  10826. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10827. std::fill_n(ptr, size * nmemb, 'A');
  10828. data->read_size += size * nmemb;
  10829. return size * nmemb;
  10830. };
  10831. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10832. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10833. std::vector<char> buffer;
  10834. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10835. using write_callback_t =
  10836. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10837. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10838. void *userdata) -> size_t {
  10839. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10840. buffer->reserve(buffer->size() + size * nmemb + 1);
  10841. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10842. return size * nmemb;
  10843. };
  10844. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10845. {
  10846. const auto res = curl_easy_perform(curl.get());
  10847. ASSERT_EQ(res, CURLE_OK);
  10848. }
  10849. {
  10850. auto response_code = long{};
  10851. const auto res =
  10852. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10853. ASSERT_EQ(res, CURLE_OK);
  10854. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10855. }
  10856. {
  10857. auto dl = curl_off_t{};
  10858. const auto res =
  10859. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10860. ASSERT_EQ(res, CURLE_OK);
  10861. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10862. }
  10863. {
  10864. buffer.push_back('\0');
  10865. ASSERT_STRCASEEQ(buffer.data(), reject);
  10866. }
  10867. }
  10868. }
  10869. #endif
  10870. template <typename S, typename C>
  10871. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10872. svr.Get("/stream", [&](const Request &, Response &res) {
  10873. auto data = new std::string("01234567890123456789");
  10874. res.set_content_provider(
  10875. data->size(), "text/plain",
  10876. [&, data](size_t offset, size_t length, DataSink &sink) {
  10877. const size_t DATA_CHUNK_SIZE = 4;
  10878. const auto &d = *data;
  10879. std::this_thread::sleep_for(std::chrono::seconds(1));
  10880. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10881. return true;
  10882. },
  10883. [data](bool success) {
  10884. EXPECT_FALSE(success);
  10885. delete data;
  10886. });
  10887. });
  10888. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10889. auto i = new size_t(0);
  10890. res.set_content_provider(
  10891. "text/plain",
  10892. [i](size_t, DataSink &sink) {
  10893. if (*i < 5) {
  10894. std::this_thread::sleep_for(std::chrono::seconds(1));
  10895. sink.write("abcd", 4);
  10896. (*i)++;
  10897. } else {
  10898. sink.done();
  10899. }
  10900. return true;
  10901. },
  10902. [i](bool success) {
  10903. EXPECT_FALSE(success);
  10904. delete i;
  10905. });
  10906. });
  10907. svr.Get("/chunked", [&](const Request &, Response &res) {
  10908. auto i = new size_t(0);
  10909. res.set_chunked_content_provider(
  10910. "text/plain",
  10911. [i](size_t, DataSink &sink) {
  10912. if (*i < 5) {
  10913. std::this_thread::sleep_for(std::chrono::seconds(1));
  10914. sink.os << "abcd";
  10915. (*i)++;
  10916. } else {
  10917. sink.done();
  10918. }
  10919. return true;
  10920. },
  10921. [i](bool success) {
  10922. EXPECT_FALSE(success);
  10923. delete i;
  10924. });
  10925. });
  10926. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10927. auto se = detail::scope_exit([&] {
  10928. svr.stop();
  10929. listen_thread.join();
  10930. ASSERT_FALSE(svr.is_running());
  10931. });
  10932. svr.wait_until_ready();
  10933. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10934. {
  10935. auto start = std::chrono::steady_clock::now();
  10936. auto res = cli.Get("/stream");
  10937. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10938. std::chrono::steady_clock::now() - start)
  10939. .count();
  10940. ASSERT_FALSE(res);
  10941. EXPECT_EQ(Error::Read, res.error());
  10942. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10943. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10944. }
  10945. {
  10946. auto start = std::chrono::steady_clock::now();
  10947. auto res = cli.Get("/stream_without_length");
  10948. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10949. std::chrono::steady_clock::now() - start)
  10950. .count();
  10951. ASSERT_FALSE(res);
  10952. EXPECT_EQ(Error::Read, res.error());
  10953. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10954. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10955. }
  10956. {
  10957. auto start = std::chrono::steady_clock::now();
  10958. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10959. EXPECT_EQ("abcd", string(data, data_length));
  10960. return true;
  10961. });
  10962. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10963. std::chrono::steady_clock::now() - start)
  10964. .count();
  10965. ASSERT_FALSE(res);
  10966. EXPECT_EQ(Error::Read, res.error());
  10967. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10968. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10969. }
  10970. }
  10971. TEST(MaxTimeoutTest, ContentStream) {
  10972. time_t timeout = 2000;
  10973. time_t threshold = 200;
  10974. Server svr;
  10975. Client cli("localhost", PORT);
  10976. max_timeout_test(svr, cli, timeout, threshold);
  10977. }
  10978. #ifdef CPPHTTPLIB_SSL_ENABLED
  10979. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10980. time_t timeout = 2000;
  10981. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10983. SSLClient cli("localhost", PORT);
  10984. cli.enable_server_certificate_verification(false);
  10985. max_timeout_test(svr, cli, timeout, threshold);
  10986. }
  10987. #endif
  10988. class EventDispatcher {
  10989. public:
  10990. EventDispatcher() {}
  10991. bool wait_event(DataSink *sink) {
  10992. unique_lock<mutex> lk(m_);
  10993. int id = id_;
  10994. // Wait with timeout to prevent hanging if client disconnects
  10995. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10996. [&] { return cid_ == id; })) {
  10997. return false; // Timeout occurred
  10998. }
  10999. sink->write(message_.data(), message_.size());
  11000. return true;
  11001. }
  11002. void send_event(const string &message) {
  11003. lock_guard<mutex> lk(m_);
  11004. cid_ = id_++;
  11005. message_ = message;
  11006. cv_.notify_all();
  11007. }
  11008. private:
  11009. mutex m_;
  11010. condition_variable cv_;
  11011. atomic_int id_{0};
  11012. atomic_int cid_{-1};
  11013. string message_;
  11014. };
  11015. TEST(ClientInThreadTest, Issue2068) {
  11016. EventDispatcher ed;
  11017. Server svr;
  11018. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11019. res.set_chunked_content_provider("text/event-stream",
  11020. [&](size_t /*offset*/, DataSink &sink) {
  11021. return ed.wait_event(&sink);
  11022. });
  11023. });
  11024. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11025. svr.wait_until_ready();
  11026. thread event_thread([&] {
  11027. int id = 0;
  11028. while (svr.is_running()) {
  11029. this_thread::sleep_for(chrono::milliseconds(500));
  11030. std::stringstream ss;
  11031. ss << "data: " << id << "\n\n";
  11032. ed.send_event(ss.str());
  11033. id++;
  11034. }
  11035. });
  11036. auto se = detail::scope_exit([&] {
  11037. svr.stop();
  11038. listen_thread.join();
  11039. event_thread.join();
  11040. ASSERT_FALSE(svr.is_running());
  11041. });
  11042. {
  11043. auto client = detail::make_unique<Client>(HOST, PORT);
  11044. client->set_read_timeout(std::chrono::minutes(10));
  11045. std::atomic<bool> stop{false};
  11046. std::thread t([&] {
  11047. client->Get("/event1",
  11048. [&](const char *, size_t) -> bool { return !stop; });
  11049. });
  11050. std::this_thread::sleep_for(std::chrono::seconds(2));
  11051. stop = true;
  11052. client->stop();
  11053. t.join();
  11054. // Reset client after thread has finished
  11055. client.reset();
  11056. }
  11057. }
  11058. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11059. auto handled = false;
  11060. Server svr;
  11061. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11062. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11063. auto se = detail::scope_exit([&] {
  11064. svr.stop();
  11065. t.join();
  11066. ASSERT_FALSE(svr.is_running());
  11067. ASSERT_FALSE(handled);
  11068. });
  11069. svr.wait_until_ready();
  11070. // Two Content-Length headers with different values — must be rejected
  11071. auto req = "POST /test HTTP/1.1\r\n"
  11072. "Content-Length: 5\r\n"
  11073. "Content-Length: 10\r\n"
  11074. "\r\n"
  11075. "hello";
  11076. std::string response;
  11077. ASSERT_TRUE(send_request(1, req, &response));
  11078. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11079. response.substr(0, response.find("\r\n")));
  11080. }
  11081. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11082. auto handled = false;
  11083. Server svr;
  11084. svr.Post("/test", [&](const Request &, Response &res) {
  11085. handled = true;
  11086. res.set_content("ok", "text/plain");
  11087. });
  11088. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11089. auto se = detail::scope_exit([&] {
  11090. svr.stop();
  11091. t.join();
  11092. ASSERT_FALSE(svr.is_running());
  11093. ASSERT_TRUE(handled);
  11094. });
  11095. svr.wait_until_ready();
  11096. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11097. auto req = "POST /test HTTP/1.1\r\n"
  11098. "Content-Length: 5\r\n"
  11099. "Content-Length: 5\r\n"
  11100. "\r\n"
  11101. "hello";
  11102. std::string response;
  11103. ASSERT_TRUE(send_request(1, req, &response));
  11104. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11105. }
  11106. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11107. Server svr;
  11108. svr.Get("/", [](const Request &req, Response &res) {
  11109. EXPECT_EQ(2U, req.trailers.size());
  11110. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11111. // Denied
  11112. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11113. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11114. // Accepted
  11115. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11116. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11117. EXPECT_TRUE(req.has_trailer("X-World"));
  11118. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11119. res.set_content("ok", "text/plain");
  11120. });
  11121. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11122. auto se = detail::scope_exit([&] {
  11123. svr.stop();
  11124. t.join();
  11125. ASSERT_FALSE(svr.is_running());
  11126. });
  11127. svr.wait_until_ready();
  11128. const std::string req = "GET / HTTP/1.1\r\n"
  11129. "Transfer-Encoding: chunked\r\n"
  11130. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11131. "\r\n"
  11132. "0\r\n"
  11133. "Content-Length: 10\r\n"
  11134. "Host: internal.local\r\n"
  11135. "Content-Type: malicious/content\r\n"
  11136. "Cookie: any\r\n"
  11137. "Set-Cookie: any\r\n"
  11138. "X-Forwarded-For: attacker.com\r\n"
  11139. "X-Real-Ip: 1.1.1.1\r\n"
  11140. "X-Hello: hello\r\n"
  11141. "X-World: world\r\n"
  11142. "\r\n";
  11143. std::string res;
  11144. ASSERT_TRUE(send_request(1, req, &res));
  11145. }
  11146. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11147. Server svr;
  11148. std::string observed_remote_addr;
  11149. std::string observed_xff;
  11150. svr.Get("/ip", [&](const Request &req, Response &res) {
  11151. observed_remote_addr = req.remote_addr;
  11152. observed_xff = req.get_header_value("X-Forwarded-For");
  11153. res.set_content("ok", "text/plain");
  11154. });
  11155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. Client cli(HOST, PORT);
  11163. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11164. ASSERT_TRUE(res);
  11165. EXPECT_EQ(StatusCode::OK_200, res->status);
  11166. EXPECT_EQ(observed_xff, "203.0.113.66");
  11167. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11168. observed_remote_addr == "127.0.0.1");
  11169. }
  11170. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11171. Server svr;
  11172. svr.set_trusted_proxies({"203.0.113.66"});
  11173. std::string observed_remote_addr;
  11174. std::string observed_xff;
  11175. svr.Get("/ip", [&](const Request &req, Response &res) {
  11176. observed_remote_addr = req.remote_addr;
  11177. observed_xff = req.get_header_value("X-Forwarded-For");
  11178. res.set_content("ok", "text/plain");
  11179. });
  11180. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11181. auto se = detail::scope_exit([&] {
  11182. svr.stop();
  11183. t.join();
  11184. ASSERT_FALSE(svr.is_running());
  11185. });
  11186. svr.wait_until_ready();
  11187. Client cli(HOST, PORT);
  11188. auto res = cli.Get("/ip");
  11189. ASSERT_TRUE(res);
  11190. EXPECT_EQ(StatusCode::OK_200, res->status);
  11191. EXPECT_EQ(observed_xff, "");
  11192. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11193. observed_remote_addr == "127.0.0.1");
  11194. }
  11195. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11196. Server svr;
  11197. svr.set_trusted_proxies({"203.0.113.66"});
  11198. std::string observed_remote_addr;
  11199. std::string observed_xff;
  11200. svr.Get("/ip", [&](const Request &req, Response &res) {
  11201. observed_remote_addr = req.remote_addr;
  11202. observed_xff = req.get_header_value("X-Forwarded-For");
  11203. res.set_content("ok", "text/plain");
  11204. });
  11205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11206. auto se = detail::scope_exit([&] {
  11207. svr.stop();
  11208. t.join();
  11209. ASSERT_FALSE(svr.is_running());
  11210. });
  11211. svr.wait_until_ready();
  11212. Client cli(HOST, PORT);
  11213. auto res =
  11214. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11215. ASSERT_TRUE(res);
  11216. EXPECT_EQ(StatusCode::OK_200, res->status);
  11217. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11218. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11219. }
  11220. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11221. Server svr;
  11222. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11223. std::string observed_remote_addr;
  11224. std::string observed_xff;
  11225. svr.Get("/ip", [&](const Request &req, Response &res) {
  11226. observed_remote_addr = req.remote_addr;
  11227. observed_xff = req.get_header_value("X-Forwarded-For");
  11228. res.set_content("ok", "text/plain");
  11229. });
  11230. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11231. auto se = detail::scope_exit([&] {
  11232. svr.stop();
  11233. t.join();
  11234. ASSERT_FALSE(svr.is_running());
  11235. });
  11236. svr.wait_until_ready();
  11237. Client cli(HOST, PORT);
  11238. auto res = cli.Get(
  11239. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11240. ASSERT_TRUE(res);
  11241. EXPECT_EQ(StatusCode::OK_200, res->status);
  11242. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11243. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11244. }
  11245. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11246. Server svr;
  11247. svr.set_trusted_proxies({"192.0.2.45"});
  11248. std::string observed_remote_addr;
  11249. std::string observed_xff;
  11250. svr.Get("/ip", [&](const Request &req, Response &res) {
  11251. observed_remote_addr = req.remote_addr;
  11252. observed_xff = req.get_header_value("X-Forwarded-For");
  11253. res.set_content("ok", "text/plain");
  11254. });
  11255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11256. auto se = detail::scope_exit([&] {
  11257. svr.stop();
  11258. t.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. });
  11261. svr.wait_until_ready();
  11262. Client cli(HOST, PORT);
  11263. auto res =
  11264. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11265. ASSERT_TRUE(res);
  11266. EXPECT_EQ(StatusCode::OK_200, res->status);
  11267. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11268. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11269. }
  11270. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11271. Server svr;
  11272. svr.set_trusted_proxies({"192.0.2.45"});
  11273. std::string observed_remote_addr;
  11274. std::string observed_xff;
  11275. svr.Get("/ip", [&](const Request &req, Response &res) {
  11276. observed_remote_addr = req.remote_addr;
  11277. observed_xff = req.get_header_value("X-Forwarded-For");
  11278. res.set_content("ok", "text/plain");
  11279. });
  11280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11281. auto se = detail::scope_exit([&] {
  11282. svr.stop();
  11283. t.join();
  11284. ASSERT_FALSE(svr.is_running());
  11285. });
  11286. svr.wait_until_ready();
  11287. Client cli(HOST, PORT);
  11288. auto res = cli.Get(
  11289. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11290. ASSERT_TRUE(res);
  11291. EXPECT_EQ(StatusCode::OK_200, res->status);
  11292. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11293. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11294. }
  11295. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11296. Server svr;
  11297. svr.set_trusted_proxies({"192.0.2.45"});
  11298. std::string observed_remote_addr;
  11299. std::string observed_xff;
  11300. svr.Get("/ip", [&](const Request &req, Response &res) {
  11301. observed_remote_addr = req.remote_addr;
  11302. observed_xff = req.get_header_value("X-Forwarded-For");
  11303. res.set_content("ok", "text/plain");
  11304. });
  11305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11306. auto se = detail::scope_exit([&] {
  11307. svr.stop();
  11308. t.join();
  11309. ASSERT_FALSE(svr.is_running());
  11310. });
  11311. svr.wait_until_ready();
  11312. std::string raw_req =
  11313. "GET /ip HTTP/1.1\r\n"
  11314. "Host: localhost\r\n"
  11315. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11316. "Connection: close\r\n"
  11317. "\r\n";
  11318. std::string out;
  11319. ASSERT_TRUE(send_request(5, raw_req, &out));
  11320. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11321. // Header parser trims surrounding whitespace of the header value
  11322. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11323. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11324. }
  11325. #ifndef _WIN32
  11326. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11327. Server svr;
  11328. svr.Post("/post", [&](const Request &req, Response &res) {
  11329. res.set_content(req.body, "text/plain");
  11330. });
  11331. svr.Put("/put", [&](const Request &req, Response &res) {
  11332. res.set_content(req.body, "text/plain");
  11333. });
  11334. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11335. res.set_content(req.body, "text/plain");
  11336. });
  11337. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11338. res.set_content(req.body, "text/plain");
  11339. });
  11340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. std::string resp;
  11348. // POST without Content-Length
  11349. ASSERT_TRUE(send_request(5,
  11350. "POST /post HTTP/1.1\r\n"
  11351. "Host: localhost\r\n"
  11352. "Connection: close\r\n"
  11353. "\r\n",
  11354. &resp));
  11355. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11356. // PUT without Content-Length
  11357. resp.clear();
  11358. ASSERT_TRUE(send_request(5,
  11359. "PUT /put HTTP/1.1\r\n"
  11360. "Host: localhost\r\n"
  11361. "Connection: close\r\n"
  11362. "\r\n",
  11363. &resp));
  11364. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11365. // PATCH without Content-Length
  11366. resp.clear();
  11367. ASSERT_TRUE(send_request(5,
  11368. "PATCH /patch HTTP/1.1\r\n"
  11369. "Host: localhost\r\n"
  11370. "Connection: close\r\n"
  11371. "\r\n",
  11372. &resp));
  11373. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11374. // DELETE without Content-Length
  11375. resp.clear();
  11376. ASSERT_TRUE(send_request(5,
  11377. "DELETE /delete HTTP/1.1\r\n"
  11378. "Host: localhost\r\n"
  11379. "Connection: close\r\n"
  11380. "\r\n",
  11381. &resp));
  11382. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11383. }
  11384. #endif
  11385. //==============================================================================
  11386. // open_stream() Tests
  11387. //==============================================================================
  11388. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11389. std::string result;
  11390. char buf[8192];
  11391. ssize_t n;
  11392. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11393. result.append(buf, static_cast<size_t>(n));
  11394. }
  11395. return result;
  11396. }
  11397. // Mock stream for unit tests
  11398. class MockStream : public Stream {
  11399. public:
  11400. std::string data;
  11401. size_t pos = 0;
  11402. ssize_t error_after = -1; // -1 = no error
  11403. explicit MockStream(const std::string &d, ssize_t err = -1)
  11404. : data(d), error_after(err) {}
  11405. bool is_readable() const override { return true; }
  11406. bool wait_readable() const override { return true; }
  11407. bool wait_writable() const override { return true; }
  11408. ssize_t read(char *ptr, size_t size) override {
  11409. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11410. if (pos >= data.size()) return 0;
  11411. size_t limit =
  11412. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11413. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11414. std::memcpy(ptr, data.data() + pos, to_read);
  11415. pos += to_read;
  11416. return static_cast<ssize_t>(to_read);
  11417. }
  11418. ssize_t write(const char *, size_t) override { return -1; }
  11419. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11420. ip = "127.0.0.1";
  11421. port = 0;
  11422. }
  11423. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11424. ip = "127.0.0.1";
  11425. port = 0;
  11426. }
  11427. socket_t socket() const override { return INVALID_SOCKET; }
  11428. time_t duration() const override { return 0; }
  11429. };
  11430. TEST(StreamHandleTest, Basic) {
  11431. ClientImpl::StreamHandle handle;
  11432. EXPECT_FALSE(handle.is_valid());
  11433. handle.response = detail::make_unique<Response>();
  11434. handle.error = Error::Connection;
  11435. EXPECT_FALSE(handle.is_valid());
  11436. handle.error = Error::Success;
  11437. EXPECT_TRUE(handle.is_valid());
  11438. }
  11439. TEST(BodyReaderTest, Basic) {
  11440. MockStream stream("Hello, World!");
  11441. detail::BodyReader reader;
  11442. reader.stream = &stream;
  11443. reader.content_length = 13;
  11444. char buf[32];
  11445. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11446. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11447. EXPECT_TRUE(reader.eof);
  11448. }
  11449. TEST(BodyReaderTest, NoStream) {
  11450. detail::BodyReader reader;
  11451. char buf[32];
  11452. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11453. EXPECT_EQ(Error::Connection, reader.last_error);
  11454. }
  11455. TEST(BodyReaderTest, Error) {
  11456. MockStream stream("Hello, World!", 5);
  11457. detail::BodyReader reader;
  11458. reader.stream = &stream;
  11459. reader.content_length = 13;
  11460. char buf[32];
  11461. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11462. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11463. EXPECT_EQ(Error::Read, reader.last_error);
  11464. }
  11465. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11466. // Mock-based StreamHandle tests relying on private internals are removed.
  11467. class OpenStreamTest : public ::testing::Test {
  11468. protected:
  11469. void SetUp() override {
  11470. svr_.Get("/hello", [](const Request &, Response &res) {
  11471. res.set_content("Hello World!", "text/plain");
  11472. });
  11473. svr_.Get("/large", [](const Request &, Response &res) {
  11474. res.set_content(std::string(10000, 'X'), "text/plain");
  11475. });
  11476. svr_.Get("/chunked", [](const Request &, Response &res) {
  11477. res.set_chunked_content_provider("text/plain",
  11478. [](size_t offset, DataSink &sink) {
  11479. if (offset < 15) {
  11480. sink.write("chunk", 5);
  11481. return true;
  11482. }
  11483. sink.done();
  11484. return true;
  11485. });
  11486. });
  11487. svr_.Get("/compressible", [](const Request &, Response &res) {
  11488. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11489. DataSink &sink) {
  11490. if (offset < 100 * 1024) {
  11491. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11492. sink.write(chunk.data(), chunk.size());
  11493. return true;
  11494. }
  11495. sink.done();
  11496. return true;
  11497. });
  11498. });
  11499. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11500. [](const Request & /*req*/, Response &res) {
  11501. auto i = new int(0);
  11502. res.set_header("Trailer", "Content-Length, X-Allowed");
  11503. res.set_chunked_content_provider(
  11504. "text/plain",
  11505. [i](size_t /*offset*/, DataSink &sink) {
  11506. switch (*i) {
  11507. case 0: sink.os << "123"; break;
  11508. case 1: sink.os << "456"; break;
  11509. case 2: sink.os << "789"; break;
  11510. case 3: {
  11511. sink.done_with_trailer(
  11512. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11513. } break;
  11514. }
  11515. (*i)++;
  11516. return true;
  11517. },
  11518. [i](bool success) {
  11519. EXPECT_TRUE(success);
  11520. delete i;
  11521. });
  11522. });
  11523. // Echo headers endpoint for header-related tests
  11524. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11525. std::string body;
  11526. for (const auto &h : req.headers) {
  11527. body.append(h.first);
  11528. body.push_back(':');
  11529. body.append(h.second);
  11530. body.push_back('\n');
  11531. }
  11532. res.set_content(body, "text/plain");
  11533. });
  11534. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11535. std::string body;
  11536. for (const auto &h : req.headers) {
  11537. body.append(h.first);
  11538. body.push_back(':');
  11539. body.append(h.second);
  11540. body.push_back('\n');
  11541. }
  11542. res.set_content(body, "text/plain");
  11543. });
  11544. port_ = svr_.bind_to_any_port("127.0.0.1");
  11545. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11546. svr_.wait_until_ready();
  11547. }
  11548. void TearDown() override {
  11549. svr_.stop();
  11550. if (thread_.joinable()) thread_.join();
  11551. }
  11552. Server svr_;
  11553. std::thread thread_;
  11554. int port_ = 0;
  11555. };
  11556. TEST_F(OpenStreamTest, Basic) {
  11557. Client cli("127.0.0.1", port_);
  11558. auto handle = cli.open_stream("GET", "/hello");
  11559. EXPECT_TRUE(handle.is_valid());
  11560. EXPECT_EQ("Hello World!", read_all(handle));
  11561. }
  11562. TEST_F(OpenStreamTest, SmallBuffer) {
  11563. Client cli("127.0.0.1", port_);
  11564. auto handle = cli.open_stream("GET", "/hello");
  11565. std::string result;
  11566. char buf[4];
  11567. ssize_t n;
  11568. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11569. result.append(buf, static_cast<size_t>(n));
  11570. EXPECT_EQ("Hello World!", result);
  11571. }
  11572. TEST_F(OpenStreamTest, DefaultHeaders) {
  11573. Client cli("127.0.0.1", port_);
  11574. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11575. {
  11576. auto handle = cli.open_stream("GET", "/echo-headers");
  11577. ASSERT_TRUE(handle.is_valid());
  11578. auto body = read_all(handle);
  11579. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11580. std::string::npos);
  11581. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11582. std::string::npos);
  11583. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11584. }
  11585. // open_stream POST with body and no explicit content_type should NOT add
  11586. // text/plain Content-Type (behavior differs from non-streaming path), but
  11587. // should include Content-Length
  11588. {
  11589. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11590. ASSERT_TRUE(handle.is_valid());
  11591. auto body = read_all(handle);
  11592. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11593. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11594. }
  11595. // open_stream POST with explicit Content-Type should preserve it
  11596. {
  11597. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11598. {{"Content-Type", "application/custom"}},
  11599. "{}", "application/custom");
  11600. ASSERT_TRUE(handle.is_valid());
  11601. auto body = read_all(handle);
  11602. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11603. }
  11604. // User-specified User-Agent must not be overwritten for stream API
  11605. {
  11606. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11607. {{"User-Agent", "MyAgent/1.2"}});
  11608. ASSERT_TRUE(handle.is_valid());
  11609. auto body = read_all(handle);
  11610. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11611. }
  11612. }
  11613. TEST_F(OpenStreamTest, Large) {
  11614. Client cli("127.0.0.1", port_);
  11615. auto handle = cli.open_stream("GET", "/large");
  11616. EXPECT_EQ(10000u, read_all(handle).size());
  11617. }
  11618. TEST_F(OpenStreamTest, ConnectionError) {
  11619. Client cli("127.0.0.1", 9999);
  11620. auto handle = cli.open_stream("GET", "/hello");
  11621. EXPECT_FALSE(handle.is_valid());
  11622. }
  11623. TEST_F(OpenStreamTest, Chunked) {
  11624. Client cli("127.0.0.1", port_);
  11625. auto handle = cli.open_stream("GET", "/chunked");
  11626. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11627. "Transfer-Encoding") == "chunked");
  11628. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11629. }
  11630. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11631. Client cli("127.0.0.1", port_);
  11632. auto handle =
  11633. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11634. ASSERT_TRUE(handle.is_valid());
  11635. // Consume body to allow trailers to be received/parsed
  11636. auto body = read_all(handle);
  11637. // Explicitly parse trailers (ensure trailers are available for assertion)
  11638. handle.parse_trailers_if_needed();
  11639. EXPECT_EQ(std::string("123456789"), body);
  11640. // The response should include a Trailer header declaring both names
  11641. ASSERT_TRUE(handle.response);
  11642. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11643. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11644. handle.response->get_header_value("Trailer"));
  11645. // Prohibited trailer must not be present
  11646. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11647. // Allowed trailer should be present
  11648. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11649. EXPECT_EQ(std::string("yes"),
  11650. handle.response->get_trailer_value("X-Allowed"));
  11651. // Verify trailers are NOT present as regular headers
  11652. EXPECT_EQ(std::string(""),
  11653. handle.response->get_header_value("Content-Length"));
  11654. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11655. }
  11656. static std::thread serve_single_response(std::promise<int> &port_promise,
  11657. const std::string &response) {
  11658. return std::thread([&port_promise, response] {
  11659. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11660. default_socket_options(srv);
  11661. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11662. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11663. sockaddr_in addr{};
  11664. addr.sin_family = AF_INET;
  11665. addr.sin_port = htons(0); // Let OS assign a free port
  11666. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11667. int opt = 1;
  11668. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11669. #ifdef _WIN32
  11670. reinterpret_cast<const char *>(&opt),
  11671. #else
  11672. &opt,
  11673. #endif
  11674. sizeof(opt));
  11675. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11676. ::listen(srv, 1) != 0) {
  11677. port_promise.set_value(-1);
  11678. detail::close_socket(srv);
  11679. return;
  11680. }
  11681. socklen_t addr_len = sizeof(addr);
  11682. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11683. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11684. sockaddr_in cli_addr{};
  11685. socklen_t cli_len = sizeof(cli_addr);
  11686. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11687. if (cli != INVALID_SOCKET) {
  11688. char buf[4096];
  11689. ::recv(cli, buf, sizeof(buf), 0);
  11690. ::send(cli,
  11691. #ifdef _WIN32
  11692. static_cast<const char *>(response.c_str()),
  11693. static_cast<int>(response.size()),
  11694. #else
  11695. response.c_str(), response.size(),
  11696. #endif
  11697. 0);
  11698. detail::close_socket(cli);
  11699. }
  11700. detail::close_socket(srv);
  11701. });
  11702. }
  11703. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11704. #ifndef _WIN32
  11705. signal(SIGPIPE, SIG_IGN);
  11706. #endif
  11707. std::promise<int> port_promise;
  11708. auto port_future = port_promise.get_future();
  11709. auto server_thread =
  11710. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11711. "Content-Type: text/plain\r\n"
  11712. "Content-Length: not-a-number\r\n"
  11713. "Connection: close\r\n"
  11714. "\r\n"
  11715. "hello");
  11716. auto port = port_future.get();
  11717. ASSERT_GT(port, 0);
  11718. Client cli("127.0.0.1", port);
  11719. auto handle = cli.open_stream("GET", "/");
  11720. EXPECT_FALSE(handle.is_valid());
  11721. server_thread.join();
  11722. }
  11723. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11724. #ifndef _WIN32
  11725. signal(SIGPIPE, SIG_IGN);
  11726. #endif
  11727. std::promise<int> port_promise;
  11728. auto port_future = port_promise.get_future();
  11729. auto server_thread = serve_single_response(
  11730. port_promise, "HTTP/1.1 200 OK\r\n"
  11731. "Content-Type: text/plain\r\n"
  11732. "Content-Length: 99999999999999999999999999\r\n"
  11733. "Connection: close\r\n"
  11734. "\r\n"
  11735. "hello");
  11736. auto port = port_future.get();
  11737. ASSERT_GT(port, 0);
  11738. // Before the fix, std::stoull would throw std::out_of_range here and
  11739. // crash the process. After the fix, strtoull silently clamps to
  11740. // ULLONG_MAX so the stream opens without crashing. The important thing
  11741. // is that the process does NOT terminate.
  11742. Client cli("127.0.0.1", port);
  11743. auto handle = cli.open_stream("GET", "/");
  11744. EXPECT_TRUE(handle.is_valid());
  11745. server_thread.join();
  11746. }
  11747. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11748. TEST_F(OpenStreamTest, Gzip) {
  11749. Client cli("127.0.0.1", port_);
  11750. auto handle = cli.open_stream("GET", "/compressible", {},
  11751. {{"Accept-Encoding", "gzip"}});
  11752. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11753. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11754. }
  11755. #endif
  11756. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11757. TEST_F(OpenStreamTest, Brotli) {
  11758. Client cli("127.0.0.1", port_);
  11759. auto handle =
  11760. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11761. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11762. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11763. }
  11764. #endif
  11765. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11766. TEST_F(OpenStreamTest, Zstd) {
  11767. Client cli("127.0.0.1", port_);
  11768. auto handle = cli.open_stream("GET", "/compressible", {},
  11769. {{"Accept-Encoding", "zstd"}});
  11770. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11771. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11772. }
  11773. #endif
  11774. #ifdef CPPHTTPLIB_SSL_ENABLED
  11775. class SSLOpenStreamTest : public ::testing::Test {
  11776. protected:
  11777. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11778. void SetUp() override {
  11779. svr_.Get("/hello", [](const Request &, Response &res) {
  11780. res.set_content("Hello SSL World!", "text/plain");
  11781. });
  11782. svr_.Get("/chunked", [](const Request &, Response &res) {
  11783. res.set_chunked_content_provider("text/plain",
  11784. [](size_t offset, DataSink &sink) {
  11785. if (offset < 15) {
  11786. sink.write("chunk", 5);
  11787. return true;
  11788. }
  11789. sink.done();
  11790. return true;
  11791. });
  11792. });
  11793. svr_.Post("/echo", [](const Request &req, Response &res) {
  11794. res.set_content(req.body, req.get_header_value("Content-Type"));
  11795. });
  11796. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11797. std::string body = req.body;
  11798. res.set_chunked_content_provider(
  11799. "text/plain", [body](size_t offset, DataSink &sink) {
  11800. if (offset < body.size()) {
  11801. sink.write(body.data() + offset, body.size() - offset);
  11802. }
  11803. sink.done();
  11804. return true;
  11805. });
  11806. });
  11807. port_ = svr_.bind_to_any_port("127.0.0.1");
  11808. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11809. svr_.wait_until_ready();
  11810. }
  11811. void TearDown() override {
  11812. svr_.stop();
  11813. if (thread_.joinable()) thread_.join();
  11814. }
  11815. SSLServer svr_;
  11816. std::thread thread_;
  11817. int port_ = 0;
  11818. };
  11819. TEST_F(SSLOpenStreamTest, Basic) {
  11820. SSLClient cli("127.0.0.1", port_);
  11821. cli.enable_server_certificate_verification(false);
  11822. auto handle = cli.open_stream("GET", "/hello");
  11823. ASSERT_TRUE(handle.is_valid());
  11824. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11825. }
  11826. TEST_F(SSLOpenStreamTest, Chunked) {
  11827. SSLClient cli("127.0.0.1", port_);
  11828. cli.enable_server_certificate_verification(false);
  11829. auto handle = cli.open_stream("GET", "/chunked");
  11830. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11831. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11832. "Transfer-Encoding") == "chunked");
  11833. auto body = read_all(handle);
  11834. EXPECT_EQ("chunkchunkchunk", body);
  11835. }
  11836. TEST_F(SSLOpenStreamTest, Post) {
  11837. SSLClient cli("127.0.0.1", port_);
  11838. cli.enable_server_certificate_verification(false);
  11839. auto handle =
  11840. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11841. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11842. EXPECT_EQ(200, handle.response->status);
  11843. auto body = read_all(handle);
  11844. EXPECT_EQ("Hello SSL POST", body);
  11845. }
  11846. TEST_F(SSLOpenStreamTest, PostChunked) {
  11847. SSLClient cli("127.0.0.1", port_);
  11848. cli.enable_server_certificate_verification(false);
  11849. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11850. "Chunked SSL Data", "text/plain");
  11851. ASSERT_TRUE(handle.is_valid());
  11852. EXPECT_EQ(200, handle.response->status);
  11853. auto body = read_all(handle);
  11854. EXPECT_EQ("Chunked SSL Data", body);
  11855. }
  11856. #endif // CPPHTTPLIB_SSL_ENABLED
  11857. //==============================================================================
  11858. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11859. // results for various scenarios.
  11860. //==============================================================================
  11861. TEST(ParityTest, GetVsOpenStream) {
  11862. Server svr;
  11863. const std::string path = "/parity";
  11864. const std::string content = "Parity test content: hello world";
  11865. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11866. res.set_content(content, "text/plain");
  11867. });
  11868. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11869. auto se = detail::scope_exit([&] {
  11870. svr.stop();
  11871. t.join();
  11872. ASSERT_FALSE(svr.is_running());
  11873. });
  11874. svr.wait_until_ready();
  11875. Client cli(HOST, PORT);
  11876. // Non-stream path
  11877. auto r1 = cli.Get(path);
  11878. ASSERT_TRUE(r1);
  11879. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11880. // Stream path
  11881. auto h = cli.open_stream("GET", path);
  11882. ASSERT_TRUE(h.is_valid());
  11883. EXPECT_EQ(r1->body, read_all(h));
  11884. }
  11885. // Helper to compress data with provided compressor type T
  11886. template <typename Compressor>
  11887. static std::string compress_payload_for_parity(const std::string &in) {
  11888. std::string out;
  11889. Compressor compressor;
  11890. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11891. [&](const char *data, size_t n) {
  11892. out.append(data, n);
  11893. return true;
  11894. });
  11895. EXPECT_TRUE(ok);
  11896. return out;
  11897. }
  11898. // Helper function for compression parity tests
  11899. template <typename Compressor>
  11900. static void test_compression_parity(const std::string &original,
  11901. const std::string &path,
  11902. const std::string &encoding) {
  11903. const std::string compressed =
  11904. compress_payload_for_parity<Compressor>(original);
  11905. Server svr;
  11906. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11907. res.set_content(compressed, "application/octet-stream");
  11908. res.set_header("Content-Encoding", encoding);
  11909. });
  11910. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11911. auto se = detail::scope_exit([&] {
  11912. svr.stop();
  11913. t.join();
  11914. ASSERT_FALSE(svr.is_running());
  11915. });
  11916. svr.wait_until_ready();
  11917. Client cli(HOST, PORT);
  11918. // Non-streaming
  11919. {
  11920. auto res = cli.Get(path);
  11921. ASSERT_TRUE(res);
  11922. EXPECT_EQ(StatusCode::OK_200, res->status);
  11923. EXPECT_EQ(original, res->body);
  11924. }
  11925. // Streaming
  11926. {
  11927. auto h = cli.open_stream("GET", path);
  11928. ASSERT_TRUE(h.is_valid());
  11929. EXPECT_EQ(original, read_all(h));
  11930. }
  11931. }
  11932. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11933. TEST(ParityTest, Gzip) {
  11934. test_compression_parity<detail::gzip_compressor>(
  11935. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11936. }
  11937. #endif
  11938. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11939. TEST(ParityTest, Brotli) {
  11940. test_compression_parity<detail::brotli_compressor>(
  11941. "Hello, brotli parity test payload", "/parity-br", "br");
  11942. }
  11943. #endif
  11944. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11945. TEST(ParityTest, Zstd) {
  11946. test_compression_parity<detail::zstd_compressor>(
  11947. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11948. }
  11949. #endif
  11950. //==============================================================================
  11951. // New Stream API Tests
  11952. //==============================================================================
  11953. inline std::string read_body(httplib::stream::Result &result) {
  11954. std::string body;
  11955. while (result.next()) {
  11956. body.append(result.data(), result.size());
  11957. }
  11958. return body;
  11959. }
  11960. TEST(ClientConnectionTest, Basic) {
  11961. httplib::ClientConnection conn;
  11962. EXPECT_FALSE(conn.is_open());
  11963. conn.sock = 1;
  11964. EXPECT_TRUE(conn.is_open());
  11965. httplib::ClientConnection conn2(std::move(conn));
  11966. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11967. conn2.sock = INVALID_SOCKET;
  11968. }
  11969. // Unified test server for all stream::* tests
  11970. class StreamApiTest : public ::testing::Test {
  11971. protected:
  11972. void SetUp() override {
  11973. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11974. res.set_content("Hello World!", "text/plain");
  11975. });
  11976. svr_.Get("/echo-params",
  11977. [](const httplib::Request &req, httplib::Response &res) {
  11978. std::string r;
  11979. for (const auto &p : req.params) {
  11980. if (!r.empty()) r += "&";
  11981. r += p.first + "=" + p.second;
  11982. }
  11983. res.set_content(r, "text/plain");
  11984. });
  11985. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11986. res.set_content(req.body, req.get_header_value("Content-Type"));
  11987. });
  11988. svr_.Post("/echo-headers",
  11989. [](const httplib::Request &req, httplib::Response &res) {
  11990. std::string r;
  11991. for (const auto &h : req.headers)
  11992. r += h.first + ": " + h.second + "\n";
  11993. res.set_content(r, "text/plain");
  11994. });
  11995. svr_.Post("/echo-params",
  11996. [](const httplib::Request &req, httplib::Response &res) {
  11997. std::string r = "params:";
  11998. for (const auto &p : req.params)
  11999. r += p.first + "=" + p.second + ";";
  12000. res.set_content(r + " body:" + req.body, "text/plain");
  12001. });
  12002. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12003. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12004. });
  12005. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12006. res.set_content("PUT:" + req.body, "text/plain");
  12007. });
  12008. svr_.Patch("/echo",
  12009. [](const httplib::Request &req, httplib::Response &res) {
  12010. res.set_content("PATCH:" + req.body, "text/plain");
  12011. });
  12012. svr_.Delete(
  12013. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12014. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12015. "text/plain");
  12016. });
  12017. svr_.Get("/head-test",
  12018. [](const httplib::Request &, httplib::Response &res) {
  12019. res.set_content("body for HEAD", "text/plain");
  12020. });
  12021. svr_.Options("/options",
  12022. [](const httplib::Request &, httplib::Response &res) {
  12023. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12024. });
  12025. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12026. svr_.wait_until_ready();
  12027. }
  12028. void TearDown() override {
  12029. svr_.stop();
  12030. if (thread_.joinable()) thread_.join();
  12031. }
  12032. httplib::Server svr_;
  12033. std::thread thread_;
  12034. };
  12035. // stream::Get tests
  12036. TEST_F(StreamApiTest, GetBasic) {
  12037. httplib::Client cli(HOST, PORT);
  12038. auto result = httplib::stream::Get(cli, "/hello");
  12039. ASSERT_TRUE(result.is_valid());
  12040. EXPECT_EQ(200, result.status());
  12041. EXPECT_EQ("Hello World!", read_body(result));
  12042. }
  12043. TEST_F(StreamApiTest, GetWithParams) {
  12044. httplib::Client cli(HOST, PORT);
  12045. httplib::Params params{{"foo", "bar"}};
  12046. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12047. ASSERT_TRUE(result.is_valid());
  12048. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12049. }
  12050. TEST_F(StreamApiTest, GetConnectionError) {
  12051. httplib::Client cli(HOST, 9999);
  12052. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12053. }
  12054. TEST_F(StreamApiTest, Get404) {
  12055. httplib::Client cli(HOST, PORT);
  12056. auto result = httplib::stream::Get(cli, "/nonexistent");
  12057. EXPECT_TRUE(result.is_valid());
  12058. EXPECT_EQ(404, result.status());
  12059. }
  12060. // stream::Post tests
  12061. TEST_F(StreamApiTest, PostBasic) {
  12062. httplib::Client cli(HOST, PORT);
  12063. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12064. "application/json");
  12065. ASSERT_TRUE(result.is_valid());
  12066. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12067. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12068. }
  12069. TEST_F(StreamApiTest, PostWithHeaders) {
  12070. httplib::Client cli(HOST, PORT);
  12071. httplib::Headers headers{{"X-Custom", "value"}};
  12072. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12073. "text/plain");
  12074. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12075. }
  12076. TEST_F(StreamApiTest, PostWithParams) {
  12077. httplib::Client cli(HOST, PORT);
  12078. httplib::Params params{{"k", "v"}};
  12079. auto result =
  12080. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12081. auto body = read_body(result);
  12082. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12083. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12084. }
  12085. TEST_F(StreamApiTest, PostLarge) {
  12086. httplib::Client cli(HOST, PORT);
  12087. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12088. size_t total = 0;
  12089. while (result.next()) {
  12090. total += result.size();
  12091. }
  12092. EXPECT_EQ(100u * 1024u, total);
  12093. }
  12094. // stream::Put/Patch tests
  12095. TEST_F(StreamApiTest, PutAndPatch) {
  12096. httplib::Client cli(HOST, PORT);
  12097. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12098. EXPECT_EQ("PUT:test", read_body(put));
  12099. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12100. EXPECT_EQ("PATCH:test", read_body(patch));
  12101. }
  12102. // stream::Delete tests
  12103. TEST_F(StreamApiTest, Delete) {
  12104. httplib::Client cli(HOST, PORT);
  12105. auto del1 = httplib::stream::Delete(cli, "/resource");
  12106. EXPECT_EQ("Deleted", read_body(del1));
  12107. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12108. EXPECT_EQ("Deleted:data", read_body(del2));
  12109. }
  12110. // stream::Head/Options tests
  12111. TEST_F(StreamApiTest, HeadAndOptions) {
  12112. httplib::Client cli(HOST, PORT);
  12113. auto head = httplib::stream::Head(cli, "/head-test");
  12114. EXPECT_TRUE(head.is_valid());
  12115. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12116. auto opts = httplib::stream::Options(cli, "/options");
  12117. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12118. }
  12119. // SSL stream::* tests
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. class SSLStreamApiTest : public ::testing::Test {
  12122. protected:
  12123. void SetUp() override {
  12124. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12125. res.set_content("Hello SSL!", "text/plain");
  12126. });
  12127. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12128. res.set_content(req.body, "text/plain");
  12129. });
  12130. port_ = svr_.bind_to_any_port("127.0.0.1");
  12131. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12132. svr_.wait_until_ready();
  12133. }
  12134. void TearDown() override {
  12135. svr_.stop();
  12136. if (thread_.joinable()) thread_.join();
  12137. }
  12138. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12139. std::thread thread_;
  12140. int port_ = 0;
  12141. };
  12142. TEST_F(SSLStreamApiTest, GetAndPost) {
  12143. httplib::SSLClient cli("127.0.0.1", port_);
  12144. cli.enable_server_certificate_verification(false);
  12145. auto get = httplib::stream::Get(cli, "/hello");
  12146. EXPECT_EQ("Hello SSL!", read_body(get));
  12147. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12148. EXPECT_EQ("test", read_body(post));
  12149. }
  12150. #endif
  12151. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12152. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12153. // BodyReader
  12154. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12155. // Test that read timeout during streaming is detected
  12156. // Use a large content-length response where server delays mid-stream
  12157. Server svr;
  12158. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12159. // Send a large response with delay in the middle
  12160. res.set_content_provider(
  12161. 1000, // content_length
  12162. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12163. if (offset < 100) {
  12164. // Send first 100 bytes immediately
  12165. std::string data(100, 'A');
  12166. sink.write(data.c_str(), data.size());
  12167. return true;
  12168. }
  12169. // Then delay longer than client timeout
  12170. std::this_thread::sleep_for(std::chrono::seconds(3));
  12171. std::string data(900, 'B');
  12172. sink.write(data.c_str(), data.size());
  12173. return true;
  12174. });
  12175. });
  12176. auto port = 8091;
  12177. std::thread t([&]() { svr.listen("localhost", port); });
  12178. svr.wait_until_ready();
  12179. Client cli("localhost", port);
  12180. cli.set_read_timeout(1, 0); // 1 second timeout
  12181. auto handle = cli.open_stream("GET", "/slow-stream");
  12182. ASSERT_TRUE(handle.is_valid());
  12183. char buf[256];
  12184. ssize_t total = 0;
  12185. ssize_t n;
  12186. bool got_error = false;
  12187. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12188. total += n;
  12189. }
  12190. if (n < 0) {
  12191. got_error = true;
  12192. // Should be timeout or read error
  12193. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12194. handle.get_read_error() == Error::Read)
  12195. << "Actual error: " << to_string(handle.get_read_error());
  12196. }
  12197. // Either we got an error, or we got less data than expected
  12198. EXPECT_TRUE(got_error || total < 1000)
  12199. << "Expected timeout but got all " << total << " bytes";
  12200. svr.stop();
  12201. t.join();
  12202. }
  12203. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12204. // Test connection closed detection via BodyReader
  12205. Server svr;
  12206. std::atomic<bool> close_now{false};
  12207. svr.Get("/will-close", [&](const Request &, Response &res) {
  12208. res.set_content_provider(
  12209. 10000, // Large content_length that we won't fully send
  12210. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12211. if (offset < 100) {
  12212. std::string data(100, 'X');
  12213. sink.write(data.c_str(), data.size());
  12214. return true;
  12215. }
  12216. // Wait for signal then abort
  12217. while (!close_now) {
  12218. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12219. }
  12220. return false; // Abort - server will close connection
  12221. });
  12222. });
  12223. auto port = 8092;
  12224. std::thread t([&]() { svr.listen("localhost", port); });
  12225. svr.wait_until_ready();
  12226. Client cli("localhost", port);
  12227. auto handle = cli.open_stream("GET", "/will-close");
  12228. ASSERT_TRUE(handle.is_valid());
  12229. char buf[256];
  12230. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12231. EXPECT_GT(n, 0) << "First read should succeed";
  12232. // Signal server to close
  12233. close_now = true;
  12234. // Keep reading until error or EOF
  12235. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12236. // Keep reading
  12237. }
  12238. // Should get an error since content_length wasn't satisfied
  12239. if (n < 0) {
  12240. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12241. handle.get_read_error() == Error::Read)
  12242. << "Actual error: " << to_string(handle.get_read_error());
  12243. }
  12244. svr.stop();
  12245. t.join();
  12246. }
  12247. #ifdef CPPHTTPLIB_SSL_ENABLED
  12248. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12249. // Test that read timeout during SSL streaming is detected
  12250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12251. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12252. res.set_content_provider(
  12253. 1000, "text/plain",
  12254. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12255. if (offset < 100) {
  12256. std::string data(100, 'A');
  12257. sink.write(data.c_str(), data.size());
  12258. return true;
  12259. }
  12260. std::this_thread::sleep_for(std::chrono::seconds(3));
  12261. std::string data(900, 'B');
  12262. sink.write(data.c_str(), data.size());
  12263. return true;
  12264. });
  12265. });
  12266. auto port = 8093;
  12267. std::thread t([&]() { svr.listen("localhost", port); });
  12268. svr.wait_until_ready();
  12269. SSLClient cli("localhost", port);
  12270. cli.enable_server_certificate_verification(false);
  12271. cli.set_read_timeout(1, 0); // 1 second timeout
  12272. auto handle = cli.open_stream("GET", "/slow-stream");
  12273. ASSERT_TRUE(handle.is_valid());
  12274. char buf[256];
  12275. ssize_t total = 0;
  12276. ssize_t n;
  12277. bool got_error = false;
  12278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12279. total += n;
  12280. }
  12281. if (n < 0) {
  12282. got_error = true;
  12283. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12284. handle.get_read_error() == Error::Read)
  12285. << "Actual error: " << to_string(handle.get_read_error());
  12286. }
  12287. EXPECT_TRUE(got_error || total < 1000)
  12288. << "Expected timeout but got all " << total << " bytes";
  12289. svr.stop();
  12290. t.join();
  12291. }
  12292. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12293. // Test SSL connection closed detection
  12294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12295. std::atomic<bool> close_now{false};
  12296. svr.Get("/will-close", [&](const Request &, Response &res) {
  12297. res.set_content_provider(
  12298. 10000, "text/plain",
  12299. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12300. if (offset < 100) {
  12301. std::string data(100, 'X');
  12302. sink.write(data.c_str(), data.size());
  12303. return true;
  12304. }
  12305. while (!close_now) {
  12306. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12307. }
  12308. return false;
  12309. });
  12310. });
  12311. auto port = 8094;
  12312. std::thread t([&]() { svr.listen("localhost", port); });
  12313. svr.wait_until_ready();
  12314. SSLClient cli("localhost", port);
  12315. cli.enable_server_certificate_verification(false);
  12316. auto handle = cli.open_stream("GET", "/will-close");
  12317. ASSERT_TRUE(handle.is_valid());
  12318. char buf[256];
  12319. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12320. EXPECT_GT(n, 0);
  12321. // Signal server to close
  12322. close_now = true;
  12323. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12324. // Keep reading
  12325. }
  12326. if (n < 0) {
  12327. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12328. handle.get_read_error() == Error::Read)
  12329. << "Actual error: " << to_string(handle.get_read_error());
  12330. }
  12331. svr.stop();
  12332. t.join();
  12333. }
  12334. #endif
  12335. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12336. using namespace httplib;
  12337. // Create a test file
  12338. const char *fname = "etag_testfile.txt";
  12339. const char *content = "etag-content";
  12340. {
  12341. std::ofstream ofs(fname);
  12342. ofs << content;
  12343. ASSERT_TRUE(ofs.good());
  12344. }
  12345. Server svr;
  12346. svr.set_mount_point("/static", ".");
  12347. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12348. svr.wait_until_ready();
  12349. Client cli(HOST, PORT);
  12350. // First request: should get 200 with ETag header
  12351. auto res1 = cli.Get("/static/etag_testfile.txt");
  12352. ASSERT_TRUE(res1);
  12353. ASSERT_EQ(200, res1->status);
  12354. ASSERT_TRUE(res1->has_header("ETag"));
  12355. std::string etag = res1->get_header_value("ETag");
  12356. EXPECT_FALSE(etag.empty());
  12357. // Verify ETag format: W/"hex-hex"
  12358. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12359. EXPECT_EQ('W', etag[0]);
  12360. EXPECT_EQ('/', etag[1]);
  12361. EXPECT_EQ('"', etag[2]);
  12362. EXPECT_EQ('"', etag.back());
  12363. // Exact match: expect 304 Not Modified
  12364. Headers h2 = {{"If-None-Match", etag}};
  12365. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12366. ASSERT_TRUE(res2);
  12367. EXPECT_EQ(304, res2->status);
  12368. // Wildcard match: expect 304 Not Modified
  12369. Headers h3 = {{"If-None-Match", "*"}};
  12370. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12371. ASSERT_TRUE(res3);
  12372. EXPECT_EQ(304, res3->status);
  12373. // Non-matching ETag: expect 200
  12374. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12375. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12376. ASSERT_TRUE(res4);
  12377. EXPECT_EQ(200, res4->status);
  12378. // Multiple ETags with one matching: expect 304
  12379. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12380. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12381. ASSERT_TRUE(res5);
  12382. EXPECT_EQ(304, res5->status);
  12383. svr.stop();
  12384. t.join();
  12385. std::remove(fname);
  12386. }
  12387. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12388. using namespace httplib;
  12389. Server svr;
  12390. svr.set_mount_point("/static", ".");
  12391. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12392. svr.wait_until_ready();
  12393. Client cli(HOST, PORT);
  12394. // Send If-None-Match: * to a non-existent file
  12395. Headers h = {{"If-None-Match", "*"}};
  12396. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12397. ASSERT_TRUE(res);
  12398. EXPECT_EQ(404, res->status);
  12399. svr.stop();
  12400. t.join();
  12401. }
  12402. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12403. using namespace httplib;
  12404. // Create a test file
  12405. const char *fname = "etag_boundary_testfile.txt";
  12406. const char *content = "boundary-test";
  12407. {
  12408. std::ofstream ofs(fname);
  12409. ofs << content;
  12410. ASSERT_TRUE(ofs.good());
  12411. }
  12412. Server svr;
  12413. svr.set_mount_point("/static", ".");
  12414. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12415. svr.wait_until_ready();
  12416. Client cli(HOST, PORT);
  12417. // Get the actual ETag
  12418. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12419. ASSERT_TRUE(res1);
  12420. ASSERT_EQ(200, res1->status);
  12421. ASSERT_TRUE(res1->has_header("ETag"));
  12422. std::string etag = res1->get_header_value("ETag");
  12423. // Test 1: Very long ETag value (longer than actual ETag)
  12424. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12425. Headers h1 = {{"If-None-Match", "W/"
  12426. "\"very-long-etag-value-that-is-much-longer-"
  12427. "than-the-actual-etag-value\""}};
  12428. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12429. ASSERT_TRUE(res2);
  12430. EXPECT_EQ(200, res2->status); // Should not match
  12431. // Test 2: Long string followed by wildcard
  12432. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12433. // string)
  12434. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12435. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12436. ASSERT_TRUE(res3);
  12437. EXPECT_EQ(304, res3->status); // Should match on "*"
  12438. // Test 3: Wildcard followed by long string
  12439. // Should match on "*" immediately and return 304
  12440. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12441. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12442. ASSERT_TRUE(res4);
  12443. EXPECT_EQ(304, res4->status); // Should match on "*"
  12444. // Test 4: Multiple long non-matching values
  12445. // Should NOT match and return 200 (test that all comparisons are safe)
  12446. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12447. "W/\"second-long-non-matching-value\", "
  12448. "W/\"third-long-non-matching-value\""}};
  12449. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12450. ASSERT_TRUE(res5);
  12451. EXPECT_EQ(200, res5->status); // Should not match
  12452. // Test 5: Single character that is not "*" (edge case)
  12453. Headers h5 = {{"If-None-Match", "X"}};
  12454. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12455. ASSERT_TRUE(res6);
  12456. EXPECT_EQ(200, res6->status); // Should not match
  12457. svr.stop();
  12458. t.join();
  12459. std::remove(fname);
  12460. }
  12461. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12462. using namespace httplib;
  12463. // Create a test file
  12464. const char *fname = "ims_testfile.txt";
  12465. const char *content = "if-modified-since-test";
  12466. {
  12467. std::ofstream ofs(fname);
  12468. ofs << content;
  12469. ASSERT_TRUE(ofs.good());
  12470. }
  12471. Server svr;
  12472. svr.set_mount_point("/static", ".");
  12473. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12474. svr.wait_until_ready();
  12475. Client cli(HOST, PORT);
  12476. // First request: should get 200 with Last-Modified header
  12477. auto res1 = cli.Get("/static/ims_testfile.txt");
  12478. ASSERT_TRUE(res1);
  12479. ASSERT_EQ(200, res1->status);
  12480. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12481. std::string last_modified = res1->get_header_value("Last-Modified");
  12482. EXPECT_FALSE(last_modified.empty());
  12483. // If-Modified-Since with same time: expect 304
  12484. Headers h2 = {{"If-Modified-Since", last_modified}};
  12485. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12486. ASSERT_TRUE(res2);
  12487. EXPECT_EQ(304, res2->status);
  12488. // If-Modified-Since with future time: expect 304
  12489. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12490. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12491. ASSERT_TRUE(res3);
  12492. EXPECT_EQ(304, res3->status);
  12493. // If-Modified-Since with past time: expect 200
  12494. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12495. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12496. ASSERT_TRUE(res4);
  12497. EXPECT_EQ(200, res4->status);
  12498. // If-None-Match takes precedence over If-Modified-Since
  12499. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12500. ASSERT_TRUE(res1->has_header("ETag"));
  12501. std::string etag = res1->get_header_value("ETag");
  12502. Headers h5 = {{"If-None-Match", etag},
  12503. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12504. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12505. ASSERT_TRUE(res5);
  12506. EXPECT_EQ(304, res5->status);
  12507. svr.stop();
  12508. t.join();
  12509. std::remove(fname);
  12510. }
  12511. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12512. using namespace httplib;
  12513. Server svr;
  12514. // Endpoint that returns compressible content
  12515. svr.Get("/compressible", [](const Request &, Response &res) {
  12516. // Return a large enough body to trigger compression
  12517. std::string body(1000, 'a');
  12518. res.set_content(body, "text/plain");
  12519. });
  12520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12521. svr.wait_until_ready();
  12522. Client cli(HOST, PORT);
  12523. // Request with gzip support: should get Vary header when compressed
  12524. cli.set_compress(true);
  12525. auto res1 = cli.Get("/compressible");
  12526. ASSERT_TRUE(res1);
  12527. EXPECT_EQ(200, res1->status);
  12528. // If Content-Encoding is set, Vary should also be set
  12529. if (res1->has_header("Content-Encoding")) {
  12530. EXPECT_TRUE(res1->has_header("Vary"));
  12531. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12532. }
  12533. // Request without Accept-Encoding header: should not have compression
  12534. Headers h_no_compress;
  12535. auto res2 = cli.Get("/compressible", h_no_compress);
  12536. ASSERT_TRUE(res2);
  12537. EXPECT_EQ(200, res2->status);
  12538. // Verify Vary header is present when compression is applied
  12539. // (the exact behavior depends on server configuration)
  12540. svr.stop();
  12541. t.join();
  12542. }
  12543. TEST(ETagTest, IfRangeWithETag) {
  12544. using namespace httplib;
  12545. // Create a test file with known content
  12546. const char *fname = "if_range_testfile.txt";
  12547. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12548. {
  12549. std::ofstream ofs(fname);
  12550. ofs << content;
  12551. ASSERT_TRUE(ofs.good());
  12552. }
  12553. Server svr;
  12554. svr.set_mount_point("/static", ".");
  12555. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12556. svr.wait_until_ready();
  12557. Client cli(HOST, PORT);
  12558. // First request: get ETag
  12559. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12560. ASSERT_TRUE(res1);
  12561. ASSERT_EQ(200, res1->status);
  12562. ASSERT_TRUE(res1->has_header("ETag"));
  12563. std::string etag = res1->get_header_value("ETag");
  12564. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12565. // Since our server generates weak ETags (W/"..."), If-Range with our
  12566. // ETag should NOT result in partial content - it should return full content.
  12567. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12568. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12569. ASSERT_TRUE(res2);
  12570. // Weak ETag in If-Range -> full content (200), not partial (206)
  12571. EXPECT_EQ(200, res2->status);
  12572. EXPECT_EQ(content, res2->body);
  12573. EXPECT_FALSE(res2->has_header("Content-Range"));
  12574. // Range request with non-matching If-Range (ETag): should get 200 (full
  12575. // content)
  12576. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12577. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12578. ASSERT_TRUE(res3);
  12579. EXPECT_EQ(200, res3->status);
  12580. EXPECT_EQ(content, res3->body);
  12581. EXPECT_FALSE(res3->has_header("Content-Range"));
  12582. // Range request with strong ETag (hypothetical - our server doesn't generate
  12583. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12584. // should return full content)
  12585. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12586. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12587. ASSERT_TRUE(res4);
  12588. EXPECT_EQ(200, res4->status);
  12589. EXPECT_EQ(content, res4->body);
  12590. EXPECT_FALSE(res4->has_header("Content-Range"));
  12591. svr.stop();
  12592. t.join();
  12593. std::remove(fname);
  12594. }
  12595. TEST(ETagTest, IfRangeWithDate) {
  12596. using namespace httplib;
  12597. // Create a test file
  12598. const char *fname = "if_range_date_testfile.txt";
  12599. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12600. {
  12601. std::ofstream ofs(fname);
  12602. ofs << content;
  12603. ASSERT_TRUE(ofs.good());
  12604. }
  12605. Server svr;
  12606. svr.set_mount_point("/static", ".");
  12607. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12608. svr.wait_until_ready();
  12609. Client cli(HOST, PORT);
  12610. // First request: get Last-Modified
  12611. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12612. ASSERT_TRUE(res1);
  12613. ASSERT_EQ(200, res1->status);
  12614. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12615. std::string last_modified = res1->get_header_value("Last-Modified");
  12616. // Range request with matching If-Range (date): should get 206
  12617. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12618. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12619. ASSERT_TRUE(res2);
  12620. EXPECT_EQ(206, res2->status);
  12621. EXPECT_EQ("FGHIJ", res2->body);
  12622. // Range request with old If-Range date: should get 200 (full content)
  12623. Headers h3 = {{"Range", "bytes=5-9"},
  12624. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12625. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12626. ASSERT_TRUE(res3);
  12627. EXPECT_EQ(200, res3->status);
  12628. EXPECT_EQ(content, res3->body);
  12629. // Range request with future If-Range date: should get 206
  12630. Headers h4 = {{"Range", "bytes=0-4"},
  12631. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12632. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12633. ASSERT_TRUE(res4);
  12634. EXPECT_EQ(206, res4->status);
  12635. EXPECT_EQ("ABCDE", res4->body);
  12636. svr.stop();
  12637. t.join();
  12638. std::remove(fname);
  12639. }
  12640. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12641. using namespace httplib;
  12642. const char *fname = "etag_malformed.txt";
  12643. const char *content = "malformed-etag";
  12644. {
  12645. std::ofstream ofs(fname);
  12646. ofs << content;
  12647. ASSERT_TRUE(ofs.good());
  12648. }
  12649. Server svr;
  12650. svr.set_mount_point("/static", ".");
  12651. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12652. svr.wait_until_ready();
  12653. Client cli(HOST, PORT);
  12654. // baseline: should get 200 and an ETag
  12655. auto res1 = cli.Get("/static/etag_malformed.txt");
  12656. ASSERT_TRUE(res1);
  12657. ASSERT_EQ(200, res1->status);
  12658. ASSERT_TRUE(res1->has_header("ETag"));
  12659. // Malformed ETag value (missing quotes) should be treated as non-matching
  12660. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12661. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12662. ASSERT_TRUE(res_bad);
  12663. EXPECT_EQ(200, res_bad->status);
  12664. // Whitespace-only header value should be considered invalid / non-matching
  12665. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12666. "Host: localhost\r\n"
  12667. "If-None-Match: \r\n"
  12668. "Connection: close\r\n"
  12669. "\r\n";
  12670. std::string out;
  12671. ASSERT_TRUE(send_request(5, raw_req, &out));
  12672. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12673. svr.stop();
  12674. t.join();
  12675. std::remove(fname);
  12676. }
  12677. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12678. using namespace httplib;
  12679. const char *fname = "ims_invalid_format.txt";
  12680. const char *content = "ims-bad-format";
  12681. {
  12682. std::ofstream ofs(fname);
  12683. ofs << content;
  12684. ASSERT_TRUE(ofs.good());
  12685. }
  12686. Server svr;
  12687. svr.set_mount_point("/static", ".");
  12688. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12689. svr.wait_until_ready();
  12690. Client cli(HOST, PORT);
  12691. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12692. ASSERT_TRUE(res1);
  12693. ASSERT_EQ(200, res1->status);
  12694. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12695. // If-Modified-Since with invalid format should not result in 304
  12696. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12697. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12698. ASSERT_TRUE(res_bad);
  12699. EXPECT_EQ(200, res_bad->status);
  12700. // If-Range with invalid date format should be treated as mismatch -> full
  12701. // content (200)
  12702. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12703. {"If-Range", "invalid-date"}};
  12704. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12705. ASSERT_TRUE(res_ifrange);
  12706. EXPECT_EQ(200, res_ifrange->status);
  12707. svr.stop();
  12708. t.join();
  12709. std::remove(fname);
  12710. }
  12711. TEST(ETagTest, IfRangeWithMalformedETag) {
  12712. using namespace httplib;
  12713. const char *fname = "ifrange_malformed.txt";
  12714. const std::string content = "0123456789";
  12715. {
  12716. std::ofstream ofs(fname);
  12717. ofs << content;
  12718. ASSERT_TRUE(ofs.good());
  12719. }
  12720. Server svr;
  12721. svr.set_mount_point("/static", ".");
  12722. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12723. svr.wait_until_ready();
  12724. Client cli(HOST, PORT);
  12725. // First request: get ETag
  12726. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12727. ASSERT_TRUE(res1);
  12728. ASSERT_EQ(200, res1->status);
  12729. ASSERT_TRUE(res1->has_header("ETag"));
  12730. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12731. // full content (200)
  12732. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12733. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12734. ASSERT_TRUE(res2);
  12735. EXPECT_EQ(200, res2->status);
  12736. EXPECT_EQ(content, res2->body);
  12737. svr.stop();
  12738. t.join();
  12739. std::remove(fname);
  12740. }
  12741. TEST(ETagTest, ExtremeLargeDateValues) {
  12742. using namespace httplib;
  12743. const char *fname = "ims_extreme_date.txt";
  12744. const char *content = "ims-extreme-date";
  12745. {
  12746. std::ofstream ofs(fname);
  12747. ofs << content;
  12748. ASSERT_TRUE(ofs.good());
  12749. }
  12750. Server svr;
  12751. svr.set_mount_point("/static", ".");
  12752. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12753. svr.wait_until_ready();
  12754. Client cli(HOST, PORT);
  12755. auto res1 = cli.Get(std::string("/static/") + fname);
  12756. ASSERT_TRUE(res1);
  12757. ASSERT_EQ(200, res1->status);
  12758. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12759. // Extremely large year that may overflow date parsing routines.
  12760. Headers h_large_date = {
  12761. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12762. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12763. ASSERT_TRUE(res_bad);
  12764. // Expect server to treat this as invalid/mismatch and return full content
  12765. EXPECT_EQ(200, res_bad->status);
  12766. // If-Range with extremely large date should be treated as mismatch -> full
  12767. // content (200)
  12768. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12769. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12770. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12771. ASSERT_TRUE(res_ifrange);
  12772. EXPECT_EQ(200, res_ifrange->status);
  12773. svr.stop();
  12774. t.join();
  12775. std::remove(fname);
  12776. }
  12777. TEST(ETagTest, NegativeFileModificationTime) {
  12778. using namespace httplib;
  12779. const char *fname = "ims_negative_mtime.txt";
  12780. const std::string content = "negative-mtime";
  12781. {
  12782. std::ofstream ofs(fname);
  12783. ofs << content;
  12784. ASSERT_TRUE(ofs.good());
  12785. }
  12786. // Try to set file mtime to a negative value. This may fail on some
  12787. // platforms/filesystems; if it fails, the test will still verify server
  12788. // behaves safely by performing a regular conditional request.
  12789. #if defined(__APPLE__) || defined(__linux__)
  12790. bool set_negative = false;
  12791. do {
  12792. struct timeval times[2];
  12793. // access time: now
  12794. times[0].tv_sec = time(nullptr);
  12795. times[0].tv_usec = 0;
  12796. // modification time: negative (e.g., -1)
  12797. times[1].tv_sec = -1;
  12798. times[1].tv_usec = 0;
  12799. if (utimes(fname, times) == 0) { set_negative = true; }
  12800. } while (0);
  12801. #else
  12802. bool set_negative = false;
  12803. #endif
  12804. Server svr;
  12805. svr.set_mount_point("/static", ".");
  12806. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12807. svr.wait_until_ready();
  12808. Client cli(HOST, PORT);
  12809. auto res1 = cli.Get(std::string("/static/") + fname);
  12810. ASSERT_TRUE(res1);
  12811. ASSERT_EQ(200, res1->status);
  12812. bool has_last_modified = res1->has_header("Last-Modified");
  12813. std::string last_modified;
  12814. if (has_last_modified) {
  12815. last_modified = res1->get_header_value("Last-Modified");
  12816. }
  12817. if (set_negative) {
  12818. // If we successfully set a negative mtime, ensure server returns a
  12819. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12820. // with an old date and ensure server handles it without crash.
  12821. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12822. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12823. ASSERT_TRUE(res2);
  12824. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12825. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12826. } else {
  12827. // Could not set negative mtime on this platform; fall back to verifying
  12828. // that normal invalid/malformed dates are treated safely (non-304).
  12829. Headers h_bad_date = {
  12830. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12831. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12832. ASSERT_TRUE(res_bad);
  12833. EXPECT_EQ(200, res_bad->status);
  12834. }
  12835. svr.stop();
  12836. t.join();
  12837. std::remove(fname);
  12838. }
  12839. //==============================================================================
  12840. // SSE Parsing Tests
  12841. //==============================================================================
  12842. class SSEParsingTest : public ::testing::Test {
  12843. protected:
  12844. // Test helper that mimics SSE parsing behavior
  12845. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12846. int &retry_ms) {
  12847. // Blank line signals end of event
  12848. if (line.empty() || line == "\r") { return true; }
  12849. // Lines starting with ':' are comments (ignored)
  12850. if (!line.empty() && line[0] == ':') { return false; }
  12851. // Find the colon separator
  12852. auto colon_pos = line.find(':');
  12853. if (colon_pos == std::string::npos) {
  12854. // Line with no colon is treated as field name with empty value
  12855. return false;
  12856. }
  12857. std::string field = line.substr(0, colon_pos);
  12858. std::string value;
  12859. // Value starts after colon, skip optional single space
  12860. if (colon_pos + 1 < line.size()) {
  12861. size_t value_start = colon_pos + 1;
  12862. if (line[value_start] == ' ') { value_start++; }
  12863. value = line.substr(value_start);
  12864. // Remove trailing \r if present
  12865. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12866. }
  12867. // Handle known fields
  12868. if (field == "event") {
  12869. msg.event = value;
  12870. } else if (field == "data") {
  12871. // Multiple data lines are concatenated with newlines
  12872. if (!msg.data.empty()) { msg.data += "\n"; }
  12873. msg.data += value;
  12874. } else if (field == "id") {
  12875. // Empty id is valid (clears the last event ID)
  12876. msg.id = value;
  12877. } else if (field == "retry") {
  12878. // Parse retry interval in milliseconds
  12879. {
  12880. int v = 0;
  12881. auto res =
  12882. detail::from_chars(value.data(), value.data() + value.size(), v);
  12883. if (res.ec == std::errc{}) { retry_ms = v; }
  12884. }
  12885. }
  12886. // Unknown fields are ignored per SSE spec
  12887. return false;
  12888. }
  12889. };
  12890. // Test: Single-line data
  12891. TEST_F(SSEParsingTest, SingleLineData) {
  12892. sse::SSEMessage msg;
  12893. int retry_ms = 3000;
  12894. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12895. EXPECT_EQ(msg.data, "hello");
  12896. EXPECT_EQ(msg.event, "message");
  12897. // Blank line ends event
  12898. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12899. }
  12900. // Test: Multi-line data
  12901. TEST_F(SSEParsingTest, MultiLineData) {
  12902. sse::SSEMessage msg;
  12903. int retry_ms = 3000;
  12904. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12905. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12906. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12907. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12908. }
  12909. // Test: Custom event types
  12910. TEST_F(SSEParsingTest, CustomEventType) {
  12911. sse::SSEMessage msg;
  12912. int retry_ms = 3000;
  12913. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12914. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12915. EXPECT_EQ(msg.event, "update");
  12916. EXPECT_EQ(msg.data, "payload");
  12917. }
  12918. // Test: Event ID handling
  12919. TEST_F(SSEParsingTest, EventIdHandling) {
  12920. sse::SSEMessage msg;
  12921. int retry_ms = 3000;
  12922. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12923. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12924. EXPECT_EQ(msg.id, "12345");
  12925. }
  12926. // Test: Empty event ID (clears last event ID)
  12927. TEST_F(SSEParsingTest, EmptyEventId) {
  12928. sse::SSEMessage msg;
  12929. msg.id = "previous";
  12930. int retry_ms = 3000;
  12931. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12932. EXPECT_EQ(msg.id, "");
  12933. }
  12934. // Test: Retry field parsing
  12935. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12936. sse::SSEMessage msg;
  12937. int retry_ms = 3000;
  12938. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12939. EXPECT_EQ(retry_ms, 5000);
  12940. }
  12941. // Test: Invalid retry value
  12942. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12943. sse::SSEMessage msg;
  12944. int retry_ms = 3000;
  12945. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12946. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12947. }
  12948. // Test: Comments (lines starting with :)
  12949. TEST_F(SSEParsingTest, CommentsIgnored) {
  12950. sse::SSEMessage msg;
  12951. int retry_ms = 3000;
  12952. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12953. EXPECT_EQ(msg.data, "");
  12954. EXPECT_EQ(msg.event, "message");
  12955. }
  12956. // Test: Colon in value
  12957. TEST_F(SSEParsingTest, ColonInValue) {
  12958. sse::SSEMessage msg;
  12959. int retry_ms = 3000;
  12960. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12961. EXPECT_EQ(msg.data, "hello:world:test");
  12962. }
  12963. // Test: Line with no colon (field name only)
  12964. TEST_F(SSEParsingTest, FieldNameOnly) {
  12965. sse::SSEMessage msg;
  12966. int retry_ms = 3000;
  12967. // According to SSE spec, this is treated as field name with empty value
  12968. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12969. // Since we don't recognize "data" without colon, data should be empty
  12970. EXPECT_EQ(msg.data, "");
  12971. }
  12972. // Test: Trailing \r handling
  12973. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12974. sse::SSEMessage msg;
  12975. int retry_ms = 3000;
  12976. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12977. EXPECT_EQ(msg.data, "hello");
  12978. }
  12979. // Test: Unknown fields ignored
  12980. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12981. sse::SSEMessage msg;
  12982. int retry_ms = 3000;
  12983. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12984. EXPECT_EQ(msg.data, "");
  12985. EXPECT_EQ(msg.event, "message");
  12986. }
  12987. // Test: Space after colon is optional
  12988. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12989. sse::SSEMessage msg1, msg2;
  12990. int retry_ms = 3000;
  12991. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12992. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12993. EXPECT_EQ(msg1.data, "hello");
  12994. EXPECT_EQ(msg2.data, "hello");
  12995. }
  12996. // Test: SSEMessage clear
  12997. TEST_F(SSEParsingTest, MessageClear) {
  12998. sse::SSEMessage msg;
  12999. msg.event = "custom";
  13000. msg.data = "some data";
  13001. msg.id = "123";
  13002. msg.clear();
  13003. EXPECT_EQ(msg.event, "message");
  13004. EXPECT_EQ(msg.data, "");
  13005. EXPECT_EQ(msg.id, "");
  13006. }
  13007. // Test: Complete event parsing
  13008. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13009. sse::SSEMessage msg;
  13010. int retry_ms = 3000;
  13011. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13012. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13013. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13014. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13015. // Blank line ends event
  13016. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13017. EXPECT_EQ(msg.event, "notification");
  13018. EXPECT_EQ(msg.id, "evt-42");
  13019. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13020. EXPECT_EQ(retry_ms, 1000);
  13021. }
  13022. //==============================================================================
  13023. // Integration Tests with Server
  13024. //==============================================================================
  13025. class SSEIntegrationTest : public ::testing::Test {
  13026. protected:
  13027. void SetUp() override {
  13028. stop_server_.store(false);
  13029. events_.clear();
  13030. server_ = httplib::detail::make_unique<Server>();
  13031. setup_server();
  13032. start_server();
  13033. }
  13034. void TearDown() override {
  13035. stop_server_.store(true);
  13036. event_cv_.notify_all();
  13037. server_->stop();
  13038. if (server_thread_.joinable()) { server_thread_.join(); }
  13039. }
  13040. void setup_server() {
  13041. // Simple SSE endpoint
  13042. server_->Get("/events", [this](const Request &req, Response &res) {
  13043. auto last_id = req.get_header_value("Last-Event-ID");
  13044. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13045. res.set_chunked_content_provider(
  13046. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13047. std::unique_lock<std::mutex> lock(event_mutex_);
  13048. if (event_cv_.wait_for(
  13049. lock, std::chrono::milliseconds(200), [this] {
  13050. return !events_.empty() || stop_server_.load();
  13051. })) {
  13052. if (stop_server_.load()) { return false; }
  13053. if (!events_.empty()) {
  13054. std::string event = events_.front();
  13055. events_.erase(events_.begin());
  13056. sink.write(event.data(), event.size());
  13057. return true;
  13058. }
  13059. }
  13060. return !stop_server_.load();
  13061. });
  13062. });
  13063. // Endpoint that returns error
  13064. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13065. res.status = 500;
  13066. res.set_content("Internal Server Error", "text/plain");
  13067. });
  13068. // Endpoint for custom event types
  13069. server_->Get("/custom-events", [](const Request &, Response &res) {
  13070. res.set_chunked_content_provider(
  13071. "text/event-stream", [](size_t offset, DataSink &sink) {
  13072. if (offset == 0) {
  13073. std::string event = "event: update\ndata: updated\n\n"
  13074. "event: delete\ndata: deleted\n\n";
  13075. sink.write(event.data(), event.size());
  13076. }
  13077. return false; // End stream after sending
  13078. });
  13079. });
  13080. }
  13081. void start_server() {
  13082. port_ = server_->bind_to_any_port(HOST);
  13083. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13084. // Wait for server to start
  13085. while (!server_->is_running()) {
  13086. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13087. }
  13088. }
  13089. int get_port() const { return port_; }
  13090. void send_event(const std::string &event) {
  13091. std::lock_guard<std::mutex> lock(event_mutex_);
  13092. events_.push_back(event);
  13093. event_cv_.notify_all();
  13094. }
  13095. std::unique_ptr<Server> server_;
  13096. std::thread server_thread_;
  13097. std::mutex event_mutex_;
  13098. std::condition_variable event_cv_;
  13099. std::vector<std::string> events_;
  13100. std::atomic<bool> stop_server_{false};
  13101. std::string last_received_event_id_;
  13102. int port_ = 0;
  13103. };
  13104. // Test: Successful connection and on_open callback
  13105. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13106. // Add a simple endpoint that sends one event and closes
  13107. server_->Get("/simple-event", [](const Request &, Response &res) {
  13108. res.set_chunked_content_provider(
  13109. "text/event-stream", [](size_t offset, DataSink &sink) {
  13110. if (offset == 0) {
  13111. std::string event = "data: hello\n\n";
  13112. sink.write(event.data(), event.size());
  13113. }
  13114. return false; // Close stream after sending
  13115. });
  13116. });
  13117. Client client("localhost", get_port());
  13118. sse::SSEClient sse(client, "/simple-event");
  13119. std::atomic<bool> open_called{false};
  13120. std::atomic<bool> message_received{false};
  13121. sse.on_open([&open_called]() { open_called.store(true); });
  13122. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13123. if (msg.data == "hello") { message_received.store(true); }
  13124. });
  13125. sse.set_reconnect_interval(100);
  13126. sse.set_max_reconnect_attempts(1);
  13127. // Start async
  13128. sse.start_async();
  13129. // Wait for message to be processed
  13130. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13131. sse.stop();
  13132. EXPECT_TRUE(open_called.load());
  13133. EXPECT_TRUE(message_received.load());
  13134. }
  13135. // Test: on_message callback
  13136. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13137. // Endpoint that sends multiple events then closes
  13138. server_->Get("/multi-event", [](const Request &, Response &res) {
  13139. res.set_chunked_content_provider(
  13140. "text/event-stream", [](size_t offset, DataSink &sink) {
  13141. if (offset == 0) {
  13142. std::string events = "data: message1\n\ndata: message2\n\n";
  13143. sink.write(events.data(), events.size());
  13144. }
  13145. return false;
  13146. });
  13147. });
  13148. Client client("localhost", get_port());
  13149. sse::SSEClient sse(client, "/multi-event");
  13150. std::vector<std::string> received_messages;
  13151. std::mutex messages_mutex;
  13152. sse.on_message([&](const sse::SSEMessage &msg) {
  13153. std::lock_guard<std::mutex> lock(messages_mutex);
  13154. received_messages.push_back(msg.data);
  13155. });
  13156. sse.set_reconnect_interval(100);
  13157. sse.set_max_reconnect_attempts(1);
  13158. sse.start_async();
  13159. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13160. sse.stop();
  13161. std::lock_guard<std::mutex> lock(messages_mutex);
  13162. EXPECT_GE(received_messages.size(), 2u);
  13163. if (received_messages.size() >= 2) {
  13164. EXPECT_EQ(received_messages[0], "message1");
  13165. EXPECT_EQ(received_messages[1], "message2");
  13166. }
  13167. }
  13168. // Test: on_event for specific types
  13169. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13170. Client client("localhost", get_port());
  13171. sse::SSEClient sse(client, "/custom-events");
  13172. std::atomic<bool> update_received{false};
  13173. std::atomic<bool> delete_received{false};
  13174. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13175. if (msg.data == "updated") { update_received.store(true); }
  13176. });
  13177. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13178. if (msg.data == "deleted") { delete_received.store(true); }
  13179. });
  13180. sse.set_max_reconnect_attempts(1);
  13181. sse.start_async();
  13182. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13183. sse.stop();
  13184. EXPECT_TRUE(update_received.load());
  13185. EXPECT_TRUE(delete_received.load());
  13186. }
  13187. // Test: on_error callback on connection failure
  13188. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13189. // Connect to a non-existent port
  13190. Client client("localhost", 59999);
  13191. sse::SSEClient sse(client, "/events");
  13192. std::atomic<bool> error_called{false};
  13193. Error received_error = Error::Success;
  13194. sse.on_error([&](Error err) {
  13195. error_called.store(true);
  13196. received_error = err;
  13197. });
  13198. sse.set_reconnect_interval(50);
  13199. sse.set_max_reconnect_attempts(1);
  13200. sse.start_async();
  13201. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13202. sse.stop();
  13203. EXPECT_TRUE(error_called.load());
  13204. EXPECT_NE(received_error, Error::Success);
  13205. }
  13206. // Test: Last-Event-ID header sent on reconnect
  13207. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13208. // Endpoint that sends event with ID
  13209. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13210. res.set_chunked_content_provider(
  13211. "text/event-stream", [](size_t offset, DataSink &sink) {
  13212. if (offset == 0) {
  13213. std::string event = "id: evt-123\ndata: test\n\n";
  13214. sink.write(event.data(), event.size());
  13215. }
  13216. return false;
  13217. });
  13218. });
  13219. Client client("localhost", get_port());
  13220. sse::SSEClient sse(client, "/event-with-id");
  13221. std::atomic<bool> id_received{false};
  13222. sse.on_message([&](const sse::SSEMessage &msg) {
  13223. if (!msg.id.empty()) { id_received.store(true); }
  13224. });
  13225. sse.set_reconnect_interval(100);
  13226. sse.set_max_reconnect_attempts(1);
  13227. sse.start_async();
  13228. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13229. sse.stop();
  13230. EXPECT_TRUE(id_received.load());
  13231. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13232. }
  13233. // Test: Manual stop
  13234. TEST_F(SSEIntegrationTest, ManualStop) {
  13235. // Endpoint that sends one event and stays open briefly
  13236. std::atomic<bool> handler_running{true};
  13237. server_->Get("/stay-open", [&handler_running](const Request &,
  13238. Response &res) {
  13239. res.set_chunked_content_provider(
  13240. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13241. if (offset == 0) {
  13242. std::string event = "data: connected\n\n";
  13243. sink.write(event.data(), event.size());
  13244. }
  13245. // Keep connection open while handler_running is true
  13246. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13247. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13248. }
  13249. return false;
  13250. });
  13251. });
  13252. Client client("localhost", get_port());
  13253. sse::SSEClient sse(client, "/stay-open");
  13254. std::atomic<bool> connected{false};
  13255. sse.on_open([&connected]() { connected.store(true); });
  13256. sse.set_reconnect_interval(100);
  13257. sse.set_max_reconnect_attempts(1);
  13258. sse.start_async();
  13259. // Wait for connection to establish
  13260. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13261. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13262. }
  13263. EXPECT_TRUE(connected.load());
  13264. EXPECT_TRUE(sse.is_connected());
  13265. // Signal handler to stop
  13266. handler_running.store(false);
  13267. // Stop SSE client
  13268. sse.stop();
  13269. EXPECT_FALSE(sse.is_connected());
  13270. }
  13271. // Test: SSEClient with custom headers
  13272. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13273. // Setup a server endpoint that checks for custom header
  13274. std::atomic<bool> header_received{false};
  13275. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13276. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13277. header_received.store(true);
  13278. }
  13279. res.set_chunked_content_provider("text/event-stream",
  13280. [](size_t, DataSink &) { return false; });
  13281. });
  13282. Client client("localhost", get_port());
  13283. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13284. sse::SSEClient sse(client, "/header-check", headers);
  13285. sse.set_max_reconnect_attempts(1);
  13286. sse.start_async();
  13287. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13288. sse.stop();
  13289. EXPECT_TRUE(header_received.load());
  13290. }
  13291. // Test: Reconnect interval configuration
  13292. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13293. Client client("localhost", get_port());
  13294. sse::SSEClient sse(client, "/events");
  13295. auto &result = sse.set_reconnect_interval(500);
  13296. // Builder pattern should return reference to self
  13297. EXPECT_EQ(&result, &sse);
  13298. }
  13299. // Test: Max reconnect attempts
  13300. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13301. // Connect to non-existent port to force reconnects
  13302. Client client("localhost", 59998);
  13303. sse::SSEClient sse(client, "/events");
  13304. std::atomic<int> error_count{0};
  13305. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13306. sse.set_reconnect_interval(50);
  13307. sse.set_max_reconnect_attempts(2);
  13308. auto start = std::chrono::steady_clock::now();
  13309. sse.start(); // Blocking call
  13310. auto end = std::chrono::steady_clock::now();
  13311. // Should have stopped after 2 failed attempts
  13312. EXPECT_GE(error_count.load(), 2);
  13313. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13314. auto duration =
  13315. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13316. #ifdef _WIN32
  13317. // Windows is much slower for socket connection failures
  13318. EXPECT_LT(duration.count(), 7000);
  13319. #else
  13320. EXPECT_LT(duration.count(), 1000);
  13321. #endif
  13322. }
  13323. // Test: Multi-line data in integration
  13324. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13325. // Endpoint with multi-line data
  13326. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13327. res.set_chunked_content_provider(
  13328. "text/event-stream", [](size_t offset, DataSink &sink) {
  13329. if (offset == 0) {
  13330. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13331. sink.write(event.data(), event.size());
  13332. }
  13333. return false;
  13334. });
  13335. });
  13336. Client client("localhost", get_port());
  13337. sse::SSEClient sse(client, "/multiline-data");
  13338. std::string received_data;
  13339. std::mutex data_mutex;
  13340. sse.on_message([&](const sse::SSEMessage &msg) {
  13341. std::lock_guard<std::mutex> lock(data_mutex);
  13342. received_data = msg.data;
  13343. });
  13344. sse.set_reconnect_interval(100);
  13345. sse.set_max_reconnect_attempts(1);
  13346. sse.start_async();
  13347. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13348. sse.stop();
  13349. std::lock_guard<std::mutex> lock(data_mutex);
  13350. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13351. }
  13352. // Test: Auto-reconnect after server disconnection
  13353. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13354. std::atomic<int> connection_count{0};
  13355. std::atomic<int> message_count{0};
  13356. // Endpoint that sends one event and closes, forcing reconnect
  13357. server_->Get("/reconnect-test",
  13358. [&connection_count](const Request &, Response &res) {
  13359. connection_count.fetch_add(1);
  13360. res.set_chunked_content_provider(
  13361. "text/event-stream", [](size_t offset, DataSink &sink) {
  13362. if (offset == 0) {
  13363. std::string event = "data: hello\n\n";
  13364. sink.write(event.data(), event.size());
  13365. }
  13366. return false; // Close connection after sending
  13367. });
  13368. });
  13369. Client client("localhost", get_port());
  13370. sse::SSEClient sse(client, "/reconnect-test");
  13371. sse.on_message([&message_count](const sse::SSEMessage &) {
  13372. message_count.fetch_add(1);
  13373. });
  13374. sse.set_reconnect_interval(100);
  13375. sse.set_max_reconnect_attempts(3);
  13376. sse.start_async();
  13377. // Wait long enough for multiple reconnects
  13378. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13379. sse.stop();
  13380. // Should have connected multiple times (initial + reconnects)
  13381. EXPECT_GE(connection_count.load(), 2);
  13382. // Should have received messages from multiple connections
  13383. EXPECT_GE(message_count.load(), 2);
  13384. }
  13385. // Test: Last-Event-ID sent on reconnect
  13386. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13387. std::atomic<int> connection_count{0};
  13388. std::vector<std::string> received_last_event_ids;
  13389. std::mutex id_mutex;
  13390. // Endpoint that checks Last-Event-ID header and sends event with ID
  13391. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13392. int conn = connection_count.fetch_add(1);
  13393. // Capture the Last-Event-ID header from each connection
  13394. {
  13395. std::lock_guard<std::mutex> lock(id_mutex);
  13396. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13397. }
  13398. res.set_chunked_content_provider(
  13399. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13400. if (offset == 0) {
  13401. std::string event =
  13402. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13403. sink.write(event.data(), event.size());
  13404. }
  13405. return false;
  13406. });
  13407. });
  13408. Client client("localhost", get_port());
  13409. sse::SSEClient sse(client, "/reconnect-with-id");
  13410. sse.set_reconnect_interval(100);
  13411. sse.set_max_reconnect_attempts(3);
  13412. sse.start_async();
  13413. // Wait for at least 2 connections
  13414. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13415. sse.stop();
  13416. // Verify behavior
  13417. std::lock_guard<std::mutex> lock(id_mutex);
  13418. EXPECT_GE(received_last_event_ids.size(), 2u);
  13419. // First connection should have no Last-Event-ID
  13420. if (!received_last_event_ids.empty()) {
  13421. EXPECT_EQ(received_last_event_ids[0], "");
  13422. }
  13423. // Second connection should have Last-Event-ID from first connection
  13424. if (received_last_event_ids.size() >= 2) {
  13425. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13426. }
  13427. }
  13428. // Test: set_headers updates headers used on reconnect
  13429. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13430. std::vector<std::string> received_tokens;
  13431. std::mutex token_mutex;
  13432. // Endpoint that captures Authorization header
  13433. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13434. {
  13435. std::lock_guard<std::mutex> lock(token_mutex);
  13436. received_tokens.push_back(req.get_header_value("Authorization"));
  13437. }
  13438. res.set_chunked_content_provider(
  13439. "text/event-stream", [](size_t offset, DataSink &sink) {
  13440. if (offset == 0) {
  13441. std::string event = "data: hello\n\n";
  13442. sink.write(event.data(), event.size());
  13443. }
  13444. return false; // Close connection to trigger reconnect
  13445. });
  13446. });
  13447. Client client("localhost", get_port());
  13448. Headers headers = {{"Authorization", "Bearer old-token"}};
  13449. sse::SSEClient sse(client, "/auth-check", headers);
  13450. // Update headers on each successful connection
  13451. sse.on_open(
  13452. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13453. sse.set_reconnect_interval(100);
  13454. sse.set_max_reconnect_attempts(3);
  13455. sse.start_async();
  13456. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13457. sse.stop();
  13458. std::lock_guard<std::mutex> lock(token_mutex);
  13459. ASSERT_GE(received_tokens.size(), 2u);
  13460. // First connection uses original header
  13461. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13462. // Second connection uses updated header from set_headers
  13463. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13464. }
  13465. // Test: 401 allows reconnection (so on_error can refresh headers)
  13466. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13467. std::atomic<int> connection_count{0};
  13468. // Endpoint: returns 401 on first attempt, 200 on second
  13469. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13470. int conn = connection_count.fetch_add(1);
  13471. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13472. res.status = StatusCode::Unauthorized_401;
  13473. res.set_content("Unauthorized", "text/plain");
  13474. return;
  13475. }
  13476. res.set_chunked_content_provider(
  13477. "text/event-stream", [](size_t offset, DataSink &sink) {
  13478. if (offset == 0) {
  13479. std::string event = "data: authenticated\n\n";
  13480. sink.write(event.data(), event.size());
  13481. }
  13482. return false;
  13483. });
  13484. });
  13485. Client client("localhost", get_port());
  13486. Headers headers = {{"Authorization", "Bearer expired"}};
  13487. sse::SSEClient sse(client, "/auth-retry", headers);
  13488. std::atomic<bool> message_received{false};
  13489. // Refresh token on error
  13490. sse.on_error(
  13491. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13492. sse.on_message([&](const sse::SSEMessage &msg) {
  13493. if (msg.data == "authenticated") { message_received.store(true); }
  13494. });
  13495. sse.set_reconnect_interval(100);
  13496. sse.set_max_reconnect_attempts(3);
  13497. sse.start_async();
  13498. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13499. sse.stop();
  13500. // Should have reconnected after 401 and succeeded with new token
  13501. EXPECT_GE(connection_count.load(), 2);
  13502. EXPECT_TRUE(message_received.load());
  13503. }
  13504. TEST(Issue2318Test, EmptyHostString) {
  13505. {
  13506. httplib::Client cli_empty("", PORT);
  13507. auto res = cli_empty.Get("/");
  13508. ASSERT_FALSE(res);
  13509. EXPECT_EQ(httplib::Error::Connection, res.error());
  13510. }
  13511. {
  13512. httplib::Client cli(" ", PORT);
  13513. auto res = cli.Get("/");
  13514. ASSERT_FALSE(res);
  13515. EXPECT_EQ(httplib::Error::Connection, res.error());
  13516. }
  13517. }
  13518. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13519. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13520. Server svr;
  13521. // Set a small payload limit (1KB)
  13522. svr.set_payload_max_length(1024);
  13523. svr.Post("/test", [&](const Request &req, Response &res) {
  13524. res.set_content("Body size: " + std::to_string(req.body.size()),
  13525. "text/plain");
  13526. });
  13527. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13528. auto se = detail::scope_exit([&] {
  13529. svr.stop();
  13530. listen_thread.join();
  13531. });
  13532. svr.wait_until_ready();
  13533. // Create data that compresses well but exceeds limit when decompressed
  13534. // 8KB of repeated null bytes compresses to a very small size
  13535. std::string original_data(8 * 1024, '\0');
  13536. // Compress the data using gzip
  13537. std::string compressed_data;
  13538. detail::gzip_compressor compressor;
  13539. compressor.compress(original_data.data(), original_data.size(), true,
  13540. [&](const char *data, size_t size) {
  13541. compressed_data.append(data, size);
  13542. return true;
  13543. });
  13544. // Verify compression worked (compressed should be much smaller)
  13545. ASSERT_LT(compressed_data.size(), original_data.size());
  13546. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13547. // Send compressed data with Content-Encoding: gzip
  13548. Client cli(HOST, PORT);
  13549. Headers headers = {{"Content-Encoding", "gzip"}};
  13550. auto res =
  13551. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13552. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13553. ASSERT_TRUE(res);
  13554. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13555. }
  13556. #endif
  13557. // ============================================================================
  13558. // OpenSSL-Specific Tests
  13559. // ============================================================================
  13560. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13561. X509 *readCertificate(const std::string &strFileName) {
  13562. std::ifstream inStream(strFileName);
  13563. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13564. std::istreambuf_iterator<char>());
  13565. if (strCertPEM.empty()) return (nullptr);
  13566. BIO *pbCert = BIO_new(BIO_s_mem());
  13567. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13568. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13569. BIO_free(pbCert);
  13570. return (pCert);
  13571. }
  13572. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13573. std::ifstream inStream(strFileName);
  13574. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13575. std::istreambuf_iterator<char>());
  13576. if (strPrivateKeyPEM.empty()) return (nullptr);
  13577. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13578. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13579. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13580. BIO_free(pbPrivKey);
  13581. return (pPrivateKey);
  13582. }
  13583. TEST(BindServerTest, UpdateCerts) {
  13584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13585. int port = svr.bind_to_any_port("0.0.0.0");
  13586. ASSERT_TRUE(svr.is_valid());
  13587. ASSERT_TRUE(port > 0);
  13588. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13589. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13590. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13591. ASSERT_TRUE(cert != nullptr);
  13592. ASSERT_TRUE(ca_cert != nullptr);
  13593. ASSERT_TRUE(key != nullptr);
  13594. X509_STORE *cert_store = X509_STORE_new();
  13595. X509_STORE_add_cert(cert_store, ca_cert);
  13596. // svr.update_certs(cert, key, cert_store); // deprecated
  13597. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13598. CLIENT_CA_CERT_FILE);
  13599. ASSERT_TRUE(svr.is_valid());
  13600. svr.stop();
  13601. X509_STORE_free(cert_store);
  13602. X509_free(cert);
  13603. X509_free(ca_cert);
  13604. EVP_PKEY_free(key);
  13605. }
  13606. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13607. // client CA list correctly for TLS handshake
  13608. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13609. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13610. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13611. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13612. ASSERT_TRUE(cert != nullptr);
  13613. ASSERT_TRUE(ca_cert != nullptr);
  13614. ASSERT_TRUE(key != nullptr);
  13615. X509_STORE *cert_store = X509_STORE_new();
  13616. X509_STORE_add_cert(cert_store, ca_cert);
  13617. // Use X509-based constructor (deprecated but should still work correctly)
  13618. #pragma GCC diagnostic push
  13619. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13620. SSLServer svr(cert, key, cert_store);
  13621. #pragma GCC diagnostic pop
  13622. ASSERT_TRUE(svr.is_valid());
  13623. // Verify that client CA list is set in SSL_CTX
  13624. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13625. ASSERT_TRUE(ssl_ctx != nullptr);
  13626. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13627. ASSERT_TRUE(ca_list != nullptr);
  13628. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13629. X509_free(cert);
  13630. X509_free(ca_cert);
  13631. EVP_PKEY_free(key);
  13632. }
  13633. // Test that update_certs() updates client CA list correctly
  13634. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13635. // Start with file-based constructor
  13636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13637. ASSERT_TRUE(svr.is_valid());
  13638. // Initially no client CA list should be set
  13639. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13640. ASSERT_TRUE(ssl_ctx != nullptr);
  13641. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13642. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13643. EXPECT_EQ(0, count_before);
  13644. // Now update with client CA (PEM string)
  13645. std::string cert_pem, key_pem, ca_pem;
  13646. read_file(SERVER_CERT_FILE, cert_pem);
  13647. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13648. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13649. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13650. ASSERT_TRUE(svr.is_valid());
  13651. // Now client CA list should be set
  13652. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13653. ASSERT_TRUE(ca_list_after != nullptr);
  13654. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13655. }
  13656. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13657. // Test that the file-path SSLServer constructor properly sets the client CA
  13658. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13660. ASSERT_TRUE(svr.is_valid());
  13661. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13662. ASSERT_TRUE(ssl_ctx != nullptr);
  13663. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13664. ASSERT_TRUE(ca_list != nullptr);
  13665. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13666. }
  13667. #endif
  13668. // ============================================================================
  13669. // MbedTLS-Specific Tests
  13670. // ============================================================================
  13671. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13672. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13673. using namespace httplib::tls;
  13674. // Track if callback was invoked
  13675. bool callback_invoked = false;
  13676. // The callback receives void* ctx which is actually MbedTlsContext*
  13677. // We can access the mbedtls_ssl_config via the context
  13678. auto setup_callback = [&callback_invoked](void *ctx) {
  13679. callback_invoked = true;
  13680. // Cast to MbedTlsContext* to access the ssl config
  13681. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13682. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13683. // Use static variables to hold certificate data (simplified for test)
  13684. static mbedtls_x509_crt own_cert;
  13685. static mbedtls_pk_context own_key;
  13686. static mbedtls_x509_crt ca_chain;
  13687. static bool initialized = false;
  13688. if (!initialized) {
  13689. mbedtls_x509_crt_init(&own_cert);
  13690. mbedtls_pk_init(&own_key);
  13691. mbedtls_x509_crt_init(&ca_chain);
  13692. // Load server certificate
  13693. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13694. return false;
  13695. }
  13696. // Load server private key
  13697. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13698. #if MBEDTLS_VERSION_MAJOR >= 3
  13699. ,
  13700. mbedtls_ctr_drbg_random, nullptr
  13701. #endif
  13702. ) != 0) {
  13703. return false;
  13704. }
  13705. // Load CA chain for client verification
  13706. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13707. return false;
  13708. }
  13709. initialized = true;
  13710. }
  13711. // Configure the SSL config
  13712. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13713. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13714. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13715. // Set minimum TLS version using mbedTLS native API
  13716. #if MBEDTLS_VERSION_MAJOR >= 3
  13717. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13718. #else
  13719. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13720. MBEDTLS_SSL_MINOR_VERSION_3);
  13721. #endif
  13722. return true;
  13723. };
  13724. SSLServer svr(setup_callback);
  13725. ASSERT_TRUE(svr.is_valid());
  13726. ASSERT_TRUE(callback_invoked);
  13727. svr.Get("/test", [&](const Request &req, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. auto cert = req.peer_cert();
  13730. ASSERT_TRUE(static_cast<bool>(cert));
  13731. auto common_name = cert.subject_cn();
  13732. EXPECT_EQ("Common Name", common_name);
  13733. });
  13734. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13735. auto se = detail::scope_exit([&] {
  13736. svr.stop();
  13737. t.join();
  13738. ASSERT_FALSE(svr.is_running());
  13739. });
  13740. svr.wait_until_ready();
  13741. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13742. cli.enable_server_certificate_verification(false);
  13743. cli.set_connection_timeout(30);
  13744. auto res = cli.Get("/test");
  13745. ASSERT_TRUE(res);
  13746. ASSERT_EQ(StatusCode::OK_200, res->status);
  13747. }
  13748. #endif
  13749. // WebSocket Tests
  13750. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13751. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13752. // defining the meaning of these bits has been negotiated.
  13753. auto make_frame = [](uint8_t first_byte) {
  13754. std::string frame;
  13755. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13756. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13757. frame += "Hello";
  13758. return frame;
  13759. };
  13760. // RSV1 set (0x40)
  13761. {
  13762. detail::BufferStream strm;
  13763. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13764. ws::Opcode opcode;
  13765. std::string payload;
  13766. bool fin;
  13767. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13768. false, 1024));
  13769. }
  13770. // RSV2 set (0x20)
  13771. {
  13772. detail::BufferStream strm;
  13773. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13774. ws::Opcode opcode;
  13775. std::string payload;
  13776. bool fin;
  13777. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13778. false, 1024));
  13779. }
  13780. // RSV3 set (0x10)
  13781. {
  13782. detail::BufferStream strm;
  13783. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13784. ws::Opcode opcode;
  13785. std::string payload;
  13786. bool fin;
  13787. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13788. false, 1024));
  13789. }
  13790. // No RSV bits set - should succeed
  13791. {
  13792. detail::BufferStream strm;
  13793. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13794. ws::Opcode opcode;
  13795. std::string payload;
  13796. bool fin;
  13797. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13798. false, 1024));
  13799. EXPECT_EQ(ws::Opcode::Text, opcode);
  13800. EXPECT_EQ("Hello", payload);
  13801. EXPECT_TRUE(fin);
  13802. }
  13803. }
  13804. TEST(WebSocketTest, ControlFrameValidation) {
  13805. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13806. // payload length <= 125.
  13807. // Ping with FIN=0 - must be rejected
  13808. {
  13809. detail::BufferStream strm;
  13810. std::string frame;
  13811. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13812. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13813. strm.write(frame.data(), frame.size());
  13814. ws::Opcode opcode;
  13815. std::string payload;
  13816. bool fin;
  13817. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13818. false, 1024));
  13819. }
  13820. // Close with FIN=0 - must be rejected
  13821. {
  13822. detail::BufferStream strm;
  13823. std::string frame;
  13824. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13825. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13826. strm.write(frame.data(), frame.size());
  13827. ws::Opcode opcode;
  13828. std::string payload;
  13829. bool fin;
  13830. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13831. false, 1024));
  13832. }
  13833. // Ping with payload_len=126 (extended length) - must be rejected
  13834. {
  13835. detail::BufferStream strm;
  13836. std::string frame;
  13837. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13838. frame += static_cast<char>(126); // payload_len=126 (>125)
  13839. frame += static_cast<char>(0x00); // extended length high byte
  13840. frame += static_cast<char>(126); // extended length low byte
  13841. frame += std::string(126, 'x');
  13842. strm.write(frame.data(), frame.size());
  13843. ws::Opcode opcode;
  13844. std::string payload;
  13845. bool fin;
  13846. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13847. false, 1024));
  13848. }
  13849. // Ping with FIN=1 and payload_len=125 - should succeed
  13850. {
  13851. detail::BufferStream strm;
  13852. std::string frame;
  13853. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13854. frame += static_cast<char>(125); // payload_len=125
  13855. frame += std::string(125, 'x');
  13856. strm.write(frame.data(), frame.size());
  13857. ws::Opcode opcode;
  13858. std::string payload;
  13859. bool fin;
  13860. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13861. false, 1024));
  13862. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13863. EXPECT_EQ(125u, payload.size());
  13864. EXPECT_TRUE(fin);
  13865. }
  13866. }
  13867. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13868. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13869. // length MUST be 0.
  13870. // MSB set - must be rejected
  13871. {
  13872. detail::BufferStream strm;
  13873. std::string frame;
  13874. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13875. frame += static_cast<char>(127); // 64-bit extended length
  13876. frame += static_cast<char>(0x80); // MSB set (invalid)
  13877. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13878. strm.write(frame.data(), frame.size());
  13879. ws::Opcode opcode;
  13880. std::string payload;
  13881. bool fin;
  13882. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13883. false, 1024));
  13884. }
  13885. // MSB clear - should pass length parsing (will be rejected by max_len,
  13886. // but that's a different check; use a small length to verify)
  13887. {
  13888. detail::BufferStream strm;
  13889. std::string frame;
  13890. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13891. frame += static_cast<char>(127); // 64-bit extended length
  13892. frame += std::string(7, '\0'); // high bytes = 0
  13893. frame += static_cast<char>(0x03); // length = 3
  13894. frame += "abc";
  13895. strm.write(frame.data(), frame.size());
  13896. ws::Opcode opcode;
  13897. std::string payload;
  13898. bool fin;
  13899. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13900. false, 1024));
  13901. EXPECT_EQ(ws::Opcode::Text, opcode);
  13902. EXPECT_EQ("abc", payload);
  13903. }
  13904. }
  13905. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13906. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13907. // Valid UTF-8
  13908. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13909. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13910. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13911. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13912. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13913. // Invalid UTF-8
  13914. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13915. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13916. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13917. EXPECT_FALSE(
  13918. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13919. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13920. }
  13921. TEST(WebSocketTest, ConnectAndDisconnect) {
  13922. Server svr;
  13923. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13924. std::string msg;
  13925. while (ws.read(msg)) {}
  13926. });
  13927. auto port = svr.bind_to_any_port(HOST);
  13928. std::thread t([&]() { svr.listen_after_bind(); });
  13929. svr.wait_until_ready();
  13930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13931. ASSERT_TRUE(client.connect());
  13932. EXPECT_TRUE(client.is_open());
  13933. client.close();
  13934. EXPECT_FALSE(client.is_open());
  13935. svr.stop();
  13936. t.join();
  13937. }
  13938. TEST(WebSocketTest, ValidURL) {
  13939. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13940. EXPECT_TRUE(ws1.is_valid());
  13941. ws::WebSocketClient ws2("ws://example.com/path");
  13942. EXPECT_TRUE(ws2.is_valid());
  13943. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13944. EXPECT_TRUE(ws3.is_valid());
  13945. #ifdef CPPHTTPLIB_SSL_ENABLED
  13946. ws::WebSocketClient wss1("wss://example.com/path");
  13947. EXPECT_TRUE(wss1.is_valid());
  13948. ws::WebSocketClient wss2("wss://example.com:443/path");
  13949. EXPECT_TRUE(wss2.is_valid());
  13950. #endif
  13951. }
  13952. TEST(WebSocketTest, InvalidURL) {
  13953. // No scheme
  13954. ws::WebSocketClient ws1("localhost:8080/path");
  13955. EXPECT_FALSE(ws1.is_valid());
  13956. // No path
  13957. ws::WebSocketClient ws2("ws://localhost:8080");
  13958. EXPECT_FALSE(ws2.is_valid());
  13959. // Empty string
  13960. ws::WebSocketClient ws3("");
  13961. EXPECT_FALSE(ws3.is_valid());
  13962. // Missing host
  13963. ws::WebSocketClient ws4("ws://:8080/path");
  13964. EXPECT_FALSE(ws4.is_valid());
  13965. // Port number overflow — should not crash
  13966. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  13967. EXPECT_FALSE(ws5.is_valid());
  13968. // Port out of range
  13969. ws::WebSocketClient ws6("ws://localhost:99999/path");
  13970. EXPECT_FALSE(ws6.is_valid());
  13971. }
  13972. TEST(WebSocketTest, UnsupportedScheme) {
  13973. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13974. ws::WebSocketClient ws1("http://localhost:8080/path");
  13975. EXPECT_FALSE(ws1.is_valid());
  13976. ws::WebSocketClient ws2("https://localhost:8080/path");
  13977. EXPECT_FALSE(ws2.is_valid());
  13978. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13979. EXPECT_FALSE(ws3.is_valid());
  13980. #else
  13981. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13982. std::invalid_argument);
  13983. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13984. std::invalid_argument);
  13985. #endif
  13986. }
  13987. TEST(WebSocketTest, ConnectWhenInvalid) {
  13988. ws::WebSocketClient ws("not a valid url");
  13989. EXPECT_FALSE(ws.is_valid());
  13990. EXPECT_FALSE(ws.connect());
  13991. }
  13992. TEST(WebSocketTest, DefaultPort) {
  13993. ws::WebSocketClient ws1("ws://example.com/path");
  13994. EXPECT_TRUE(ws1.is_valid());
  13995. // ws:// defaults to port 80 (verified by successful parse)
  13996. #ifdef CPPHTTPLIB_SSL_ENABLED
  13997. ws::WebSocketClient ws2("wss://example.com/path");
  13998. EXPECT_TRUE(ws2.is_valid());
  13999. // wss:// defaults to port 443 (verified by successful parse)
  14000. #endif
  14001. }
  14002. TEST(WebSocketTest, IPv6LiteralAddress) {
  14003. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14004. EXPECT_TRUE(ws1.is_valid());
  14005. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14006. EXPECT_TRUE(ws2.is_valid());
  14007. }
  14008. TEST(WebSocketTest, ComplexPath) {
  14009. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14010. EXPECT_TRUE(ws1.is_valid());
  14011. ws::WebSocketClient ws2("ws://localhost:8080/");
  14012. EXPECT_TRUE(ws2.is_valid());
  14013. }
  14014. class WebSocketIntegrationTest : public ::testing::Test {
  14015. protected:
  14016. void SetUp() override {
  14017. server_ = httplib::detail::make_unique<Server>();
  14018. setup_server();
  14019. start_server();
  14020. }
  14021. void TearDown() override {
  14022. server_->stop();
  14023. if (server_thread_.joinable()) { server_thread_.join(); }
  14024. }
  14025. void setup_server() {
  14026. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14027. std::string msg;
  14028. ws::ReadResult ret;
  14029. while ((ret = ws.read(msg))) {
  14030. if (ret == ws::Binary) {
  14031. ws.send(msg.data(), msg.size());
  14032. } else {
  14033. ws.send(msg);
  14034. }
  14035. }
  14036. });
  14037. server_->WebSocket("/ws-echo-string",
  14038. [](const Request &, ws::WebSocket &ws) {
  14039. std::string msg;
  14040. while (ws.read(msg)) {
  14041. ws.send("echo: " + msg);
  14042. }
  14043. });
  14044. server_->WebSocket(
  14045. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14046. // Echo back request metadata
  14047. ws.send("path:" + req.path);
  14048. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14049. std::string msg;
  14050. while (ws.read(msg)) {}
  14051. });
  14052. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14053. std::string msg;
  14054. ws.read(msg); // wait for a message
  14055. ws.close();
  14056. });
  14057. server_->WebSocket("/ws-close-status",
  14058. [](const Request &, ws::WebSocket &ws) {
  14059. std::string msg;
  14060. ws.read(msg); // wait for a message
  14061. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14062. });
  14063. server_->WebSocket(
  14064. "/ws-subprotocol",
  14065. [](const Request &, ws::WebSocket &ws) {
  14066. std::string msg;
  14067. while (ws.read(msg)) {
  14068. ws.send(msg);
  14069. }
  14070. },
  14071. [](const std::vector<std::string> &protocols) -> std::string {
  14072. for (const auto &p : protocols) {
  14073. if (p == "graphql-ws") { return p; }
  14074. }
  14075. return "";
  14076. });
  14077. }
  14078. void start_server() {
  14079. port_ = server_->bind_to_any_port(HOST);
  14080. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14081. server_->wait_until_ready();
  14082. }
  14083. std::unique_ptr<Server> server_;
  14084. std::thread server_thread_;
  14085. int port_ = 0;
  14086. };
  14087. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14089. "/ws-echo");
  14090. ASSERT_TRUE(client.connect());
  14091. ASSERT_TRUE(client.is_open());
  14092. ASSERT_TRUE(client.send("Hello WebSocket"));
  14093. std::string msg;
  14094. EXPECT_EQ(ws::Text, client.read(msg));
  14095. EXPECT_EQ("Hello WebSocket", msg);
  14096. client.close();
  14097. }
  14098. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14099. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14100. "/ws-echo");
  14101. ASSERT_TRUE(client.connect());
  14102. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14103. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14104. std::string msg;
  14105. EXPECT_EQ(ws::Binary, client.read(msg));
  14106. EXPECT_EQ(binary_data, msg);
  14107. client.close();
  14108. }
  14109. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14111. "/ws-echo");
  14112. ASSERT_TRUE(client.connect());
  14113. for (int i = 0; i < 10; i++) {
  14114. auto text = "message " + std::to_string(i);
  14115. ASSERT_TRUE(client.send(text));
  14116. std::string msg;
  14117. ASSERT_TRUE(client.read(msg));
  14118. EXPECT_EQ(text, msg);
  14119. }
  14120. client.close();
  14121. }
  14122. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14123. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14124. "/ws-close");
  14125. ASSERT_TRUE(client.connect());
  14126. // Send a message to trigger the server to close
  14127. ASSERT_TRUE(client.send("trigger close"));
  14128. // The server will close, so read should return false
  14129. std::string msg;
  14130. EXPECT_FALSE(client.read(msg));
  14131. EXPECT_FALSE(client.is_open());
  14132. }
  14133. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14134. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14135. "/ws-echo");
  14136. ASSERT_TRUE(client.connect());
  14137. // 128KB message
  14138. std::string large_data(128 * 1024, 'X');
  14139. ASSERT_TRUE(client.send(large_data));
  14140. std::string msg;
  14141. ASSERT_TRUE(client.read(msg));
  14142. EXPECT_EQ(large_data, msg);
  14143. client.close();
  14144. }
  14145. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14147. "/ws-echo");
  14148. ASSERT_TRUE(client.connect());
  14149. const int num_threads = 4;
  14150. std::vector<std::thread> threads;
  14151. std::atomic<int> send_count{0};
  14152. for (int t = 0; t < num_threads; t++) {
  14153. threads.emplace_back([&client, &send_count, t]() {
  14154. for (int i = 0; i < 5; i++) {
  14155. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14156. if (client.send(text)) { send_count++; }
  14157. }
  14158. });
  14159. }
  14160. for (auto &th : threads) {
  14161. th.join();
  14162. }
  14163. int received = 0;
  14164. std::string msg;
  14165. while (received < send_count.load()) {
  14166. if (!client.read(msg)) { break; }
  14167. received++;
  14168. }
  14169. EXPECT_EQ(send_count.load(), received);
  14170. client.close();
  14171. }
  14172. TEST_F(WebSocketIntegrationTest, ReadString) {
  14173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14174. "/ws-echo-string");
  14175. ASSERT_TRUE(client.connect());
  14176. ASSERT_TRUE(client.send("hello"));
  14177. std::string msg;
  14178. ASSERT_TRUE(client.read(msg));
  14179. EXPECT_EQ("echo: hello", msg);
  14180. ASSERT_TRUE(client.send("world"));
  14181. ASSERT_TRUE(client.read(msg));
  14182. EXPECT_EQ("echo: world", msg);
  14183. client.close();
  14184. }
  14185. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14186. Headers headers = {{"X-Test-Header", "test-value"}};
  14187. ws::WebSocketClient client(
  14188. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14189. ASSERT_TRUE(client.connect());
  14190. std::string msg;
  14191. ASSERT_TRUE(client.read(msg));
  14192. EXPECT_EQ("path:/ws-request-info", msg);
  14193. ASSERT_TRUE(client.read(msg));
  14194. EXPECT_EQ("header:test-value", msg);
  14195. client.close();
  14196. }
  14197. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14198. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14199. "/ws-echo");
  14200. client.set_read_timeout(1, 0); // 1 second
  14201. ASSERT_TRUE(client.connect());
  14202. // Don't send anything — server echo handler waits for a message,
  14203. // so read() should time out and return false.
  14204. std::string msg;
  14205. EXPECT_FALSE(client.read(msg));
  14206. }
  14207. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14208. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14209. "/ws-echo");
  14210. client.set_read_timeout(5, 0);
  14211. ASSERT_TRUE(client.connect());
  14212. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14213. // The server should reject it and close the connection.
  14214. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14215. client.send(oversized);
  14216. // The server's read() should have failed due to payload limit,
  14217. // so our read() should return false (connection closed).
  14218. std::string msg;
  14219. EXPECT_FALSE(client.read(msg));
  14220. }
  14221. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14222. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14223. "/ws-echo");
  14224. client.set_read_timeout(10, 0);
  14225. ASSERT_TRUE(client.connect());
  14226. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14227. // This should succeed.
  14228. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14229. ASSERT_TRUE(client.send(at_limit));
  14230. std::string msg;
  14231. ASSERT_TRUE(client.read(msg));
  14232. EXPECT_EQ(at_limit.size(), msg.size());
  14233. client.close();
  14234. }
  14235. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14236. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14237. "/nonexistent");
  14238. EXPECT_FALSE(client.connect());
  14239. EXPECT_FALSE(client.is_open());
  14240. }
  14241. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14242. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14243. "/ws-echo");
  14244. ASSERT_TRUE(client.connect());
  14245. ASSERT_TRUE(client.send(""));
  14246. std::string msg;
  14247. EXPECT_EQ(ws::Text, client.read(msg));
  14248. EXPECT_EQ("", msg);
  14249. client.close();
  14250. }
  14251. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14252. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14253. "/ws-echo");
  14254. // First connection
  14255. ASSERT_TRUE(client.connect());
  14256. ASSERT_TRUE(client.send("first"));
  14257. std::string msg;
  14258. ASSERT_TRUE(client.read(msg));
  14259. EXPECT_EQ("first", msg);
  14260. client.close();
  14261. EXPECT_FALSE(client.is_open());
  14262. // Reconnect using the same client object
  14263. ASSERT_TRUE(client.connect());
  14264. ASSERT_TRUE(client.is_open());
  14265. ASSERT_TRUE(client.send("second"));
  14266. ASSERT_TRUE(client.read(msg));
  14267. EXPECT_EQ("second", msg);
  14268. client.close();
  14269. }
  14270. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14271. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14272. "/ws-close-status");
  14273. ASSERT_TRUE(client.connect());
  14274. // Trigger the server to close with GoingAway status
  14275. ASSERT_TRUE(client.send("trigger"));
  14276. // read() should return false after receiving the close frame
  14277. std::string msg;
  14278. EXPECT_FALSE(client.read(msg));
  14279. EXPECT_FALSE(client.is_open());
  14280. }
  14281. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14282. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14283. "/ws-echo");
  14284. ASSERT_TRUE(client.connect());
  14285. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14286. EXPECT_FALSE(client.is_open());
  14287. }
  14288. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14289. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14290. ws::WebSocketClient client(
  14291. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14292. ASSERT_TRUE(client.connect());
  14293. // Server should have selected graphql-ws
  14294. EXPECT_EQ("graphql-ws", client.subprotocol());
  14295. client.close();
  14296. }
  14297. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14298. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14299. ws::WebSocketClient client(
  14300. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14301. ASSERT_TRUE(client.connect());
  14302. // Server should not have selected any subprotocol
  14303. EXPECT_TRUE(client.subprotocol().empty());
  14304. client.close();
  14305. }
  14306. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14307. // Connect without requesting any subprotocol
  14308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14309. "/ws-subprotocol");
  14310. ASSERT_TRUE(client.connect());
  14311. EXPECT_TRUE(client.subprotocol().empty());
  14312. client.close();
  14313. }
  14314. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14316. "/ws-echo");
  14317. client.set_tcp_nodelay(true);
  14318. client.set_address_family(AF_INET);
  14319. client.set_connection_timeout(3, 0);
  14320. bool socket_options_called = false;
  14321. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14322. ASSERT_TRUE(client.connect());
  14323. ASSERT_TRUE(client.is_open());
  14324. EXPECT_TRUE(socket_options_called);
  14325. ASSERT_TRUE(client.send("hello"));
  14326. std::string msg;
  14327. auto result = client.read(msg);
  14328. EXPECT_EQ(result, ws::ReadResult::Text);
  14329. EXPECT_EQ(msg, "hello");
  14330. client.close();
  14331. }
  14332. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14333. Server svr;
  14334. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14335. if (!req.has_header("Authorization")) {
  14336. res.status = StatusCode::Unauthorized_401;
  14337. res.set_content("Unauthorized", "text/plain");
  14338. return Server::HandlerResponse::Handled;
  14339. }
  14340. return Server::HandlerResponse::Unhandled;
  14341. });
  14342. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14343. std::string msg;
  14344. while (ws.read(msg)) {
  14345. ws.send(msg);
  14346. }
  14347. });
  14348. auto port = svr.bind_to_any_port("localhost");
  14349. std::thread t([&]() { svr.listen_after_bind(); });
  14350. svr.wait_until_ready();
  14351. // Without Authorization header - should be rejected before upgrade
  14352. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14353. EXPECT_FALSE(client1.connect());
  14354. // With Authorization header - should succeed
  14355. Headers headers = {{"Authorization", "Bearer token123"}};
  14356. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14357. headers);
  14358. ASSERT_TRUE(client2.connect());
  14359. ASSERT_TRUE(client2.send("hello"));
  14360. std::string msg;
  14361. ASSERT_TRUE(client2.read(msg));
  14362. EXPECT_EQ("hello", msg);
  14363. client2.close();
  14364. svr.stop();
  14365. t.join();
  14366. }
  14367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14368. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14369. protected:
  14370. void SetUp() override {
  14371. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14372. SERVER_PRIVATE_KEY_FILE);
  14373. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14374. std::string msg;
  14375. ws::ReadResult ret;
  14376. while ((ret = ws.read(msg))) {
  14377. if (ret == ws::Binary) {
  14378. ws.send(msg.data(), msg.size());
  14379. } else {
  14380. ws.send(msg);
  14381. }
  14382. }
  14383. });
  14384. port_ = server_->bind_to_any_port(HOST);
  14385. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14386. server_->wait_until_ready();
  14387. }
  14388. void TearDown() override {
  14389. server_->stop();
  14390. if (server_thread_.joinable()) { server_thread_.join(); }
  14391. }
  14392. std::unique_ptr<SSLServer> server_;
  14393. std::thread server_thread_;
  14394. int port_ = 0;
  14395. };
  14396. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14397. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14398. "/ws-echo");
  14399. client.enable_server_certificate_verification(false);
  14400. ASSERT_TRUE(client.connect());
  14401. ASSERT_TRUE(client.is_open());
  14402. ASSERT_TRUE(client.send("Hello WSS"));
  14403. std::string msg;
  14404. EXPECT_EQ(ws::Text, client.read(msg));
  14405. EXPECT_EQ("Hello WSS", msg);
  14406. client.close();
  14407. }
  14408. #endif
  14409. #if !defined(_WIN32)
  14410. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14411. auto secret_dir = std::string("./symlink_test_secret");
  14412. auto served_dir = std::string("./symlink_test_served");
  14413. auto secret_file = secret_dir + "/secret.txt";
  14414. auto symlink_path = served_dir + "/escape";
  14415. // Setup: create directories and files
  14416. mkdir(secret_dir.c_str(), 0755);
  14417. mkdir(served_dir.c_str(), 0755);
  14418. {
  14419. std::ofstream ofs(secret_file);
  14420. ofs << "SECRET_DATA";
  14421. }
  14422. // Create symlink using absolute path so it resolves correctly
  14423. char abs_secret[PATH_MAX];
  14424. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14425. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14426. auto se = detail::scope_exit([&] {
  14427. unlink(symlink_path.c_str());
  14428. unlink(secret_file.c_str());
  14429. rmdir(served_dir.c_str());
  14430. rmdir(secret_dir.c_str());
  14431. });
  14432. Server svr;
  14433. svr.set_mount_point("/", served_dir);
  14434. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14435. auto se2 = detail::scope_exit([&] {
  14436. svr.stop();
  14437. listen_thread.join();
  14438. });
  14439. svr.wait_until_ready();
  14440. Client cli("localhost", PORT);
  14441. // Symlink pointing outside base dir should be blocked
  14442. auto res = cli.Get("/escape/secret.txt");
  14443. ASSERT_TRUE(res);
  14444. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14445. }
  14446. #endif
  14447. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14448. // A GET request with Content-Length to a static file handler must have its
  14449. // body drained before the keep-alive connection is reused. Otherwise the
  14450. // unread body bytes are interpreted as the next HTTP request.
  14451. //
  14452. // The body is sent AFTER receiving the first response (as in the original
  14453. // PoC) so that the stream_line_reader cannot buffer it together with the
  14454. // headers of the first request.
  14455. Server svr;
  14456. svr.set_mount_point("/", "./www");
  14457. std::atomic<int> smuggled_count(0);
  14458. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14459. smuggled_count++;
  14460. res.set_content("oops", "text/plain");
  14461. });
  14462. auto port = svr.bind_to_any_port("localhost");
  14463. thread t = thread([&] { svr.listen_after_bind(); });
  14464. auto se = detail::scope_exit([&] {
  14465. svr.stop();
  14466. t.join();
  14467. });
  14468. svr.wait_until_ready();
  14469. auto error = Error::Success;
  14470. auto sock = detail::create_client_socket(
  14471. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14472. /*connection_timeout_sec=*/2, 0,
  14473. /*read_timeout_sec=*/2, 0,
  14474. /*write_timeout_sec=*/2, 0, std::string(), error);
  14475. ASSERT_NE(INVALID_SOCKET, sock);
  14476. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14477. // The "smuggled" request will be sent as the body of the outer GET
  14478. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14479. "Host: localhost\r\n"
  14480. "Connection: close\r\n"
  14481. "\r\n";
  14482. // Step 1: Send only the outer request headers (no body yet)
  14483. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14484. "Host: localhost\r\n"
  14485. "Content-Length: " +
  14486. std::to_string(smuggled.size()) +
  14487. "\r\n"
  14488. "\r\n";
  14489. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14490. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14491. // Step 2: Read the first response (server serves file without reading body)
  14492. std::string first_response;
  14493. char buf[4096];
  14494. for (;;) {
  14495. auto n = recv(sock, buf, sizeof(buf), 0);
  14496. if (n <= 0) break;
  14497. first_response.append(buf, static_cast<size_t>(n));
  14498. // Stop once we have a complete response (headers + body)
  14499. auto hdr_end = first_response.find("\r\n\r\n");
  14500. if (hdr_end != std::string::npos) {
  14501. // Check for Content-Length to know when the body is complete
  14502. auto cl_pos = first_response.find("Content-Length:");
  14503. if (cl_pos != std::string::npos) {
  14504. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14505. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14506. auto cl = std::stoul(
  14507. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14508. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14509. } else {
  14510. break; // No Content-Length, assume headers-only response
  14511. }
  14512. }
  14513. }
  14514. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14515. // Step 3: Now send the body, which looks like a new HTTP request.
  14516. // On a vulnerable server the keep-alive loop reads this as a second request.
  14517. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14518. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14519. // Step 4: Try to read a second response (should NOT exist after fix)
  14520. std::string second_response;
  14521. for (;;) {
  14522. auto n = recv(sock, buf, sizeof(buf), 0);
  14523. if (n <= 0) break;
  14524. second_response.append(buf, static_cast<size_t>(n));
  14525. }
  14526. // The smuggled request must NOT have been processed
  14527. EXPECT_EQ(0, smuggled_count.load());
  14528. }
  14529. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14530. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14531. // must be rejected with 400 Bad Request.
  14532. Server svr;
  14533. svr.Post("/test", [&](const Request &, Response &res) {
  14534. res.set_content("ok", "text/plain");
  14535. });
  14536. thread t = thread([&] { svr.listen(HOST, PORT); });
  14537. auto se = detail::scope_exit([&] {
  14538. svr.stop();
  14539. t.join();
  14540. ASSERT_FALSE(svr.is_running());
  14541. });
  14542. svr.wait_until_ready();
  14543. // Exact "chunked"
  14544. {
  14545. auto req = "POST /test HTTP/1.1\r\n"
  14546. "Host: localhost\r\n"
  14547. "Content-Length: 5\r\n"
  14548. "Transfer-Encoding: chunked\r\n"
  14549. "Connection: close\r\n"
  14550. "\r\n"
  14551. "hello";
  14552. std::string response;
  14553. ASSERT_TRUE(send_request(1, req, &response));
  14554. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14555. response.substr(0, response.find("\r\n")));
  14556. }
  14557. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14558. {
  14559. auto req = "POST /test HTTP/1.1\r\n"
  14560. "Host: localhost\r\n"
  14561. "Content-Length: 5\r\n"
  14562. "Transfer-Encoding: gzip, chunked\r\n"
  14563. "Connection: close\r\n"
  14564. "\r\n"
  14565. "hello";
  14566. std::string response;
  14567. ASSERT_TRUE(send_request(1, req, &response));
  14568. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14569. response.substr(0, response.find("\r\n")));
  14570. }
  14571. }