1
0

test.cc 511 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674
  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. const int PORT = get_base_port();
  57. const string LONG_QUERY_VALUE = string(25000, '@');
  58. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  59. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  60. const string TOO_LONG_QUERY_URL =
  61. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  62. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  63. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  64. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  65. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  66. return file.name == key;
  67. });
  68. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  69. return *it;
  70. #else
  71. if (it != items.end()) { return *it; }
  72. throw std::runtime_error("invalid multipart form data name error");
  73. #endif
  74. }
  75. static void read_file(const std::string &path, std::string &out) {
  76. std::ifstream fs(path, std::ios_base::binary);
  77. if (!fs) {
  78. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  79. return;
  80. #else
  81. throw std::runtime_error("File not found: " + path);
  82. #endif
  83. }
  84. fs.seekg(0, std::ios_base::end);
  85. auto size = fs.tellg();
  86. fs.seekg(0);
  87. out.resize(static_cast<size_t>(size));
  88. fs.read(&out[0], static_cast<std::streamsize>(size));
  89. }
  90. void performance_test(const char *host) {
  91. Server svr;
  92. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  93. res.set_content("Benchmark Response", "text/plain");
  94. });
  95. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  96. auto se = detail::scope_exit([&] {
  97. svr.stop();
  98. listen_thread.join();
  99. ASSERT_FALSE(svr.is_running());
  100. });
  101. svr.wait_until_ready();
  102. Client cli(host, PORT);
  103. // Warm-up request to establish connection and resolve DNS
  104. auto warmup_res = cli.Get("/benchmark");
  105. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  106. // Run multiple trials and collect timings
  107. const int num_trials = 20;
  108. std::vector<int64_t> timings;
  109. timings.reserve(num_trials);
  110. for (int i = 0; i < num_trials; i++) {
  111. auto start = std::chrono::high_resolution_clock::now();
  112. auto res = cli.Get("/benchmark");
  113. auto end = std::chrono::high_resolution_clock::now();
  114. auto elapsed =
  115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  116. .count();
  117. // Assertions after timing measurement to avoid overhead
  118. ASSERT_TRUE(res);
  119. EXPECT_EQ(StatusCode::OK_200, res->status);
  120. timings.push_back(elapsed);
  121. }
  122. // Calculate 25th percentile (lower quartile)
  123. std::sort(timings.begin(), timings.end());
  124. auto p25 = timings[num_trials / 4];
  125. // Format timings for output
  126. std::ostringstream timings_str;
  127. timings_str << "[";
  128. for (size_t i = 0; i < timings.size(); i++) {
  129. if (i > 0) timings_str << ", ";
  130. timings_str << timings[i];
  131. }
  132. timings_str << "]";
  133. // Localhost HTTP GET should be fast even in CI environments
  134. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  135. << "ms (Issue #1777). Timings: " << timings_str.str();
  136. }
  137. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  138. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  139. class UnixSocketTest : public ::testing::Test {
  140. protected:
  141. void TearDown() override { std::remove(pathname_.c_str()); }
  142. void client_GET(const std::string &addr) {
  143. httplib::Client cli{addr};
  144. cli.set_address_family(AF_UNIX);
  145. ASSERT_TRUE(cli.is_valid());
  146. const auto &result = cli.Get(pattern_);
  147. ASSERT_TRUE(result) << "error: " << result.error();
  148. const auto &resp = result.value();
  149. EXPECT_EQ(resp.status, StatusCode::OK_200);
  150. EXPECT_EQ(resp.body, content_);
  151. }
  152. static std::string make_sock_path() {
  153. const char *shard = getenv("GTEST_SHARD_INDEX");
  154. return shard ? std::string("./httplib-server-") + shard + ".sock"
  155. : "./httplib-server.sock";
  156. }
  157. const std::string pathname_{make_sock_path()};
  158. const std::string pattern_{"/hi"};
  159. const std::string content_{"Hello World!"};
  160. };
  161. TEST_F(UnixSocketTest, pathname) {
  162. httplib::Server svr;
  163. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  164. res.set_content(content_, "text/plain");
  165. });
  166. std::thread t{[&] {
  167. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  168. }};
  169. auto se = detail::scope_exit([&] {
  170. svr.stop();
  171. t.join();
  172. ASSERT_FALSE(svr.is_running());
  173. });
  174. svr.wait_until_ready();
  175. ASSERT_TRUE(svr.is_running());
  176. client_GET(pathname_);
  177. }
  178. #if defined(__linux__) || \
  179. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  180. TEST_F(UnixSocketTest, PeerPid) {
  181. httplib::Server svr;
  182. std::string remote_port_val;
  183. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. remote_port_val = std::to_string(req.remote_port);
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(pathname_);
  198. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  199. }
  200. #endif
  201. #ifdef __linux__
  202. TEST_F(UnixSocketTest, abstract) {
  203. constexpr char svr_path[]{"\x00httplib-server.sock"};
  204. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  205. httplib::Server svr;
  206. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. client_GET(abstract_addr);
  220. }
  221. #endif
  222. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  223. httplib::Server svr;
  224. std::string received_host_header;
  225. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  226. // Capture the Host header sent by the client
  227. auto host_iter = req.headers.find("Host");
  228. if (host_iter != req.headers.end()) {
  229. received_host_header = host_iter->second;
  230. }
  231. res.set_content(content_, "text/plain");
  232. });
  233. std::thread t{[&] {
  234. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  235. }};
  236. auto se = detail::scope_exit([&] {
  237. svr.stop();
  238. t.join();
  239. ASSERT_FALSE(svr.is_running());
  240. });
  241. svr.wait_until_ready();
  242. ASSERT_TRUE(svr.is_running());
  243. // Test that Host header is automatically set to "localhost" for Unix socket
  244. // connections
  245. httplib::Client cli{pathname_};
  246. cli.set_address_family(AF_UNIX);
  247. ASSERT_TRUE(cli.is_valid());
  248. const auto &result = cli.Get(pattern_);
  249. ASSERT_TRUE(result) << "error: " << result.error();
  250. const auto &resp = result.value();
  251. EXPECT_EQ(resp.status, StatusCode::OK_200);
  252. EXPECT_EQ(resp.body, content_);
  253. // Verify that Host header was automatically set to "localhost"
  254. EXPECT_EQ(received_host_header, "localhost");
  255. }
  256. #ifndef _WIN32
  257. TEST(SocketStream, wait_writable_UNIX) {
  258. int fds[2];
  259. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  260. const auto asSocketStream = [&](socket_t fd,
  261. std::function<bool(Stream &)> func) {
  262. return detail::process_client_socket(
  263. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  264. };
  265. asSocketStream(fds[0], [&](Stream &s0) {
  266. EXPECT_EQ(s0.socket(), fds[0]);
  267. EXPECT_TRUE(s0.wait_writable());
  268. EXPECT_EQ(0, close(fds[1]));
  269. EXPECT_FALSE(s0.wait_writable());
  270. return true;
  271. });
  272. EXPECT_EQ(0, close(fds[0]));
  273. }
  274. TEST(SocketStream, wait_writable_INET) {
  275. sockaddr_in addr;
  276. memset(&addr, 0, sizeof(addr));
  277. addr.sin_family = AF_INET;
  278. addr.sin_port = htons(PORT + 1);
  279. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  280. int disconnected_svr_sock = -1;
  281. std::thread svr{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, listen(s, 1));
  286. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  287. ASSERT_EQ(0, close(s));
  288. }};
  289. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  290. std::thread cli{[&] {
  291. const int s = socket(AF_INET, SOCK_STREAM, 0);
  292. ASSERT_LE(0, s);
  293. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  294. ASSERT_EQ(0, close(s));
  295. }};
  296. cli.join();
  297. svr.join();
  298. ASSERT_NE(disconnected_svr_sock, -1);
  299. const auto asSocketStream = [&](socket_t fd,
  300. std::function<bool(Stream &)> func) {
  301. return detail::process_client_socket(
  302. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  303. };
  304. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  305. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  306. EXPECT_FALSE(ss.wait_writable());
  307. return true;
  308. });
  309. ASSERT_EQ(0, close(disconnected_svr_sock));
  310. }
  311. #endif // #ifndef _WIN32
  312. TEST(ClientTest, MoveConstructible) {
  313. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  314. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  315. }
  316. TEST(ClientTest, MoveAssignable) {
  317. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  318. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  319. }
  320. #ifdef _WIN32
  321. TEST(StartupTest, WSAStartup) {
  322. WSADATA wsaData;
  323. int ret = WSAStartup(0x0002, &wsaData);
  324. ASSERT_EQ(0, ret);
  325. }
  326. #endif
  327. TEST(DecodePathTest, PercentCharacter) {
  328. EXPECT_EQ(
  329. decode_path_component(
  330. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  331. U8("descrip=Gastos áéíóúñÑ 6"));
  332. }
  333. TEST(DecodePathTest, PercentCharacterNUL) {
  334. string expected;
  335. expected.push_back('x');
  336. expected.push_back('\0');
  337. expected.push_back('x');
  338. EXPECT_EQ(decode_path_component("x%00x"), expected);
  339. }
  340. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  341. string unescapedCharacters = "-_.!~*'()";
  342. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  343. }
  344. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  345. string reservedCharacters = ";,/?:@&=+$";
  346. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  347. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  348. }
  349. TEST(ClientQueryOrder, PreserveOrder) {
  350. // This test reproduces Issue #2259: client may reorder query parameters
  351. // when sending a GET request. The expected behavior is that the client
  352. // preserves the original query string order when the caller supplied it
  353. // as part of the path.
  354. Server svr;
  355. svr.Get("/", [&](const Request &req, Response &res) {
  356. // Echo back the raw target so the test can assert ordering
  357. res.set_content(req.target, "text/plain");
  358. });
  359. std::thread t{[&] { svr.listen(HOST, PORT); }};
  360. auto se = detail::scope_exit([&] {
  361. svr.stop();
  362. t.join();
  363. ASSERT_FALSE(svr.is_running());
  364. });
  365. svr.wait_until_ready();
  366. Client cli(HOST, PORT);
  367. ASSERT_TRUE(cli.is_valid());
  368. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  369. auto res = cli.Get(original);
  370. ASSERT_TRUE(res);
  371. // Expect the echoed target to exactly match the original path (order
  372. // preserved)
  373. EXPECT_EQ(res->body, original);
  374. }
  375. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  376. string chineseCharacters = U8("中国語");
  377. string russianCharacters = U8("дом");
  378. string brazilianCharacters = U8("óculos");
  379. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  380. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  381. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  382. "%D0%B4%D0%BE%D0%BC");
  383. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  384. }
  385. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  386. string unescapedCharacters = "-_.!~*'()";
  387. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  388. }
  389. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  390. string reservedCharacters = ";,/?:@&=+$";
  391. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  392. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  393. }
  394. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  395. string chineseCharacters = U8("中国語");
  396. string russianCharacters = U8("дом");
  397. string brazilianCharacters = U8("óculos");
  398. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  399. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  400. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  401. "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  405. // Issue #2082 use case: encoding path component with ampersand
  406. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  407. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  408. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  409. }
  410. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  411. string unescapedCharacters = "-_.!~*'()";
  412. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  413. }
  414. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  415. string reservedCharacters = ";,/?:@&=+$#";
  416. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  417. }
  418. TEST(EncodeUriTest, TestUTF8Characters) {
  419. string chineseCharacters = U8("中国語");
  420. string russianCharacters = U8("дом");
  421. string brazilianCharacters = U8("óculos");
  422. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  423. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  424. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  425. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  426. }
  427. TEST(EncodeUriTest, TestCompleteUri) {
  428. string uri =
  429. "https://example.com/path/to/resource?query=value&param=test#fragment";
  430. EXPECT_EQ(
  431. httplib::encode_uri(uri),
  432. "https://example.com/path/to/resource?query=value&param=test#fragment");
  433. }
  434. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  435. string uri =
  436. "https://example.com/path with spaces/file name.html?q=hello world";
  437. EXPECT_EQ(httplib::encode_uri(uri),
  438. "https://example.com/path%20with%20spaces/"
  439. "file%20name.html?q=hello%20world");
  440. }
  441. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  442. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  443. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  444. }
  445. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  446. string unescapedCharacters = "-_.!~*'()";
  447. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  448. }
  449. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  450. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  451. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  452. string encodedBrazilian = "%C3%B3culos";
  453. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  454. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  455. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  456. }
  457. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  458. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  459. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  460. "Piri Tommy Villiers - on & on");
  461. }
  462. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  463. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  464. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  465. }
  466. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  467. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  468. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  469. }
  470. TEST(DecodeUriTest, TestUTF8Characters) {
  471. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  472. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  473. string encodedBrazilian = "%C3%B3culos";
  474. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  475. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  476. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  477. }
  478. TEST(DecodeUriTest, TestCompleteUri) {
  479. string encodedUri = "https://example.com/path%20with%20spaces/"
  480. "file%20name.html?q=hello%20world";
  481. EXPECT_EQ(
  482. httplib::decode_uri(encodedUri),
  483. "https://example.com/path with spaces/file name.html?q=hello world");
  484. }
  485. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  486. string original =
  487. "https://example.com/path with spaces/file name.html?q=hello world";
  488. string encoded = httplib::encode_uri(original);
  489. string decoded = httplib::decode_uri(encoded);
  490. EXPECT_EQ(decoded, original);
  491. }
  492. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  493. string original = "Piri Tommy Villiers - on & on";
  494. string encoded = httplib::encode_uri_component(original);
  495. string decoded = httplib::decode_uri_component(encoded);
  496. EXPECT_EQ(decoded, original);
  497. }
  498. TEST(TrimTests, TrimStringTests) {
  499. EXPECT_EQ("abc", detail::trim_copy("abc"));
  500. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  501. EXPECT_TRUE(detail::trim_copy("").empty());
  502. }
  503. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  504. // Simple case without quality values
  505. std::vector<std::string> result1;
  506. EXPECT_TRUE(detail::parse_accept_header(
  507. "text/html,application/json,text/plain", result1));
  508. EXPECT_EQ(result1.size(), 3U);
  509. EXPECT_EQ(result1[0], "text/html");
  510. EXPECT_EQ(result1[1], "application/json");
  511. EXPECT_EQ(result1[2], "text/plain");
  512. // With quality values
  513. std::vector<std::string> result2;
  514. EXPECT_TRUE(detail::parse_accept_header(
  515. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  516. EXPECT_EQ(result2.size(), 3U);
  517. EXPECT_EQ(result2[0], "application/json"); // highest q value
  518. EXPECT_EQ(result2[1], "text/html");
  519. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  520. }
  521. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  522. // Mixed with and without quality values
  523. std::vector<std::string> result;
  524. EXPECT_TRUE(detail::parse_accept_header(
  525. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  526. EXPECT_EQ(result.size(), 3U);
  527. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  528. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  529. EXPECT_EQ(result[2], "application/json"); // q=0.5
  530. }
  531. TEST(ParseAcceptHeaderTest, EdgeCases) {
  532. // Empty header
  533. std::vector<std::string> empty_result;
  534. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  535. EXPECT_TRUE(empty_result.empty());
  536. // Single type
  537. std::vector<std::string> single_result;
  538. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  539. EXPECT_EQ(single_result.size(), 1U);
  540. EXPECT_EQ(single_result[0], "application/json");
  541. // Wildcard types
  542. std::vector<std::string> wildcard_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  545. EXPECT_EQ(wildcard_result.size(), 3U);
  546. EXPECT_EQ(wildcard_result[0], "application/json");
  547. EXPECT_EQ(wildcard_result[1], "text/*");
  548. EXPECT_EQ(wildcard_result[2], "*/*");
  549. }
  550. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  551. // Common browser Accept header
  552. std::vector<std::string> browser_result;
  553. EXPECT_TRUE(
  554. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  555. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  556. browser_result));
  557. EXPECT_EQ(browser_result.size(), 6U);
  558. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  560. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  561. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  563. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  564. // API client header
  565. std::vector<std::string> api_result;
  566. EXPECT_TRUE(detail::parse_accept_header(
  567. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  568. api_result));
  569. EXPECT_EQ(api_result.size(), 3U);
  570. EXPECT_EQ(api_result[0], "application/json");
  571. EXPECT_EQ(api_result[1], "application/xml");
  572. EXPECT_EQ(api_result[2], "text/plain");
  573. }
  574. TEST(ParseAcceptHeaderTest, SpecialCases) {
  575. // Quality value with 3 decimal places
  576. std::vector<std::string> decimal_result;
  577. EXPECT_TRUE(detail::parse_accept_header(
  578. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  579. EXPECT_EQ(decimal_result.size(), 2U);
  580. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  581. EXPECT_EQ(decimal_result[1], "text/html");
  582. // Zero quality (should still be included but with lowest priority)
  583. std::vector<std::string> zero_q_result;
  584. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  585. zero_q_result));
  586. EXPECT_EQ(zero_q_result.size(), 2U);
  587. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  588. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  589. // No spaces around commas
  590. std::vector<std::string> no_space_result;
  591. EXPECT_TRUE(detail::parse_accept_header(
  592. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  593. no_space_result));
  594. EXPECT_EQ(no_space_result.size(), 3U);
  595. EXPECT_EQ(no_space_result[0], "text/html");
  596. EXPECT_EQ(no_space_result[1], "application/json");
  597. EXPECT_EQ(no_space_result[2], "text/plain");
  598. }
  599. TEST(ParseAcceptHeaderTest, InvalidCases) {
  600. std::vector<std::string> result;
  601. // Invalid quality value (> 1.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  604. // Invalid quality value (< 0.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  607. // Invalid quality value (not a number)
  608. EXPECT_FALSE(detail::parse_accept_header(
  609. "text/html;q=invalid,application/json", result));
  610. // Empty quality value
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("text/html;q=,application/json", result));
  613. // Invalid media type format (no slash and not wildcard)
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("invalidtype,application/json", result));
  616. // Empty media type
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  619. // Only commas
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  622. // Valid cases should still work
  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("*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "*");
  629. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "text/*");
  632. }
  633. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  634. Server svr;
  635. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  636. EXPECT_EQ(req.accept_content_types.size(), 3U);
  637. EXPECT_EQ(req.accept_content_types[0], "application/json");
  638. EXPECT_EQ(req.accept_content_types[1], "text/html");
  639. EXPECT_EQ(req.accept_content_types[2], "*/*");
  640. res.set_content("ok", "text/plain");
  641. });
  642. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  643. EXPECT_TRUE(false);
  644. res.set_content("bad request", "text/plain");
  645. });
  646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  647. auto se = detail::scope_exit([&] {
  648. svr.stop();
  649. listen_thread.join();
  650. ASSERT_FALSE(svr.is_running());
  651. });
  652. svr.wait_until_ready();
  653. Client cli("localhost", PORT);
  654. {
  655. auto res =
  656. cli.Get("/accept_ok",
  657. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ(StatusCode::OK_200, res->status);
  660. }
  661. {
  662. auto res = cli.Get("/accept_bad_request",
  663. {{"Accept", "text/html;q=abc,application/json"}});
  664. ASSERT_TRUE(res);
  665. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  666. }
  667. }
  668. TEST(DivideTest, DivideStringTests) {
  669. auto divide = [](const std::string &str, char d) {
  670. std::string lhs;
  671. std::string rhs;
  672. detail::divide(str, d,
  673. [&](const char *lhs_data, std::size_t lhs_size,
  674. const char *rhs_data, std::size_t rhs_size) {
  675. lhs.assign(lhs_data, lhs_size);
  676. rhs.assign(rhs_data, rhs_size);
  677. });
  678. return std::make_pair(std::move(lhs), std::move(rhs));
  679. };
  680. {
  681. const auto res = divide("", '=');
  682. EXPECT_EQ(res.first, "");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("=", '=');
  687. EXPECT_EQ(res.first, "");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide(" ", '=');
  692. EXPECT_EQ(res.first, " ");
  693. EXPECT_EQ(res.second, "");
  694. }
  695. {
  696. const auto res = divide("a", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "");
  699. }
  700. {
  701. const auto res = divide("a=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "");
  704. }
  705. {
  706. const auto res = divide("=b", '=');
  707. EXPECT_EQ(res.first, "");
  708. EXPECT_EQ(res.second, "b");
  709. }
  710. {
  711. const auto res = divide("a=b", '=');
  712. EXPECT_EQ(res.first, "a");
  713. EXPECT_EQ(res.second, "b");
  714. }
  715. {
  716. const auto res = divide("a=b=", '=');
  717. EXPECT_EQ(res.first, "a");
  718. EXPECT_EQ(res.second, "b=");
  719. }
  720. {
  721. const auto res = divide("a=b=c", '=');
  722. EXPECT_EQ(res.first, "a");
  723. EXPECT_EQ(res.second, "b=c");
  724. }
  725. }
  726. TEST(SplitTest, ParseQueryString) {
  727. string s = "key1=val1&key2=val2&key3=val3";
  728. Params dic;
  729. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  730. [&](const char *b, const char *e) {
  731. string key, val;
  732. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  733. if (key.empty()) {
  734. key.assign(b2, e2);
  735. } else {
  736. val.assign(b2, e2);
  737. }
  738. });
  739. dic.emplace(key, val);
  740. });
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. TEST(SplitTest, ParseInvalidQueryTests) {
  746. {
  747. string s = " ";
  748. Params dict;
  749. detail::parse_query_text(s, dict);
  750. EXPECT_TRUE(dict.empty());
  751. }
  752. {
  753. string s = " = =";
  754. Params dict;
  755. detail::parse_query_text(s, dict);
  756. EXPECT_TRUE(dict.empty());
  757. }
  758. }
  759. TEST(ParseQueryTest, ParseQueryString) {
  760. {
  761. std::string s = "key1=val1&key2=val2&key3=val3";
  762. Params dic;
  763. detail::parse_query_text(s, dic);
  764. EXPECT_EQ("val1", dic.find("key1")->second);
  765. EXPECT_EQ("val2", dic.find("key2")->second);
  766. EXPECT_EQ("val3", dic.find("key3")->second);
  767. }
  768. {
  769. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  770. Params dic;
  771. detail::parse_query_text(s, dic);
  772. EXPECT_EQ("", dic.find("key1")->second);
  773. EXPECT_EQ("val1", dic.find("key2")->second);
  774. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  775. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  776. }
  777. }
  778. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  779. Params dic;
  780. EXPECT_EQ(detail::params_to_query_str(dic), "");
  781. dic.emplace("key1", "val1");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  783. dic.emplace("key2", "val2");
  784. dic.emplace("key3", "val3");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  786. }
  787. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  788. string content_type = "multipart/form-data; boundary=something";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "something");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  795. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  796. string boundary;
  797. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  798. EXPECT_TRUE(ret);
  799. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  800. }
  801. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  802. string content_type =
  803. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  804. string boundary;
  805. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  806. EXPECT_TRUE(ret);
  807. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  808. }
  809. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  810. string content_type =
  811. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  812. string boundary;
  813. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  814. EXPECT_TRUE(ret);
  815. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  816. }
  817. TEST(GetHeaderValueTest, DefaultValue) {
  818. Headers headers = {{"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  820. EXPECT_STREQ("text/plain", val);
  821. }
  822. TEST(GetHeaderValueTest, DefaultValueInt) {
  823. Headers headers = {{"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularValue) {
  828. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  829. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  830. EXPECT_STREQ("text/html", val);
  831. }
  832. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  833. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  834. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  835. EXPECT_STREQ("text/html", val);
  836. }
  837. TEST(GetHeaderValueTest, SetContent) {
  838. Response res;
  839. res.set_content("html", "text/html");
  840. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  841. res.set_content("text", "text/plain");
  842. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  843. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  844. }
  845. TEST(GetHeaderValueTest, RegularValueInt) {
  846. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  847. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  848. EXPECT_EQ(100ull, val);
  849. }
  850. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  851. Headers headers = {{"Content-Length", "x"}};
  852. auto is_invalid_value = false;
  853. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  854. is_invalid_value);
  855. EXPECT_EQ(0ull, val);
  856. EXPECT_TRUE(is_invalid_value);
  857. }
  858. TEST(GetHeaderValueTest, Range) {
  859. {
  860. Headers headers = {make_range_header({{1, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{-1, 1}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=-1", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{1, 10}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=1-10", val);
  873. }
  874. {
  875. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  876. auto val = detail::get_header_value(headers, "Range", 0, 0);
  877. EXPECT_STREQ("bytes=1-10, 100-", val);
  878. }
  879. {
  880. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  881. auto val = detail::get_header_value(headers, "Range", 0, 0);
  882. EXPECT_STREQ("bytes=1-10, 100-200", val);
  883. }
  884. {
  885. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  886. auto val = detail::get_header_value(headers, "Range", 0, 0);
  887. EXPECT_STREQ("bytes=0-0, -1", val);
  888. }
  889. }
  890. TEST(ParseHeaderValueTest, Range) {
  891. {
  892. Ranges ranges;
  893. auto ret = detail::parse_range_header("bytes=1-", ranges);
  894. EXPECT_TRUE(ret);
  895. EXPECT_EQ(1u, ranges.size());
  896. EXPECT_EQ(1u, ranges[0].first);
  897. EXPECT_EQ(-1, ranges[0].second);
  898. }
  899. {
  900. Ranges ranges;
  901. auto ret = detail::parse_range_header("bytes=-1", ranges);
  902. EXPECT_TRUE(ret);
  903. EXPECT_EQ(1u, ranges.size());
  904. EXPECT_EQ(-1, ranges[0].first);
  905. EXPECT_EQ(1u, ranges[0].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  910. EXPECT_TRUE(ret);
  911. EXPECT_EQ(1u, ranges.size());
  912. EXPECT_EQ(1u, ranges[0].first);
  913. EXPECT_EQ(10u, ranges[0].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  918. EXPECT_FALSE(ret);
  919. }
  920. {
  921. Ranges ranges;
  922. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  923. EXPECT_TRUE(ret);
  924. EXPECT_EQ(2u, ranges.size());
  925. EXPECT_EQ(1u, ranges[0].first);
  926. EXPECT_EQ(10u, ranges[0].second);
  927. EXPECT_EQ(100u, ranges[1].first);
  928. EXPECT_EQ(-1, ranges[1].second);
  929. }
  930. {
  931. Ranges ranges;
  932. auto ret =
  933. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  934. EXPECT_TRUE(ret);
  935. EXPECT_EQ(3u, ranges.size());
  936. EXPECT_EQ(1u, ranges[0].first);
  937. EXPECT_EQ(10u, ranges[0].second);
  938. EXPECT_EQ(100u, ranges[1].first);
  939. EXPECT_EQ(200u, ranges[1].second);
  940. EXPECT_EQ(300u, ranges[2].first);
  941. EXPECT_EQ(400u, ranges[2].second);
  942. }
  943. {
  944. Ranges 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=0", 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=,", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  958. EXPECT_TRUE(ranges.empty());
  959. }
  960. }
  961. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  962. Request req;
  963. req.set_header("Accept-Encoding", "gzip");
  964. Response res;
  965. res.set_header("Content-Type", "text/plain");
  966. auto ret = detail::encoding_type(req, res);
  967. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  968. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  969. #else
  970. EXPECT_TRUE(ret == detail::EncodingType::None);
  971. #endif
  972. }
  973. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  974. Request req;
  975. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  976. Response res;
  977. res.set_header("Content-Type", "text/plain");
  978. auto ret = detail::encoding_type(req, res);
  979. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  980. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  981. #elif CPPHTTPLIB_ZLIB_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  983. #elif CPPHTTPLIB_ZSTD_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  985. #else
  986. EXPECT_TRUE(ret == detail::EncodingType::None);
  987. #endif
  988. }
  989. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  990. Request req;
  991. req.set_header("Accept-Encoding",
  992. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  993. Response res;
  994. res.set_header("Content-Type", "text/plain");
  995. auto ret = detail::encoding_type(req, res);
  996. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  997. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  998. #elif CPPHTTPLIB_ZLIB_SUPPORT
  999. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1000. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1001. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1002. #else
  1003. EXPECT_TRUE(ret == detail::EncodingType::None);
  1004. #endif
  1005. }
  1006. TEST(BufferStreamTest, read) {
  1007. detail::BufferStream strm1;
  1008. Stream &strm = strm1;
  1009. EXPECT_EQ(5, strm.write("hello"));
  1010. char buf[512];
  1011. EXPECT_EQ(2, strm.read(buf, 2));
  1012. EXPECT_EQ('h', buf[0]);
  1013. EXPECT_EQ('e', buf[1]);
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('l', buf[0]);
  1016. EXPECT_EQ('l', buf[1]);
  1017. EXPECT_EQ(1, strm.read(buf, 1));
  1018. EXPECT_EQ('o', buf[0]);
  1019. EXPECT_EQ(0, strm.read(buf, 1));
  1020. }
  1021. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1022. auto host = "www.httpwatch.com";
  1023. auto ip = hosted_at(host);
  1024. EXPECT_EQ("23.96.13.243", ip);
  1025. std::vector<std::string> addrs;
  1026. hosted_at(host, addrs);
  1027. EXPECT_EQ(1u, addrs.size());
  1028. }
  1029. #if 0 // It depends on each test environment...
  1030. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1031. auto host = "www.youtube.com";
  1032. std::vector<std::string> addrs;
  1033. hosted_at(host, addrs);
  1034. EXPECT_EQ(20u, addrs.size());
  1035. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1036. EXPECT_TRUE(it != addrs.end());
  1037. }
  1038. #endif
  1039. class ChunkedEncodingTest : public ::testing::Test {
  1040. protected:
  1041. ChunkedEncodingTest()
  1042. : cli_(HOST, PORT)
  1043. #ifdef CPPHTTPLIB_SSL_ENABLED
  1044. ,
  1045. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1046. #endif
  1047. {
  1048. cli_.set_connection_timeout(2);
  1049. #ifdef CPPHTTPLIB_SSL_ENABLED
  1050. cli_.enable_server_certificate_verification(false);
  1051. #endif
  1052. }
  1053. virtual void SetUp() {
  1054. read_file("./image.jpg", image_data_);
  1055. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1056. res.set_content("Hello World!", "text/plain");
  1057. });
  1058. svr_.Get(
  1059. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1060. res.set_chunked_content_provider(
  1061. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1062. size_t remaining = image_data_.size() - offset;
  1063. if (remaining == 0) {
  1064. sink.done();
  1065. } else {
  1066. constexpr size_t CHUNK_SIZE = 1024;
  1067. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1068. sink.write(&image_data_[offset], send_size);
  1069. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1070. }
  1071. return true;
  1072. });
  1073. });
  1074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1075. svr_.wait_until_ready();
  1076. }
  1077. virtual void TearDown() {
  1078. svr_.stop();
  1079. if (!request_threads_.empty()) {
  1080. std::this_thread::sleep_for(std::chrono::seconds(1));
  1081. for (auto &t : request_threads_) {
  1082. t.join();
  1083. }
  1084. }
  1085. t_.join();
  1086. }
  1087. #ifdef CPPHTTPLIB_SSL_ENABLED
  1088. SSLClient cli_;
  1089. SSLServer svr_;
  1090. #else
  1091. Client cli_;
  1092. Server svr_;
  1093. #endif
  1094. thread t_;
  1095. std::vector<thread> request_threads_;
  1096. std::string image_data_;
  1097. };
  1098. TEST_F(ChunkedEncodingTest, NormalGet) {
  1099. auto res = cli_.Get("/chunked");
  1100. ASSERT_TRUE(res);
  1101. std::string out;
  1102. read_file("./image.jpg", out);
  1103. EXPECT_EQ(StatusCode::OK_200, res->status);
  1104. EXPECT_EQ(out, res->body);
  1105. }
  1106. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1107. std::string body;
  1108. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1109. body.append(data, data_length);
  1110. return true;
  1111. });
  1112. ASSERT_TRUE(res);
  1113. std::string out;
  1114. read_file("./image.jpg", out);
  1115. EXPECT_EQ(StatusCode::OK_200, res->status);
  1116. EXPECT_EQ(out, body);
  1117. }
  1118. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1119. std::string body;
  1120. auto res = cli_.Get(
  1121. "/chunked",
  1122. [&](const Response &response) {
  1123. EXPECT_EQ(StatusCode::OK_200, response.status);
  1124. return true;
  1125. },
  1126. [&](const char *data, size_t data_length) {
  1127. body.append(data, data_length);
  1128. return true;
  1129. });
  1130. ASSERT_TRUE(res);
  1131. std::string out;
  1132. read_file("./image.jpg", out);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. EXPECT_EQ(out, body);
  1135. }
  1136. TEST(RangeTest, FromHTTPBin_Online) {
  1137. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1138. auto host = "httpcan.org";
  1139. auto path = std::string{"/range/32"};
  1140. #else
  1141. auto host = "nghttp2.org";
  1142. auto path = std::string{"/httpbin/range/32"};
  1143. #endif
  1144. #ifdef CPPHTTPLIB_SSL_ENABLED
  1145. auto port = 443;
  1146. SSLClient cli(host, port);
  1147. #else
  1148. auto port = 80;
  1149. Client cli(host, port);
  1150. #endif
  1151. cli.set_connection_timeout(5);
  1152. {
  1153. auto res = cli.Get(path);
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1156. EXPECT_EQ(StatusCode::OK_200, res->status);
  1157. }
  1158. {
  1159. Headers headers = {make_range_header({{1, -1}})};
  1160. auto res = cli.Get(path, headers);
  1161. ASSERT_TRUE(res);
  1162. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1164. }
  1165. {
  1166. Headers headers = {make_range_header({{1, 10}})};
  1167. auto res = cli.Get(path, headers);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ("bcdefghijk", res->body);
  1170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1171. }
  1172. {
  1173. Headers headers = {make_range_header({{0, 31}})};
  1174. auto res = cli.Get(path, headers);
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1177. EXPECT_EQ(StatusCode::OK_200, res->status);
  1178. }
  1179. {
  1180. Headers headers = {make_range_header({{0, -1}})};
  1181. auto res = cli.Get(path, headers);
  1182. ASSERT_TRUE(res);
  1183. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1184. EXPECT_EQ(StatusCode::OK_200, res->status);
  1185. }
  1186. {
  1187. Headers headers = {make_range_header({{0, 32}})};
  1188. auto res = cli.Get(path, headers);
  1189. ASSERT_TRUE(res);
  1190. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1191. }
  1192. }
  1193. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1194. auto host = "unresolvableaddress.local";
  1195. auto path = std::string{"/"};
  1196. #ifdef CPPHTTPLIB_SSL_ENABLED
  1197. auto port = 443;
  1198. SSLClient cli(host, port);
  1199. #else
  1200. auto port = 80;
  1201. Client cli(host, port);
  1202. #endif
  1203. cli.set_connection_timeout(1);
  1204. {
  1205. auto res = cli.Get(path);
  1206. ASSERT_FALSE(res);
  1207. }
  1208. std::this_thread::sleep_for(std::chrono::seconds(8));
  1209. }
  1210. TEST(ConnectionErrorTest, InvalidHost) {
  1211. auto host = "-abcde.com";
  1212. #ifdef CPPHTTPLIB_SSL_ENABLED
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(2));
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(ConnectionErrorTest, InvalidHost2) {
  1225. auto host = "httpcan.org/";
  1226. #ifdef CPPHTTPLIB_SSL_ENABLED
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_connection_timeout(std::chrono::seconds(2));
  1232. auto res = cli.Get("/");
  1233. ASSERT_TRUE(!res);
  1234. EXPECT_EQ(Error::Connection, res.error());
  1235. }
  1236. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1237. auto host = "httpcan.org/";
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. stringstream s;
  1247. s << "error code: " << res.error();
  1248. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1249. }
  1250. TEST(ConnectionErrorTest, InvalidPort) {
  1251. auto host = "localhost";
  1252. auto port = 44380;
  1253. #ifdef CPPHTTPLIB_SSL_ENABLED
  1254. SSLClient cli(host, port);
  1255. #else
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. auto res = cli.Get("/");
  1260. ASSERT_TRUE(!res);
  1261. EXPECT_TRUE(Error::Connection == res.error() ||
  1262. Error::ConnectionTimeout == res.error());
  1263. }
  1264. TEST(ConnectionErrorTest, Timeout_Online) {
  1265. auto host = "google.com";
  1266. #ifdef CPPHTTPLIB_SSL_ENABLED
  1267. auto port = 44380;
  1268. SSLClient cli(host, port);
  1269. #else
  1270. auto port = 8080;
  1271. Client cli(host, port);
  1272. #endif
  1273. cli.set_connection_timeout(std::chrono::seconds(2));
  1274. // only probe one address type so that the error reason
  1275. // correlates to the timed-out IPv4, not the unsupported
  1276. // IPv6 connection attempt
  1277. cli.set_address_family(AF_INET);
  1278. auto res = cli.Get("/");
  1279. ASSERT_TRUE(!res);
  1280. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1281. }
  1282. TEST(CancelTest, NoCancel_Online) {
  1283. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1284. auto host = "httpcan.org";
  1285. auto path = std::string{"/range/32"};
  1286. #else
  1287. auto host = "nghttp2.org";
  1288. auto path = std::string{"/httpbin/range/32"};
  1289. #endif
  1290. #ifdef CPPHTTPLIB_SSL_ENABLED
  1291. auto port = 443;
  1292. SSLClient cli(host, port);
  1293. #else
  1294. auto port = 80;
  1295. Client cli(host, port);
  1296. #endif
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1301. EXPECT_EQ(StatusCode::OK_200, res->status);
  1302. }
  1303. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpcan.org";
  1306. auto path = std::string{"/range/32"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/range/32"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_SSL_ENABLED
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1319. cli.set_connection_timeout(std::chrono::seconds(5));
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, WithCancelLargePayload_Online) {
  1324. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1325. auto host = "httpcan.org";
  1326. auto path = std::string{"/range/65536"};
  1327. #else
  1328. auto host = "nghttp2.org";
  1329. auto path = std::string{"/httpbin/range/65536"};
  1330. #endif
  1331. #ifdef CPPHTTPLIB_SSL_ENABLED
  1332. auto port = 443;
  1333. SSLClient cli(host, port);
  1334. #else
  1335. auto port = 80;
  1336. Client cli(host, port);
  1337. #endif
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. uint32_t count = 0;
  1340. auto res =
  1341. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, NoCancelPost) {
  1346. Server svr;
  1347. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content("Hello World!", "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return true; });
  1362. ASSERT_TRUE(res);
  1363. EXPECT_EQ("Hello World!", res->body);
  1364. EXPECT_EQ(StatusCode::OK_200, res->status);
  1365. }
  1366. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1367. Server svr;
  1368. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1369. res.set_content("Hello World!", "text/plain");
  1370. });
  1371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1372. auto se = detail::scope_exit([&] {
  1373. svr.stop();
  1374. thread.join();
  1375. ASSERT_FALSE(svr.is_running());
  1376. });
  1377. svr.wait_until_ready();
  1378. Client cli(HOST, PORT);
  1379. cli.set_connection_timeout(std::chrono::seconds(5));
  1380. auto res =
  1381. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1382. "application/json", [](uint64_t, uint64_t) { return false; });
  1383. ASSERT_TRUE(!res);
  1384. EXPECT_EQ(Error::Canceled, res.error());
  1385. }
  1386. TEST(CancelTest, WithCancelLargePayloadPost) {
  1387. Server svr;
  1388. svr.set_payload_max_length(200 * 1024 * 1024);
  1389. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content(LARGE_DATA, "text/plain");
  1391. });
  1392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1393. auto se = detail::scope_exit([&] {
  1394. svr.stop();
  1395. thread.join();
  1396. ASSERT_FALSE(svr.is_running());
  1397. });
  1398. svr.wait_until_ready();
  1399. Client cli(HOST, PORT);
  1400. cli.set_payload_max_length(200 * 1024 * 1024);
  1401. cli.set_connection_timeout(std::chrono::seconds(5));
  1402. auto res =
  1403. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1404. "application/json", [](uint64_t, uint64_t) { return false; });
  1405. ASSERT_TRUE(!res);
  1406. EXPECT_EQ(Error::Canceled, res.error());
  1407. }
  1408. TEST(CancelTest, NoCancelPut) {
  1409. Server svr;
  1410. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1411. res.set_content("Hello World!", "text/plain");
  1412. });
  1413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. thread.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. Client cli(HOST, PORT);
  1421. cli.set_connection_timeout(std::chrono::seconds(5));
  1422. auto res =
  1423. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1424. "application/json", [](uint64_t, uint64_t) { return true; });
  1425. ASSERT_TRUE(res);
  1426. EXPECT_EQ("Hello World!", res->body);
  1427. EXPECT_EQ(StatusCode::OK_200, res->status);
  1428. }
  1429. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1430. Server svr;
  1431. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("Hello World!", "text/plain");
  1433. });
  1434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. thread.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. Client cli(HOST, PORT);
  1442. cli.set_connection_timeout(std::chrono::seconds(5));
  1443. auto res =
  1444. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1445. "application/json", [](uint64_t, uint64_t) { return false; });
  1446. ASSERT_TRUE(!res);
  1447. EXPECT_EQ(Error::Canceled, res.error());
  1448. }
  1449. TEST(CancelTest, WithCancelLargePayloadPut) {
  1450. Server svr;
  1451. svr.set_payload_max_length(200 * 1024 * 1024);
  1452. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_payload_max_length(200 * 1024 * 1024);
  1464. cli.set_connection_timeout(std::chrono::seconds(5));
  1465. auto res =
  1466. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1467. "application/json", [](uint64_t, uint64_t) { return false; });
  1468. ASSERT_TRUE(!res);
  1469. EXPECT_EQ(Error::Canceled, res.error());
  1470. }
  1471. TEST(CancelTest, NoCancelPatch) {
  1472. Server svr;
  1473. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1474. res.set_content("Hello World!", "text/plain");
  1475. });
  1476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. thread.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. Client cli(HOST, PORT);
  1484. cli.set_connection_timeout(std::chrono::seconds(5));
  1485. auto res =
  1486. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1487. "application/json", [](uint64_t, uint64_t) { return true; });
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("Hello World!", res->body);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. }
  1492. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1493. Server svr;
  1494. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1495. res.set_content("Hello World!", "text/plain");
  1496. });
  1497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1498. auto se = detail::scope_exit([&] {
  1499. svr.stop();
  1500. thread.join();
  1501. ASSERT_FALSE(svr.is_running());
  1502. });
  1503. svr.wait_until_ready();
  1504. Client cli(HOST, PORT);
  1505. cli.set_connection_timeout(std::chrono::seconds(5));
  1506. auto res =
  1507. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1508. "application/json", [](uint64_t, uint64_t) { return false; });
  1509. ASSERT_TRUE(!res);
  1510. EXPECT_EQ(Error::Canceled, res.error());
  1511. }
  1512. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1513. Server svr;
  1514. svr.set_payload_max_length(200 * 1024 * 1024);
  1515. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content(LARGE_DATA, "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_payload_max_length(200 * 1024 * 1024);
  1527. cli.set_connection_timeout(std::chrono::seconds(5));
  1528. auto res =
  1529. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1530. "application/json", [](uint64_t, uint64_t) { return false; });
  1531. ASSERT_TRUE(!res);
  1532. EXPECT_EQ(Error::Canceled, res.error());
  1533. }
  1534. TEST(CancelTest, NoCancelDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return true; });
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ("Hello World!", res->body);
  1553. EXPECT_EQ(StatusCode::OK_200, res->status);
  1554. }
  1555. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1556. Server svr;
  1557. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content("Hello World!", "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_connection_timeout(std::chrono::seconds(5));
  1569. auto res =
  1570. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1571. "application/json", [](uint64_t, uint64_t) { return false; });
  1572. ASSERT_TRUE(!res);
  1573. EXPECT_EQ(Error::Canceled, res.error());
  1574. }
  1575. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1576. Server svr;
  1577. svr.set_payload_max_length(200 * 1024 * 1024);
  1578. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content(LARGE_DATA, "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_payload_max_length(200 * 1024 * 1024);
  1590. cli.set_connection_timeout(std::chrono::seconds(5));
  1591. auto res =
  1592. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1593. "application/json", [](uint64_t, uint64_t) { return false; });
  1594. ASSERT_TRUE(!res);
  1595. EXPECT_EQ(Error::Canceled, res.error());
  1596. }
  1597. static std::string remove_whitespace(const std::string &input) {
  1598. std::string output;
  1599. output.reserve(input.size());
  1600. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1601. [](unsigned char c) { return !std::isspace(c); });
  1602. return output;
  1603. }
  1604. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1605. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1606. auto host = "httpcan.org";
  1607. auto path = std::string{"/basic-auth/hello/world"};
  1608. #else
  1609. auto host = "nghttp2.org";
  1610. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1611. #endif
  1612. #ifdef CPPHTTPLIB_SSL_ENABLED
  1613. auto port = 443;
  1614. SSLClient cli(host, port);
  1615. #else
  1616. auto port = 80;
  1617. Client cli(host, port);
  1618. #endif
  1619. {
  1620. auto res = cli.Get(path);
  1621. ASSERT_TRUE(res);
  1622. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1623. }
  1624. {
  1625. auto res =
  1626. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. {
  1633. cli.set_basic_auth("hello", "world");
  1634. auto res = cli.Get(path);
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1637. remove_whitespace(res->body));
  1638. EXPECT_EQ(StatusCode::OK_200, res->status);
  1639. }
  1640. {
  1641. cli.set_basic_auth("hello", "bad");
  1642. auto res = cli.Get(path);
  1643. ASSERT_TRUE(res);
  1644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1645. }
  1646. {
  1647. cli.set_basic_auth("bad", "world");
  1648. auto res = cli.Get(path);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1651. }
  1652. }
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. auto host = "httpcan.org";
  1657. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1658. auto paths = std::vector<std::string>{
  1659. "/digest-auth/auth/hello/world/MD5",
  1660. "/digest-auth/auth/hello/world/SHA-256",
  1661. "/digest-auth/auth/hello/world/SHA-512",
  1662. };
  1663. #else
  1664. auto host = "nghttp2.org";
  1665. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1666. auto paths = std::vector<std::string>{
  1667. "/httpbin/digest-auth/auth/hello/world/MD5",
  1668. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1669. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1670. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1671. };
  1672. #endif
  1673. auto port = 443;
  1674. SSLClient cli(host, port);
  1675. {
  1676. auto res = cli.Get(unauth_path);
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1679. }
  1680. {
  1681. cli.set_digest_auth("hello", "world");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1686. std::string algo(path.substr(path.rfind('/') + 1));
  1687. EXPECT_EQ(
  1688. remove_whitespace("{\"algorithm\":\"" + algo +
  1689. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1690. remove_whitespace(res->body));
  1691. #else
  1692. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1693. remove_whitespace(res->body));
  1694. #endif
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1698. cli.set_digest_auth("hello", "bad");
  1699. for (const auto &path : paths) {
  1700. auto res = cli.Get(path.c_str());
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1703. }
  1704. #endif
  1705. }
  1706. }
  1707. #endif
  1708. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1709. auto host = "google.com";
  1710. auto another_host = "example.com";
  1711. auto wrong_ip = "0.0.0.0";
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. SSLClient cli(host);
  1714. #else
  1715. Client cli(host);
  1716. #endif
  1717. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1718. auto res = cli.Get("/");
  1719. ASSERT_TRUE(res);
  1720. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1721. }
  1722. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1723. auto host = "google.com";
  1724. auto wrong_ip = "0.0.0.0";
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. SSLClient cli(host);
  1727. #else
  1728. Client cli(host);
  1729. #endif
  1730. cli.set_hostname_addr_map({{host, wrong_ip}});
  1731. auto res = cli.Get("/");
  1732. ASSERT_TRUE(!res);
  1733. EXPECT_EQ(Error::Connection, res.error());
  1734. }
  1735. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1736. auto host = "nghttp2.org";
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. SSLClient cli(host);
  1739. #else
  1740. Client cli(host);
  1741. #endif
  1742. cli.set_follow_location(true);
  1743. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(RedirectTest, Redirect_Online) {
  1748. auto host = "nghttp2.org";
  1749. #ifdef CPPHTTPLIB_SSL_ENABLED
  1750. SSLClient cli(host);
  1751. #else
  1752. Client cli(host);
  1753. #endif
  1754. cli.set_follow_location(true);
  1755. auto res = cli.Get("/httpbin/redirect/3");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::OK_200, res->status);
  1758. }
  1759. TEST(RelativeRedirectTest, Redirect_Online) {
  1760. auto host = "nghttp2.org";
  1761. #ifdef CPPHTTPLIB_SSL_ENABLED
  1762. SSLClient cli(host);
  1763. #else
  1764. Client cli(host);
  1765. #endif
  1766. cli.set_follow_location(true);
  1767. auto res = cli.Get("/httpbin/relative-redirect/3");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. }
  1771. TEST(TooManyRedirectTest, Redirect_Online) {
  1772. auto host = "nghttp2.org";
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. SSLClient cli(host);
  1775. #else
  1776. Client cli(host);
  1777. #endif
  1778. cli.set_follow_location(true);
  1779. auto res = cli.Get("/httpbin/redirect/21");
  1780. ASSERT_TRUE(!res);
  1781. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1782. }
  1783. #ifdef CPPHTTPLIB_SSL_ENABLED
  1784. TEST(YahooRedirectTest, Redirect_Online) {
  1785. Client cli("yahoo.com");
  1786. auto res = cli.Get("/");
  1787. ASSERT_TRUE(res);
  1788. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1789. cli.set_follow_location(true);
  1790. res = cli.Get("/");
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1794. }
  1795. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1796. #define REDIR_HOST "httpbingo.org"
  1797. #define REDIR_PATH "/redirect-to"
  1798. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1799. SSLClient cli(REDIR_HOST);
  1800. cli.set_follow_location(true);
  1801. auto res =
  1802. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(StatusCode::OK_200, res->status);
  1805. }
  1806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1807. SSLClient cli(REDIR_HOST);
  1808. cli.set_follow_location(true);
  1809. Params params;
  1810. params.emplace("url", "http://example.com");
  1811. params.emplace("status_code", "302");
  1812. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::OK_200, res->status);
  1815. }
  1816. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1817. SSLClient cli(REDIR_HOST);
  1818. cli.set_follow_location(true);
  1819. Params params;
  1820. params.emplace("url", "http://example.com");
  1821. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1822. ASSERT_TRUE(res);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. TEST(UrlWithSpace, Redirect_Online) {
  1826. SSLClient cli("edge.forgecdn.net");
  1827. cli.set_follow_location(true);
  1828. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1829. ASSERT_TRUE(res);
  1830. EXPECT_EQ(StatusCode::OK_200, res->status);
  1831. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1832. }
  1833. #endif
  1834. #if !defined(_WIN32) && !defined(_WIN64)
  1835. TEST(ReceiveSignals, Signal) {
  1836. auto setupSignalHandlers = []() {
  1837. struct sigaction act;
  1838. sigemptyset(&act.sa_mask);
  1839. act.sa_flags = SA_SIGINFO;
  1840. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1841. switch (sig) {
  1842. case SIGINT:
  1843. default: break;
  1844. }
  1845. };
  1846. ::sigaction(SIGINT, &act, nullptr);
  1847. };
  1848. Server svr;
  1849. int port = 0;
  1850. auto thread = std::thread([&]() {
  1851. setupSignalHandlers();
  1852. port = svr.bind_to_any_port(HOST);
  1853. svr.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr.stop();
  1857. thread.join();
  1858. ASSERT_FALSE(svr.is_running());
  1859. });
  1860. svr.wait_until_ready();
  1861. ASSERT_TRUE(svr.is_running());
  1862. pthread_kill(thread.native_handle(), SIGINT);
  1863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1864. ASSERT_TRUE(svr.is_running());
  1865. }
  1866. #endif
  1867. TEST(RedirectToDifferentPort, Redirect) {
  1868. Server svr1;
  1869. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content("Hello World!", "text/plain");
  1871. });
  1872. int svr1_port = 0;
  1873. auto thread1 = std::thread([&]() {
  1874. svr1_port = svr1.bind_to_any_port(HOST);
  1875. svr1.listen_after_bind();
  1876. });
  1877. Server svr2;
  1878. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1880. });
  1881. int svr2_port = 0;
  1882. auto thread2 = std::thread([&]() {
  1883. svr2_port = svr2.bind_to_any_port(HOST);
  1884. svr2.listen_after_bind();
  1885. });
  1886. auto se = detail::scope_exit([&] {
  1887. svr2.stop();
  1888. thread2.join();
  1889. svr1.stop();
  1890. thread1.join();
  1891. ASSERT_FALSE(svr2.is_running());
  1892. ASSERT_FALSE(svr1.is_running());
  1893. });
  1894. svr1.wait_until_ready();
  1895. svr2.wait_until_ready();
  1896. Client cli("localhost", svr2_port);
  1897. cli.set_follow_location(true);
  1898. auto res = cli.Get("/2");
  1899. ASSERT_TRUE(res);
  1900. EXPECT_EQ(StatusCode::OK_200, res->status);
  1901. EXPECT_EQ("Hello World!", res->body);
  1902. }
  1903. TEST(RedirectFromPageWithContent, Redirect) {
  1904. Server svr;
  1905. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1906. res.set_content("___", "text/plain");
  1907. res.set_redirect("/2");
  1908. });
  1909. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. th.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. {
  1920. Client cli("localhost", PORT);
  1921. cli.set_follow_location(true);
  1922. std::string body;
  1923. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1924. body.append(data, data_length);
  1925. return true;
  1926. });
  1927. ASSERT_TRUE(res);
  1928. EXPECT_EQ(StatusCode::OK_200, res->status);
  1929. EXPECT_EQ("Hello World!", body);
  1930. }
  1931. {
  1932. Client cli("localhost", PORT);
  1933. std::string body;
  1934. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1935. body.append(data, data_length);
  1936. return true;
  1937. });
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(StatusCode::Found_302, res->status);
  1940. EXPECT_EQ("___", body);
  1941. }
  1942. }
  1943. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1944. Server svr;
  1945. auto port_str = std::to_string(PORT);
  1946. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1947. auto expected_host = "[::1]:" + port_str;
  1948. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1949. res.set_content("___", "text/plain");
  1950. // res.set_redirect("/2");
  1951. res.set_redirect(redirect_url);
  1952. });
  1953. svr.Get("/2", [&](const Request &req, Response &res) {
  1954. auto host_header = req.headers.find("Host");
  1955. ASSERT_TRUE(host_header != req.headers.end());
  1956. EXPECT_EQ(expected_host, host_header->second);
  1957. res.set_content("Hello World!", "text/plain");
  1958. });
  1959. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1960. auto se = detail::scope_exit([&] {
  1961. svr.stop();
  1962. th.join();
  1963. ASSERT_FALSE(svr.is_running());
  1964. });
  1965. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1966. // actually starts anything, so the condition !svr.is_running() will
  1967. // always remain true, and the loop never stops.
  1968. // This basically counts how many milliseconds have passed since the
  1969. // call to svr.listen(), and if after 5 seconds nothing started yet
  1970. // aborts the test.
  1971. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1972. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1973. ASSERT_LT(milliseconds, 5000U);
  1974. }
  1975. {
  1976. Client cli("::1", PORT);
  1977. cli.set_follow_location(true);
  1978. std::string body;
  1979. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1980. body.append(data, data_length);
  1981. return true;
  1982. });
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. EXPECT_EQ("Hello World!", body);
  1986. }
  1987. {
  1988. Client cli("::1", PORT);
  1989. std::string body;
  1990. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1991. body.append(data, data_length);
  1992. return true;
  1993. });
  1994. ASSERT_TRUE(res);
  1995. EXPECT_EQ(StatusCode::Found_302, res->status);
  1996. EXPECT_EQ("___", body);
  1997. }
  1998. }
  1999. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2000. Server svr;
  2001. svr.Get("/foo", [](const Request &req, Response &res) {
  2002. auto a = req.params.find("a");
  2003. if (a != req.params.end()) {
  2004. res.set_content((*a).second, "text/plain");
  2005. res.status = StatusCode::OK_200;
  2006. } else {
  2007. res.status = StatusCode::BadRequest_400;
  2008. }
  2009. });
  2010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2011. auto se = detail::scope_exit([&] {
  2012. svr.stop();
  2013. thread.join();
  2014. ASSERT_FALSE(svr.is_running());
  2015. });
  2016. svr.wait_until_ready();
  2017. {
  2018. Client cli(HOST, PORT);
  2019. cli.set_path_encode(false);
  2020. auto res = cli.Get("/foo?a=explicitly+encoded");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. // This expects it back with a space, as the `+` won't have been
  2024. // url-encoded, and server-side the params get decoded turning `+`
  2025. // into spaces.
  2026. EXPECT_EQ("explicitly encoded", res->body);
  2027. }
  2028. }
  2029. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2030. Server svr;
  2031. svr.Get("/", [](const Request &req, Response &) {
  2032. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli(HOST, PORT);
  2043. cli.set_path_encode(false);
  2044. auto res = cli.Get("/?something=%0A");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. }
  2048. }
  2049. TEST(BindServerTest, DISABLED_BindDualStack) {
  2050. Server svr;
  2051. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2052. res.set_content("Hello World!", "text/plain");
  2053. });
  2054. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2055. auto se = detail::scope_exit([&] {
  2056. svr.stop();
  2057. thread.join();
  2058. ASSERT_FALSE(svr.is_running());
  2059. });
  2060. svr.wait_until_ready();
  2061. {
  2062. Client cli("127.0.0.1", PORT);
  2063. auto res = cli.Get("/1");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(StatusCode::OK_200, res->status);
  2066. EXPECT_EQ("Hello World!", res->body);
  2067. }
  2068. {
  2069. Client cli("::1", PORT);
  2070. auto res = cli.Get("/1");
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::OK_200, res->status);
  2073. EXPECT_EQ("Hello World!", res->body);
  2074. }
  2075. }
  2076. TEST(BindServerTest, BindAndListenSeparately) {
  2077. Server svr;
  2078. int port = svr.bind_to_any_port("0.0.0.0");
  2079. ASSERT_TRUE(svr.is_valid());
  2080. ASSERT_TRUE(port > 0);
  2081. svr.stop();
  2082. }
  2083. #ifdef CPPHTTPLIB_SSL_ENABLED
  2084. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2086. CLIENT_CA_CERT_DIR);
  2087. int port = svr.bind_to_any_port("0.0.0.0");
  2088. ASSERT_TRUE(svr.is_valid());
  2089. ASSERT_TRUE(port > 0);
  2090. svr.stop();
  2091. }
  2092. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2093. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2094. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2095. int port = svr.bind_to_any_port("0.0.0.0");
  2096. ASSERT_TRUE(svr.is_valid());
  2097. ASSERT_TRUE(port > 0);
  2098. svr.stop();
  2099. }
  2100. TEST(BindServerTest, UpdateCertsPem) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. // Read PEM files
  2106. std::string cert_pem, key_pem, ca_pem;
  2107. read_file(SERVER_CERT_FILE, cert_pem);
  2108. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2109. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2110. // Update server certificates using PEM API
  2111. ASSERT_TRUE(
  2112. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2113. ASSERT_TRUE(svr.is_valid());
  2114. svr.stop();
  2115. }
  2116. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2117. // Start server with client CA (enables client auth)
  2118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2119. ASSERT_TRUE(svr.is_valid());
  2120. bool handler_called = false;
  2121. svr.Get("/test", [&](const Request &req, Response &res) {
  2122. handler_called = true;
  2123. // Verify client certificate is present
  2124. auto cert = req.peer_cert();
  2125. EXPECT_TRUE(static_cast<bool>(cert));
  2126. res.set_content("ok", "text/plain");
  2127. });
  2128. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2129. auto se = detail::scope_exit([&] {
  2130. svr.stop();
  2131. t.join();
  2132. ASSERT_FALSE(svr.is_running());
  2133. });
  2134. svr.wait_until_ready();
  2135. // Read PEM files
  2136. std::string cert_pem, key_pem, ca_pem;
  2137. read_file(SERVER_CERT_FILE, cert_pem);
  2138. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2139. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2140. // Update server certificates and client CA using PEM API while server running
  2141. ASSERT_TRUE(
  2142. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2143. // Connect with client certificate
  2144. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2145. cli.enable_server_certificate_verification(false);
  2146. cli.set_connection_timeout(30);
  2147. auto res = cli.Get("/test");
  2148. ASSERT_TRUE(res);
  2149. ASSERT_EQ(StatusCode::OK_200, res->status);
  2150. ASSERT_TRUE(handler_called);
  2151. EXPECT_EQ("ok", res->body);
  2152. }
  2153. #endif
  2154. TEST(ErrorHandlerTest, ContentLength) {
  2155. Server svr;
  2156. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2157. res.status = StatusCode::OK_200;
  2158. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2159. "text/html"); // <= Content-Length still 13
  2160. });
  2161. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2162. res.set_content("Hello World!\n", "text/plain");
  2163. res.status = 524;
  2164. });
  2165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2166. auto se = detail::scope_exit([&] {
  2167. svr.stop();
  2168. thread.join();
  2169. ASSERT_FALSE(svr.is_running());
  2170. });
  2171. svr.wait_until_ready();
  2172. {
  2173. Client cli(HOST, PORT);
  2174. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::OK_200, res->status);
  2177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2178. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2180. }
  2181. }
  2182. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2183. TEST(ExceptionTest, WithoutExceptionHandler) {
  2184. Server svr;
  2185. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2186. throw std::runtime_error("exception...");
  2187. });
  2188. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception\r\n...");
  2190. });
  2191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. listen_thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. Client cli("localhost", PORT);
  2199. {
  2200. auto res = cli.Get("/exception");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2203. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2204. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2205. }
  2206. {
  2207. auto res = cli.Get("/unknown");
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2210. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2211. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2212. }
  2213. }
  2214. TEST(ExceptionTest, WithExceptionHandler) {
  2215. Server svr;
  2216. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2217. std::exception_ptr ep) {
  2218. EXPECT_FALSE(ep == nullptr);
  2219. try {
  2220. std::rethrow_exception(ep);
  2221. } catch (std::exception &e) {
  2222. EXPECT_EQ("abc", std::string(e.what()));
  2223. } catch (...) {}
  2224. res.status = StatusCode::InternalServerError_500;
  2225. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2226. "text/html"); // <= Content-Length still 13 at this point
  2227. });
  2228. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2229. res.set_content("Hello World!\n", "text/plain");
  2230. throw std::runtime_error("abc");
  2231. });
  2232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2233. auto se = detail::scope_exit([&] {
  2234. svr.stop();
  2235. thread.join();
  2236. ASSERT_FALSE(svr.is_running());
  2237. });
  2238. svr.wait_until_ready();
  2239. for (size_t i = 0; i < 10; i++) {
  2240. Client cli(HOST, PORT);
  2241. for (size_t j = 0; j < 100; j++) {
  2242. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2243. ASSERT_TRUE(res);
  2244. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2245. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2246. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2248. }
  2249. cli.set_keep_alive(true);
  2250. for (size_t j = 0; j < 100; j++) {
  2251. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2254. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2255. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2256. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2257. }
  2258. }
  2259. }
  2260. TEST(ExceptionTest, AndErrorHandler) {
  2261. Server svr;
  2262. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2263. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2264. });
  2265. svr.set_exception_handler(
  2266. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2267. EXPECT_FALSE(ep == nullptr);
  2268. try {
  2269. std::rethrow_exception(ep);
  2270. } catch (std::exception &e) {
  2271. res.set_content(e.what(), "text/html");
  2272. } catch (...) {}
  2273. res.status = StatusCode::InternalServerError_500;
  2274. });
  2275. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2276. throw std::runtime_error("EXCEPTION");
  2277. });
  2278. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2279. res.set_content("ERROR", "text/html");
  2280. res.status = StatusCode::InternalServerError_500;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. Client cli(HOST, PORT);
  2290. {
  2291. auto res = cli.Get("/exception");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2294. EXPECT_EQ("EXCEPTION", res->body);
  2295. }
  2296. {
  2297. auto res = cli.Get("/error");
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2300. EXPECT_EQ("ERROR", res->body);
  2301. }
  2302. {
  2303. auto res = cli.Get("/invalid");
  2304. ASSERT_TRUE(res);
  2305. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2306. EXPECT_EQ("NOT_FOUND", res->body);
  2307. }
  2308. }
  2309. #endif
  2310. TEST(NoContentTest, ContentLength) {
  2311. Server svr;
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.status = StatusCode::NoContent_204;
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. Client cli(HOST, PORT);
  2324. auto res = cli.Get("/hi");
  2325. ASSERT_TRUE(res);
  2326. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2327. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2328. }
  2329. }
  2330. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2333. ASSERT_TRUE(svr.is_valid());
  2334. #else
  2335. Server svr;
  2336. #endif
  2337. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2338. if (req.path == "/routing_handler") {
  2339. res.set_header("PRE_ROUTING", "on");
  2340. res.set_content("Routing Handler", "text/plain");
  2341. return httplib::Server::HandlerResponse::Handled;
  2342. }
  2343. return httplib::Server::HandlerResponse::Unhandled;
  2344. });
  2345. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2346. res.set_content("Error", "text/html");
  2347. });
  2348. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2349. if (req.path == "/routing_handler") {
  2350. res.set_header("POST_ROUTING", "on");
  2351. }
  2352. });
  2353. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2354. res.set_content("Hello World!\n", "text/plain");
  2355. });
  2356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2357. auto se = detail::scope_exit([&] {
  2358. svr.stop();
  2359. thread.join();
  2360. ASSERT_FALSE(svr.is_running());
  2361. });
  2362. svr.wait_until_ready();
  2363. {
  2364. #ifdef CPPHTTPLIB_SSL_ENABLED
  2365. SSLClient cli(HOST, PORT);
  2366. cli.enable_server_certificate_verification(false);
  2367. #else
  2368. Client cli(HOST, PORT);
  2369. #endif
  2370. auto res = cli.Get("/routing_handler");
  2371. ASSERT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. EXPECT_EQ("Routing Handler", res->body);
  2374. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2375. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2376. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2377. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2378. }
  2379. {
  2380. #ifdef CPPHTTPLIB_SSL_ENABLED
  2381. SSLClient cli(HOST, PORT);
  2382. cli.enable_server_certificate_verification(false);
  2383. #else
  2384. Client cli(HOST, PORT);
  2385. #endif
  2386. auto res = cli.Get("/hi");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(StatusCode::OK_200, res->status);
  2389. EXPECT_EQ("Hello World!\n", res->body);
  2390. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2391. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2392. }
  2393. {
  2394. #ifdef CPPHTTPLIB_SSL_ENABLED
  2395. SSLClient cli(HOST, PORT);
  2396. cli.enable_server_certificate_verification(false);
  2397. #else
  2398. Client cli(HOST, PORT);
  2399. #endif
  2400. auto res = cli.Get("/aaa");
  2401. ASSERT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2403. EXPECT_EQ("Error", res->body);
  2404. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2405. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2406. }
  2407. }
  2408. TEST(RequestHandlerTest, PreRequestHandler) {
  2409. auto route_path = "/user/:user";
  2410. Server svr;
  2411. svr.Get("/hi", [](const Request &, Response &res) {
  2412. res.set_content("hi", "text/plain");
  2413. });
  2414. svr.Get(route_path, [](const Request &req, Response &res) {
  2415. res.set_content(req.path_params.at("user"), "text/plain");
  2416. });
  2417. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2418. if (req.matched_route == route_path) {
  2419. auto user = req.path_params.at("user");
  2420. if (user != "john") {
  2421. res.status = StatusCode::Forbidden_403;
  2422. res.set_content("error", "text/html");
  2423. return Server::HandlerResponse::Handled;
  2424. }
  2425. }
  2426. return Server::HandlerResponse::Unhandled;
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. Client cli(HOST, PORT);
  2436. {
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(StatusCode::OK_200, res->status);
  2440. EXPECT_EQ("hi", res->body);
  2441. }
  2442. {
  2443. auto res = cli.Get("/user/john");
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(StatusCode::OK_200, res->status);
  2446. EXPECT_EQ("john", res->body);
  2447. }
  2448. {
  2449. auto res = cli.Get("/user/invalid-user");
  2450. ASSERT_TRUE(res);
  2451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2452. EXPECT_EQ("error", res->body);
  2453. }
  2454. }
  2455. TEST(AnyTest, BasicOperations) {
  2456. // Default construction
  2457. httplib::any a;
  2458. EXPECT_FALSE(a.has_value());
  2459. // Value construction and any_cast (pointer form, noexcept)
  2460. httplib::any b(42);
  2461. EXPECT_TRUE(b.has_value());
  2462. auto *p = httplib::any_cast<int>(&b);
  2463. ASSERT_NE(nullptr, p);
  2464. EXPECT_EQ(42, *p);
  2465. // Type mismatch → nullptr
  2466. auto *q = httplib::any_cast<std::string>(&b);
  2467. EXPECT_EQ(nullptr, q);
  2468. // any_cast (value form) succeeds
  2469. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2470. // any_cast (value form) throws on type mismatch
  2471. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2472. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2473. #endif
  2474. // Copy
  2475. httplib::any c = b;
  2476. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2477. // Move
  2478. httplib::any d = std::move(c);
  2479. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2480. // Assignment with different type
  2481. b = std::string("hello");
  2482. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2483. // Reset
  2484. b.reset();
  2485. EXPECT_FALSE(b.has_value());
  2486. }
  2487. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2488. struct AuthCtx {
  2489. std::string user_id;
  2490. };
  2491. Server svr;
  2492. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2493. res.user_data["auth"] = AuthCtx{"alice"};
  2494. return Server::HandlerResponse::Unhandled;
  2495. });
  2496. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2497. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2498. ASSERT_NE(nullptr, ctx);
  2499. res.set_content("Hello " + ctx->user_id, "text/plain");
  2500. });
  2501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2502. auto se = detail::scope_exit([&] {
  2503. svr.stop();
  2504. thread.join();
  2505. ASSERT_FALSE(svr.is_running());
  2506. });
  2507. svr.wait_until_ready();
  2508. Client cli(HOST, PORT);
  2509. auto res = cli.Get("/me");
  2510. ASSERT_TRUE(res);
  2511. EXPECT_EQ(StatusCode::OK_200, res->status);
  2512. EXPECT_EQ("Hello alice", res->body);
  2513. }
  2514. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2515. struct RoleCtx {
  2516. std::string role;
  2517. };
  2518. Server svr;
  2519. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2520. res.user_data["role"] = RoleCtx{"admin"};
  2521. return Server::HandlerResponse::Unhandled;
  2522. });
  2523. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2524. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2525. ASSERT_NE(nullptr, ctx);
  2526. res.set_content(ctx->role, "text/plain");
  2527. });
  2528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2529. auto se = detail::scope_exit([&] {
  2530. svr.stop();
  2531. thread.join();
  2532. ASSERT_FALSE(svr.is_running());
  2533. });
  2534. svr.wait_until_ready();
  2535. Client cli(HOST, PORT);
  2536. auto res = cli.Get("/role");
  2537. ASSERT_TRUE(res);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. EXPECT_EQ("admin", res->body);
  2540. }
  2541. TEST(InvalidFormatTest, StatusCode) {
  2542. Server svr;
  2543. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2544. res.set_content("Hello World!\n", "text/plain");
  2545. res.status = 9999; // Status should be a three-digit code...
  2546. });
  2547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2548. auto se = detail::scope_exit([&] {
  2549. svr.stop();
  2550. thread.join();
  2551. ASSERT_FALSE(svr.is_running());
  2552. });
  2553. svr.wait_until_ready();
  2554. {
  2555. Client cli(HOST, PORT);
  2556. auto res = cli.Get("/hi");
  2557. ASSERT_FALSE(res);
  2558. }
  2559. }
  2560. TEST(URLFragmentTest, WithFragment) {
  2561. Server svr;
  2562. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2563. EXPECT_TRUE(req.target == "/hi");
  2564. });
  2565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2566. auto se = detail::scope_exit([&] {
  2567. svr.stop();
  2568. thread.join();
  2569. ASSERT_FALSE(svr.is_running());
  2570. });
  2571. svr.wait_until_ready();
  2572. {
  2573. Client cli(HOST, PORT);
  2574. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2575. EXPECT_TRUE(res);
  2576. EXPECT_EQ(StatusCode::OK_200, res->status);
  2577. res = cli.Get("/hi%23key1=val1=key2=val2");
  2578. EXPECT_TRUE(res);
  2579. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2580. }
  2581. }
  2582. TEST(HeaderWriter, SetHeaderWriter) {
  2583. Server svr;
  2584. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2585. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2586. return detail::write_headers(strm, hdrs);
  2587. });
  2588. svr.Get("/hi", [](const Request &req, Response &res) {
  2589. auto it = req.headers.find("CustomClientHeader");
  2590. EXPECT_TRUE(it != req.headers.end());
  2591. EXPECT_EQ(it->second, "CustomClientValue");
  2592. res.set_content("Hello World!\n", "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. {
  2602. Client cli(HOST, PORT);
  2603. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2604. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2605. return detail::write_headers(strm, hdrs);
  2606. });
  2607. auto res = cli.Get("/hi");
  2608. EXPECT_TRUE(res);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. auto it = res->headers.find("CustomServerHeader");
  2611. EXPECT_TRUE(it != res->headers.end());
  2612. EXPECT_EQ(it->second, "CustomServerValue");
  2613. }
  2614. }
  2615. class ServerTest : public ::testing::Test {
  2616. protected:
  2617. ServerTest()
  2618. : cli_(HOST, PORT)
  2619. #ifdef CPPHTTPLIB_SSL_ENABLED
  2620. ,
  2621. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2622. #endif
  2623. {
  2624. #ifdef CPPHTTPLIB_SSL_ENABLED
  2625. cli_.enable_server_certificate_verification(false);
  2626. #endif
  2627. // Allow LARGE_DATA (100MB) responses
  2628. cli_.set_payload_max_length(200 * 1024 * 1024);
  2629. }
  2630. virtual void SetUp() {
  2631. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2632. svr_.set_payload_max_length(200 * 1024 * 1024);
  2633. svr_.set_mount_point("/", "./www");
  2634. svr_.set_mount_point("/mount", "./www2");
  2635. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2636. svr_.Get("/hi",
  2637. [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. })
  2640. .Get("/file_content",
  2641. [&](const Request & /*req*/, Response &res) {
  2642. res.set_file_content("./www/dir/test.html");
  2643. })
  2644. .Get("/file_content_with_content_type",
  2645. [&](const Request & /*req*/, Response &res) {
  2646. res.set_file_content("./www/file", "text/plain");
  2647. })
  2648. .Get("/invalid_file_content",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_file_content("./www/dir/invalid_file_path");
  2651. })
  2652. .Get("/http_response_splitting",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2655. EXPECT_EQ(0U, res.headers.size());
  2656. EXPECT_FALSE(res.has_header("a"));
  2657. res.set_header("a", "1\nSet-Cookie: a=1");
  2658. EXPECT_EQ(0U, res.headers.size());
  2659. EXPECT_FALSE(res.has_header("a"));
  2660. res.set_header("a", "1\rSet-Cookie: a=1");
  2661. EXPECT_EQ(0U, res.headers.size());
  2662. EXPECT_FALSE(res.has_header("a"));
  2663. res.set_header("a\r\nb", "0");
  2664. EXPECT_EQ(0U, res.headers.size());
  2665. EXPECT_FALSE(res.has_header("a"));
  2666. res.set_header("a\rb", "0");
  2667. EXPECT_EQ(0U, res.headers.size());
  2668. EXPECT_FALSE(res.has_header("a"));
  2669. res.set_header("a\nb", "0");
  2670. EXPECT_EQ(0U, res.headers.size());
  2671. EXPECT_FALSE(res.has_header("a"));
  2672. res.set_redirect("1\r\nSet-Cookie: a=1");
  2673. EXPECT_EQ(0U, res.headers.size());
  2674. EXPECT_FALSE(res.has_header("Location"));
  2675. })
  2676. .Get("/slow",
  2677. [&](const Request & /*req*/, Response &res) {
  2678. std::this_thread::sleep_for(std::chrono::seconds(2));
  2679. res.set_content("slow", "text/plain");
  2680. })
  2681. #if 0
  2682. .Post("/slowpost",
  2683. [&](const Request & /*req*/, Response &res) {
  2684. std::this_thread::sleep_for(std::chrono::seconds(2));
  2685. res.set_content("slow", "text/plain");
  2686. })
  2687. #endif
  2688. .Get("/remote_addr",
  2689. [&](const Request &req, Response &res) {
  2690. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2691. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2692. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2693. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2694. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2695. #endif
  2696. res.set_content(req.remote_addr, "text/plain");
  2697. })
  2698. .Get("/local_addr",
  2699. [&](const Request &req, Response &res) {
  2700. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2701. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2702. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2703. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2704. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2705. #endif
  2706. auto local_addr = req.local_addr;
  2707. auto local_port = std::to_string(req.local_port);
  2708. res.set_content(local_addr.append(":").append(local_port),
  2709. "text/plain");
  2710. })
  2711. .Get("/endwith%",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. res.set_content("Hello World!", "text/plain");
  2714. })
  2715. .Get("/a\\+\\+b",
  2716. [&](const Request &req, Response &res) {
  2717. ASSERT_TRUE(req.has_param("a +b"));
  2718. auto val = req.get_param_value("a +b");
  2719. res.set_content(val, "text/plain");
  2720. })
  2721. .Get("/", [&](const Request & /*req*/,
  2722. Response &res) { res.set_redirect("/hi"); })
  2723. .Post("/1",
  2724. [](const Request & /*req*/, Response &res) {
  2725. res.set_redirect("/2", StatusCode::SeeOther_303);
  2726. })
  2727. .Get("/2",
  2728. [](const Request & /*req*/, Response &res) {
  2729. res.set_content("redirected.", "text/plain");
  2730. res.status = StatusCode::OK_200;
  2731. })
  2732. .Post("/person",
  2733. [&](const Request &req, Response &res) {
  2734. if (req.has_param("name") && req.has_param("note")) {
  2735. persons_[req.get_param_value("name")] =
  2736. req.get_param_value("note");
  2737. } else {
  2738. res.status = StatusCode::BadRequest_400;
  2739. }
  2740. })
  2741. .Put("/person",
  2742. [&](const Request &req, Response &res) {
  2743. if (req.has_param("name") && req.has_param("note")) {
  2744. persons_[req.get_param_value("name")] =
  2745. req.get_param_value("note");
  2746. } else {
  2747. res.status = StatusCode::BadRequest_400;
  2748. }
  2749. })
  2750. .Get("/person/(.*)",
  2751. [&](const Request &req, Response &res) {
  2752. string name = req.matches[1];
  2753. if (persons_.find(name) != persons_.end()) {
  2754. auto note = persons_[name];
  2755. res.set_content(note, "text/plain");
  2756. } else {
  2757. res.status = StatusCode::NotFound_404;
  2758. }
  2759. })
  2760. .Delete("/person",
  2761. [&](const Request &req, Response &res) {
  2762. if (req.has_param("name")) {
  2763. string name = req.get_param_value("name");
  2764. if (persons_.find(name) != persons_.end()) {
  2765. persons_.erase(name);
  2766. res.set_content("DELETED", "text/plain");
  2767. } else {
  2768. res.status = StatusCode::NotFound_404;
  2769. }
  2770. } else {
  2771. res.status = StatusCode::BadRequest_400;
  2772. }
  2773. })
  2774. .Post("/x-www-form-urlencoded-json",
  2775. [&](const Request &req, Response &res) {
  2776. auto json = req.get_param_value("json");
  2777. ASSERT_EQ(JSON_DATA, json);
  2778. res.set_content(json, "appliation/json");
  2779. res.status = StatusCode::OK_200;
  2780. })
  2781. .Get("/streamed-chunked",
  2782. [&](const Request & /*req*/, Response &res) {
  2783. res.set_chunked_content_provider(
  2784. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2785. sink.os << "123";
  2786. sink.os << "456";
  2787. sink.os << "789";
  2788. sink.done();
  2789. return true;
  2790. });
  2791. })
  2792. .Get("/streamed-chunked-with-prohibited-trailer",
  2793. [&](const Request & /*req*/, Response &res) {
  2794. auto i = new int(0);
  2795. // Declare both a prohibited trailer (Content-Length) and an
  2796. // allowed one
  2797. res.set_header("Trailer", "Content-Length, X-Allowed");
  2798. res.set_chunked_content_provider(
  2799. "text/plain",
  2800. [i](size_t /*offset*/, DataSink &sink) {
  2801. switch (*i) {
  2802. case 0: sink.os << "123"; break;
  2803. case 1: sink.os << "456"; break;
  2804. case 2: sink.os << "789"; break;
  2805. case 3: {
  2806. sink.done_with_trailer(
  2807. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2808. } break;
  2809. }
  2810. (*i)++;
  2811. return true;
  2812. },
  2813. [i](bool success) {
  2814. EXPECT_TRUE(success);
  2815. delete i;
  2816. });
  2817. })
  2818. .Get("/streamed-chunked2",
  2819. [&](const Request & /*req*/, Response &res) {
  2820. auto i = new int(0);
  2821. res.set_chunked_content_provider(
  2822. "text/plain",
  2823. [i](size_t /*offset*/, DataSink &sink) {
  2824. switch (*i) {
  2825. case 0: sink.os << "123"; break;
  2826. case 1: sink.os << "456"; break;
  2827. case 2: sink.os << "789"; break;
  2828. case 3: sink.done(); break;
  2829. }
  2830. (*i)++;
  2831. return true;
  2832. },
  2833. [i](bool success) {
  2834. EXPECT_TRUE(success);
  2835. delete i;
  2836. });
  2837. })
  2838. .Get("/streamed-chunked-with-trailer",
  2839. [&](const Request & /*req*/, Response &res) {
  2840. auto i = new int(0);
  2841. res.set_header("Trailer", "Dummy1, Dummy2");
  2842. res.set_chunked_content_provider(
  2843. "text/plain",
  2844. [i](size_t /*offset*/, DataSink &sink) {
  2845. switch (*i) {
  2846. case 0: sink.os << "123"; break;
  2847. case 1: sink.os << "456"; break;
  2848. case 2: sink.os << "789"; break;
  2849. case 3: {
  2850. sink.done_with_trailer(
  2851. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2852. } break;
  2853. }
  2854. (*i)++;
  2855. return true;
  2856. },
  2857. [i](bool success) {
  2858. EXPECT_TRUE(success);
  2859. delete i;
  2860. });
  2861. })
  2862. .Get("/streamed",
  2863. [&](const Request & /*req*/, Response &res) {
  2864. res.set_content_provider(
  2865. 6, "text/plain",
  2866. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2867. sink.os << (offset < 3 ? "a" : "b");
  2868. return true;
  2869. });
  2870. })
  2871. .Get("/streamed-with-range",
  2872. [&](const Request &req, Response &res) {
  2873. auto data = new std::string("abcdefg");
  2874. res.set_content_provider(
  2875. data->size(), "text/plain",
  2876. [data](size_t offset, size_t length, DataSink &sink) {
  2877. size_t DATA_CHUNK_SIZE = 4;
  2878. const auto &d = *data;
  2879. auto out_len =
  2880. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2881. auto ret =
  2882. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2883. EXPECT_TRUE(ret);
  2884. return true;
  2885. },
  2886. [data, &req](bool success) {
  2887. EXPECT_EQ(success, !req.has_param("error"));
  2888. delete data;
  2889. });
  2890. })
  2891. .Get("/streamed-cancel",
  2892. [&](const Request & /*req*/, Response &res) {
  2893. res.set_content_provider(
  2894. size_t(-1), "text/plain",
  2895. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2896. sink.os << "data_chunk";
  2897. return true;
  2898. });
  2899. })
  2900. .Get("/regex-with-delimiter",
  2901. [&](const Request &req, Response & /*res*/) {
  2902. ASSERT_TRUE(req.has_param("key"));
  2903. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2904. })
  2905. .Get("/with-range",
  2906. [&](const Request & /*req*/, Response &res) {
  2907. res.set_content("abcdefg", "text/plain");
  2908. })
  2909. .Get("/test-start-time",
  2910. [&](const Request &req, Response & /*res*/) {
  2911. EXPECT_NE(req.start_time_,
  2912. std::chrono::steady_clock::time_point::min());
  2913. })
  2914. .Get("/with-range-customized-response",
  2915. [&](const Request & /*req*/, Response &res) {
  2916. res.status = StatusCode::BadRequest_400;
  2917. res.set_content(JSON_DATA, "application/json");
  2918. })
  2919. .Post("/chunked",
  2920. [&](const Request &req, Response & /*res*/) {
  2921. EXPECT_EQ(req.body, "dechunked post body");
  2922. })
  2923. .Post("/large-chunked",
  2924. [&](const Request &req, Response & /*res*/) {
  2925. std::string expected(6 * 30 * 1024u, 'a');
  2926. EXPECT_EQ(req.body, expected);
  2927. })
  2928. .Post("/multipart",
  2929. [&](const Request &req, Response & /*res*/) {
  2930. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2931. req.form.get_field_count("text2") +
  2932. req.form.get_field_count("file3") +
  2933. req.form.get_field_count("file4"));
  2934. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2935. req.form.get_file_count("file2"));
  2936. ASSERT_TRUE(!req.form.has_file("???"));
  2937. ASSERT_TRUE(!req.form.has_field("???"));
  2938. ASSERT_TRUE(req.body.empty());
  2939. {
  2940. const auto &text = req.form.get_field("text1");
  2941. EXPECT_EQ("text default", text);
  2942. }
  2943. {
  2944. const auto &text = req.form.get_field("text2");
  2945. EXPECT_EQ("aωb", text);
  2946. }
  2947. {
  2948. const auto &file = req.form.get_file("file1");
  2949. EXPECT_EQ("hello.txt", file.filename);
  2950. EXPECT_EQ("text/plain", file.content_type);
  2951. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2952. }
  2953. {
  2954. const auto &file = req.form.get_file("file2");
  2955. EXPECT_EQ("world.json", file.filename);
  2956. EXPECT_EQ("application/json", file.content_type);
  2957. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2958. }
  2959. {
  2960. const auto &text = req.form.get_field("file3");
  2961. EXPECT_EQ(0u, text.size());
  2962. }
  2963. {
  2964. const auto &text = req.form.get_field("file4");
  2965. EXPECT_EQ(0u, text.size());
  2966. }
  2967. })
  2968. .Post("/multipart/multi_file_values",
  2969. [&](const Request &req, Response & /*res*/) {
  2970. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2971. req.form.get_field_count("multi_text1"));
  2972. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2973. ASSERT_TRUE(!req.form.has_file("???"));
  2974. ASSERT_TRUE(!req.form.has_field("???"));
  2975. ASSERT_TRUE(req.body.empty());
  2976. {
  2977. const auto &text = req.form.get_field("text");
  2978. EXPECT_EQ("default text", text);
  2979. }
  2980. {
  2981. const auto &text1_values = req.form.get_fields("multi_text1");
  2982. EXPECT_EQ(2u, text1_values.size());
  2983. EXPECT_EQ("aaaaa", text1_values[0]);
  2984. EXPECT_EQ("bbbbb", text1_values[1]);
  2985. }
  2986. {
  2987. const auto &file1_values = req.form.get_files("multi_file1");
  2988. EXPECT_EQ(2u, file1_values.size());
  2989. auto file1 = file1_values[0];
  2990. EXPECT_EQ(file1.filename, "hello.txt");
  2991. EXPECT_EQ(file1.content_type, "text/plain");
  2992. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2993. auto file2 = file1_values[1];
  2994. EXPECT_EQ(file2.filename, "world.json");
  2995. EXPECT_EQ(file2.content_type, "application/json");
  2996. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2997. }
  2998. })
  2999. .Post("/empty",
  3000. [&](const Request &req, Response &res) {
  3001. EXPECT_EQ(req.body, "");
  3002. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3003. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3004. res.set_content("empty", "text/plain");
  3005. })
  3006. .Post("/empty-no-content-type",
  3007. [&](const Request &req, Response &res) {
  3008. EXPECT_EQ(req.body, "");
  3009. EXPECT_FALSE(req.has_header("Content-Type"));
  3010. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3011. res.set_content("empty-no-content-type", "text/plain");
  3012. })
  3013. .Post("/path-only",
  3014. [&](const Request &req, Response &res) {
  3015. EXPECT_EQ(req.body, "");
  3016. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3017. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3018. res.set_content("path-only", "text/plain");
  3019. })
  3020. .Post("/path-headers-only",
  3021. [&](const Request &req, Response &res) {
  3022. EXPECT_EQ(req.body, "");
  3023. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3024. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3025. EXPECT_EQ("world", req.get_header_value("hello"));
  3026. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3027. res.set_content("path-headers-only", "text/plain");
  3028. })
  3029. .Post("/post-large",
  3030. [&](const Request &req, Response &res) {
  3031. EXPECT_EQ(req.body, LARGE_DATA);
  3032. res.set_content(req.body, "text/plain");
  3033. })
  3034. .Post("/post-loopback",
  3035. [&](const Request &, Response &res,
  3036. ContentReader const &content_reader) {
  3037. std::string body;
  3038. content_reader([&](const char *data, size_t data_length) {
  3039. body.append(data, data_length);
  3040. return true;
  3041. });
  3042. res.set_content(body, "text/plain");
  3043. })
  3044. .Put("/put-loopback",
  3045. [&](const Request &, Response &res,
  3046. ContentReader const &content_reader) {
  3047. std::string body;
  3048. content_reader([&](const char *data, size_t data_length) {
  3049. body.append(data, data_length);
  3050. return true;
  3051. });
  3052. res.set_content(body, "text/plain");
  3053. })
  3054. .Patch("/patch-loopback",
  3055. [&](const Request &, Response &res,
  3056. ContentReader const &content_reader) {
  3057. std::string body;
  3058. content_reader([&](const char *data, size_t data_length) {
  3059. body.append(data, data_length);
  3060. return true;
  3061. });
  3062. res.set_content(body, "text/plain");
  3063. })
  3064. .Put("/empty-no-content-type",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(req.body, "");
  3067. EXPECT_FALSE(req.has_header("Content-Type"));
  3068. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3069. res.set_content("empty-no-content-type", "text/plain");
  3070. })
  3071. .Put("/put",
  3072. [&](const Request &req, Response &res) {
  3073. EXPECT_EQ(req.body, "PUT");
  3074. res.set_content(req.body, "text/plain");
  3075. })
  3076. .Put("/put-large",
  3077. [&](const Request &req, Response &res) {
  3078. EXPECT_EQ(req.body, LARGE_DATA);
  3079. res.set_content(req.body, "text/plain");
  3080. })
  3081. .Patch("/patch",
  3082. [&](const Request &req, Response &res) {
  3083. EXPECT_EQ(req.body, "PATCH");
  3084. res.set_content(req.body, "text/plain");
  3085. })
  3086. .Delete("/delete",
  3087. [&](const Request & /*req*/, Response &res) {
  3088. res.set_content("DELETE", "text/plain");
  3089. })
  3090. .Delete("/delete-body",
  3091. [&](const Request &req, Response &res) {
  3092. EXPECT_EQ(req.body, "content");
  3093. res.set_content(req.body, "text/plain");
  3094. })
  3095. .Options(R"(\*)",
  3096. [&](const Request & /*req*/, Response &res) {
  3097. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3098. })
  3099. .Get("/request-target",
  3100. [&](const Request &req, Response & /*res*/) {
  3101. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3102. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3103. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3104. })
  3105. .Get("/long-query-value",
  3106. [&](const Request &req, Response & /*res*/) {
  3107. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3108. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3109. })
  3110. .Get("/too-long-query-value",
  3111. [&](const Request &req, Response & /*res*/) {
  3112. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3113. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3114. })
  3115. .Get("/array-param",
  3116. [&](const Request &req, Response & /*res*/) {
  3117. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3118. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3119. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3120. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3121. })
  3122. .Post("/validate-no-multiple-headers",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3125. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3126. })
  3127. .Post("/content_receiver",
  3128. [&](const Request &req, Response &res,
  3129. const ContentReader &content_reader) {
  3130. if (req.is_multipart_form_data()) {
  3131. std::vector<FormData> items;
  3132. content_reader(
  3133. [&](const FormData &file) {
  3134. items.push_back(file);
  3135. return true;
  3136. },
  3137. [&](const char *data, size_t data_length) {
  3138. items.back().content.append(data, data_length);
  3139. return true;
  3140. });
  3141. EXPECT_EQ(5u, items.size());
  3142. {
  3143. const auto &file = get_file_value(items, "text1");
  3144. EXPECT_TRUE(file.filename.empty());
  3145. EXPECT_EQ("text default", file.content);
  3146. }
  3147. {
  3148. const auto &file = get_file_value(items, "text2");
  3149. EXPECT_TRUE(file.filename.empty());
  3150. EXPECT_EQ("aωb", file.content);
  3151. }
  3152. {
  3153. const auto &file = get_file_value(items, "file1");
  3154. EXPECT_EQ("hello.txt", file.filename);
  3155. EXPECT_EQ("text/plain", file.content_type);
  3156. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3157. }
  3158. {
  3159. const auto &file = get_file_value(items, "file2");
  3160. EXPECT_EQ("world.json", file.filename);
  3161. EXPECT_EQ("application/json", file.content_type);
  3162. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3163. }
  3164. {
  3165. const auto &file = get_file_value(items, "file3");
  3166. EXPECT_TRUE(file.filename.empty());
  3167. EXPECT_EQ("application/octet-stream", file.content_type);
  3168. EXPECT_EQ(0u, file.content.size());
  3169. }
  3170. } else {
  3171. std::string body;
  3172. content_reader([&](const char *data, size_t data_length) {
  3173. EXPECT_EQ(7U, data_length);
  3174. body.append(data, data_length);
  3175. return true;
  3176. });
  3177. EXPECT_EQ(body, "content");
  3178. res.set_content(body, "text/plain");
  3179. }
  3180. })
  3181. .Put("/content_receiver",
  3182. [&](const Request & /*req*/, Response &res,
  3183. const ContentReader &content_reader) {
  3184. std::string body;
  3185. content_reader([&](const char *data, size_t data_length) {
  3186. body.append(data, data_length);
  3187. return true;
  3188. });
  3189. EXPECT_EQ(body, "content");
  3190. res.set_content(body, "text/plain");
  3191. })
  3192. .Patch("/content_receiver",
  3193. [&](const Request & /*req*/, Response &res,
  3194. const ContentReader &content_reader) {
  3195. std::string body;
  3196. content_reader([&](const char *data, size_t data_length) {
  3197. body.append(data, data_length);
  3198. return true;
  3199. });
  3200. EXPECT_EQ(body, "content");
  3201. res.set_content(body, "text/plain");
  3202. })
  3203. .Post("/query-string-and-body",
  3204. [&](const Request &req, Response & /*res*/) {
  3205. ASSERT_TRUE(req.has_param("key"));
  3206. EXPECT_EQ(req.get_param_value("key"), "value");
  3207. EXPECT_EQ(req.body, "content");
  3208. })
  3209. .Get("/last-request",
  3210. [&](const Request &req, Response & /*res*/) {
  3211. EXPECT_EQ("close", req.get_header_value("Connection"));
  3212. })
  3213. .Get(R"(/redirect/(\d+))",
  3214. [&](const Request &req, Response &res) {
  3215. auto num = std::stoi(req.matches[1]) + 1;
  3216. std::string url = "/redirect/" + std::to_string(num);
  3217. res.set_redirect(url);
  3218. })
  3219. .Post("/binary",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(4U, req.body.size());
  3222. EXPECT_EQ("application/octet-stream",
  3223. req.get_header_value("Content-Type"));
  3224. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3225. res.set_content(req.body, "application/octet-stream");
  3226. })
  3227. .Put("/binary",
  3228. [&](const Request &req, Response &res) {
  3229. EXPECT_EQ(4U, req.body.size());
  3230. EXPECT_EQ("application/octet-stream",
  3231. req.get_header_value("Content-Type"));
  3232. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3233. res.set_content(req.body, "application/octet-stream");
  3234. })
  3235. .Patch("/binary",
  3236. [&](const Request &req, Response &res) {
  3237. EXPECT_EQ(4U, req.body.size());
  3238. EXPECT_EQ("application/octet-stream",
  3239. req.get_header_value("Content-Type"));
  3240. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3241. res.set_content(req.body, "application/octet-stream");
  3242. })
  3243. .Delete("/binary",
  3244. [&](const Request &req, Response &res) {
  3245. EXPECT_EQ(4U, req.body.size());
  3246. EXPECT_EQ("application/octet-stream",
  3247. req.get_header_value("Content-Type"));
  3248. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3249. res.set_content(req.body, "application/octet-stream");
  3250. })
  3251. .Get("/issue1772",
  3252. [&](const Request & /*req*/, Response &res) {
  3253. res.status = 401;
  3254. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3255. })
  3256. .Delete("/issue609",
  3257. [](const httplib::Request &, httplib::Response &res,
  3258. const httplib::ContentReader &) {
  3259. res.set_content("ok", "text/plain");
  3260. })
  3261. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3262. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3263. .Get("/compress",
  3264. [&](const Request & /*req*/, Response &res) {
  3265. res.set_content(
  3266. "12345678901234567890123456789012345678901234567890123456789"
  3267. "01234567890123456789012345678901234567890",
  3268. "text/plain");
  3269. })
  3270. .Get("/nocompress",
  3271. [&](const Request & /*req*/, Response &res) {
  3272. res.set_content(
  3273. "12345678901234567890123456789012345678901234567890123456789"
  3274. "01234567890123456789012345678901234567890",
  3275. "application/octet-stream");
  3276. })
  3277. .Post("/compress-multipart",
  3278. [&](const Request &req, Response & /*res*/) {
  3279. EXPECT_EQ(2u, req.form.fields.size());
  3280. ASSERT_TRUE(!req.form.has_field("???"));
  3281. {
  3282. const auto &text = req.form.get_field("key1");
  3283. EXPECT_EQ("test", text);
  3284. }
  3285. {
  3286. const auto &text = req.form.get_field("key2");
  3287. EXPECT_EQ("--abcdefg123", text);
  3288. }
  3289. })
  3290. #endif
  3291. ;
  3292. persons_["john"] = "programmer";
  3293. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3294. svr_.wait_until_ready();
  3295. }
  3296. virtual void TearDown() {
  3297. svr_.stop();
  3298. if (!request_threads_.empty()) {
  3299. std::this_thread::sleep_for(std::chrono::seconds(1));
  3300. for (auto &t : request_threads_) {
  3301. t.join();
  3302. }
  3303. }
  3304. t_.join();
  3305. }
  3306. map<string, string> persons_;
  3307. #ifdef CPPHTTPLIB_SSL_ENABLED
  3308. SSLClient cli_;
  3309. SSLServer svr_;
  3310. #else
  3311. Client cli_;
  3312. Server svr_;
  3313. #endif
  3314. thread t_;
  3315. std::vector<thread> request_threads_;
  3316. };
  3317. TEST_F(ServerTest, GetMethod200) {
  3318. auto res = cli_.Get("/hi");
  3319. ASSERT_TRUE(res);
  3320. EXPECT_EQ("HTTP/1.1", res->version);
  3321. EXPECT_EQ(StatusCode::OK_200, res->status);
  3322. EXPECT_EQ("OK", res->reason);
  3323. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3324. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3325. EXPECT_EQ("Hello World!", res->body);
  3326. }
  3327. TEST_F(ServerTest, GetEmptyFile) {
  3328. auto res = cli_.Get("/empty_file");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3333. EXPECT_EQ("", res->body);
  3334. }
  3335. TEST_F(ServerTest, GetFileContent) {
  3336. auto res = cli_.Get("/file_content");
  3337. ASSERT_TRUE(res);
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3340. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3341. EXPECT_EQ("test.html", res->body);
  3342. }
  3343. TEST_F(ServerTest, GetFileContentWithRange) {
  3344. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3345. ASSERT_TRUE(res);
  3346. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3347. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3348. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3349. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3350. EXPECT_EQ("est", res->body);
  3351. }
  3352. TEST_F(ServerTest, GetFileContentWithContentType) {
  3353. auto res = cli_.Get("/file_content_with_content_type");
  3354. ASSERT_TRUE(res);
  3355. EXPECT_EQ(StatusCode::OK_200, res->status);
  3356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3357. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3358. EXPECT_EQ("file\n", res->body);
  3359. }
  3360. TEST_F(ServerTest, GetInvalidFileContent) {
  3361. auto res = cli_.Get("/invalid_file_content");
  3362. ASSERT_TRUE(res);
  3363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3364. }
  3365. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3366. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3367. ASSERT_TRUE(res);
  3368. EXPECT_EQ("HTTP/1.1", res->version);
  3369. EXPECT_EQ(StatusCode::OK_200, res->status);
  3370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3372. EXPECT_EQ("Hello World!", res->body);
  3373. }
  3374. TEST_F(ServerTest, GetMethod302) {
  3375. auto res = cli_.Get("/");
  3376. ASSERT_TRUE(res);
  3377. EXPECT_EQ(StatusCode::Found_302, res->status);
  3378. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3379. }
  3380. TEST_F(ServerTest, GetMethod302Redirect) {
  3381. cli_.set_follow_location(true);
  3382. auto res = cli_.Get("/");
  3383. ASSERT_TRUE(res);
  3384. EXPECT_EQ(StatusCode::OK_200, res->status);
  3385. EXPECT_EQ("Hello World!", res->body);
  3386. EXPECT_EQ("/hi", res->location);
  3387. }
  3388. TEST_F(ServerTest, GetMethod404) {
  3389. auto res = cli_.Get("/invalid");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3392. }
  3393. TEST_F(ServerTest, HeadMethod200) {
  3394. auto res = cli_.Head("/hi");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. EXPECT_TRUE(res->body.empty());
  3399. }
  3400. TEST_F(ServerTest, HeadMethod200Static) {
  3401. auto res = cli_.Head("/mount/dir/index.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::OK_200, res->status);
  3404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3405. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3406. EXPECT_TRUE(res->body.empty());
  3407. }
  3408. TEST_F(ServerTest, HeadMethod404) {
  3409. auto res = cli_.Head("/invalid");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3412. EXPECT_TRUE(res->body.empty());
  3413. }
  3414. TEST_F(ServerTest, GetMethodPersonJohn) {
  3415. auto res = cli_.Get("/person/john");
  3416. ASSERT_TRUE(res);
  3417. EXPECT_EQ(StatusCode::OK_200, res->status);
  3418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3419. EXPECT_EQ("programmer", res->body);
  3420. }
  3421. TEST_F(ServerTest, PostMethod1) {
  3422. auto res = cli_.Get("/person/john1");
  3423. ASSERT_TRUE(res);
  3424. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3425. res = cli_.Post("/person", "name=john1&note=coder",
  3426. "application/x-www-form-urlencoded");
  3427. ASSERT_TRUE(res);
  3428. ASSERT_EQ(StatusCode::OK_200, res->status);
  3429. res = cli_.Get("/person/john1");
  3430. ASSERT_TRUE(res);
  3431. ASSERT_EQ(StatusCode::OK_200, res->status);
  3432. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3433. ASSERT_EQ("coder", res->body);
  3434. }
  3435. TEST_F(ServerTest, PostMethod2) {
  3436. auto res = cli_.Get("/person/john2");
  3437. ASSERT_TRUE(res);
  3438. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3439. Params params;
  3440. params.emplace("name", "john2");
  3441. params.emplace("note", "coder");
  3442. res = cli_.Post("/person", params);
  3443. ASSERT_TRUE(res);
  3444. ASSERT_EQ(StatusCode::OK_200, res->status);
  3445. res = cli_.Get("/person/john2");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3449. ASSERT_EQ("coder", res->body);
  3450. }
  3451. TEST_F(ServerTest, PutMethod3) {
  3452. auto res = cli_.Get("/person/john3");
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3455. Params params;
  3456. params.emplace("name", "john3");
  3457. params.emplace("note", "coder");
  3458. res = cli_.Put("/person", params);
  3459. ASSERT_TRUE(res);
  3460. ASSERT_EQ(StatusCode::OK_200, res->status);
  3461. res = cli_.Get("/person/john3");
  3462. ASSERT_TRUE(res);
  3463. ASSERT_EQ(StatusCode::OK_200, res->status);
  3464. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3465. ASSERT_EQ("coder", res->body);
  3466. }
  3467. TEST_F(ServerTest, DeleteMethod1) {
  3468. auto res = cli_.Get("/person/john4");
  3469. ASSERT_TRUE(res);
  3470. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3471. Params params;
  3472. params.emplace("name", "john4");
  3473. params.emplace("note", "coder");
  3474. res = cli_.Post("/person", params);
  3475. ASSERT_TRUE(res);
  3476. ASSERT_EQ(StatusCode::OK_200, res->status);
  3477. res = cli_.Get("/person/john4");
  3478. ASSERT_TRUE(res);
  3479. ASSERT_EQ(StatusCode::OK_200, res->status);
  3480. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3481. ASSERT_EQ("coder", res->body);
  3482. Params delete_params;
  3483. delete_params.emplace("name", "john4");
  3484. res = cli_.Delete("/person", delete_params);
  3485. ASSERT_TRUE(res);
  3486. ASSERT_EQ(StatusCode::OK_200, res->status);
  3487. ASSERT_EQ("DELETED", res->body);
  3488. res = cli_.Get("/person/john4");
  3489. ASSERT_TRUE(res);
  3490. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3491. }
  3492. TEST_F(ServerTest, DeleteMethod2) {
  3493. auto res = cli_.Get("/person/john5");
  3494. ASSERT_TRUE(res);
  3495. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3496. Params params;
  3497. params.emplace("name", "john5");
  3498. params.emplace("note", "developer");
  3499. res = cli_.Post("/person", params);
  3500. ASSERT_TRUE(res);
  3501. ASSERT_EQ(StatusCode::OK_200, res->status);
  3502. res = cli_.Get("/person/john5");
  3503. ASSERT_TRUE(res);
  3504. ASSERT_EQ(StatusCode::OK_200, res->status);
  3505. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3506. ASSERT_EQ("developer", res->body);
  3507. Params delete_params;
  3508. delete_params.emplace("name", "john5");
  3509. Headers headers;
  3510. headers.emplace("Custom-Header", "test-value");
  3511. res = cli_.Delete("/person", headers, delete_params);
  3512. ASSERT_TRUE(res);
  3513. ASSERT_EQ(StatusCode::OK_200, res->status);
  3514. ASSERT_EQ("DELETED", res->body);
  3515. res = cli_.Get("/person/john5");
  3516. ASSERT_TRUE(res);
  3517. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3518. }
  3519. TEST_F(ServerTest, DeleteMethod3) {
  3520. auto res = cli_.Get("/person/john6");
  3521. ASSERT_TRUE(res);
  3522. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3523. Params params;
  3524. params.emplace("name", "john6");
  3525. params.emplace("note", "tester");
  3526. res = cli_.Post("/person", params);
  3527. ASSERT_TRUE(res);
  3528. ASSERT_EQ(StatusCode::OK_200, res->status);
  3529. res = cli_.Get("/person/john6");
  3530. ASSERT_TRUE(res);
  3531. ASSERT_EQ(StatusCode::OK_200, res->status);
  3532. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3533. ASSERT_EQ("tester", res->body);
  3534. Params delete_params;
  3535. delete_params.emplace("name", "john6");
  3536. Headers headers;
  3537. headers.emplace("Custom-Header", "test-value");
  3538. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3539. ASSERT_TRUE(res);
  3540. ASSERT_EQ(StatusCode::OK_200, res->status);
  3541. ASSERT_EQ("DELETED", res->body);
  3542. res = cli_.Get("/person/john6");
  3543. ASSERT_TRUE(res);
  3544. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3545. }
  3546. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3547. Params params;
  3548. params.emplace("json", JSON_DATA);
  3549. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3550. ASSERT_TRUE(res);
  3551. ASSERT_EQ(StatusCode::OK_200, res->status);
  3552. ASSERT_EQ(JSON_DATA, res->body);
  3553. }
  3554. TEST_F(ServerTest, PostEmptyContent) {
  3555. auto res = cli_.Post("/empty", "", "text/plain");
  3556. ASSERT_TRUE(res);
  3557. ASSERT_EQ(StatusCode::OK_200, res->status);
  3558. ASSERT_EQ("empty", res->body);
  3559. }
  3560. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3561. auto res = cli_.Post("/empty-no-content-type");
  3562. ASSERT_TRUE(res);
  3563. ASSERT_EQ(StatusCode::OK_200, res->status);
  3564. ASSERT_EQ("empty-no-content-type", res->body);
  3565. }
  3566. TEST_F(ServerTest, PostPathOnly) {
  3567. auto res = cli_.Post("/path-only");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::OK_200, res->status);
  3570. ASSERT_EQ("path-only", res->body);
  3571. }
  3572. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3573. auto res = cli_.Post("/path-headers-only",
  3574. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3575. ASSERT_TRUE(res);
  3576. ASSERT_EQ(StatusCode::OK_200, res->status);
  3577. ASSERT_EQ("path-headers-only", res->body);
  3578. }
  3579. TEST_F(ServerTest, PostLarge) {
  3580. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3581. ASSERT_TRUE(res);
  3582. ASSERT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ(LARGE_DATA, res->body);
  3584. }
  3585. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3586. auto res = cli_.Put("/empty-no-content-type");
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. ASSERT_EQ("empty-no-content-type", res->body);
  3590. }
  3591. TEST_F(ServerTest, GetMethodDir) {
  3592. auto res = cli_.Get("/dir/");
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3596. auto body = R"(<html>
  3597. <head>
  3598. </head>
  3599. <body>
  3600. <a href="/dir/test.html">Test</a>
  3601. <a href="/hi">hi</a>
  3602. </body>
  3603. </html>
  3604. )";
  3605. EXPECT_EQ(body, res->body);
  3606. }
  3607. TEST_F(ServerTest, GetMethodDirTest) {
  3608. auto res = cli_.Get("/dir/test.html");
  3609. ASSERT_TRUE(res);
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3612. EXPECT_EQ("test.html", res->body);
  3613. }
  3614. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3615. auto res = cli_.Get("/dir/../dir/test.html");
  3616. ASSERT_TRUE(res);
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3619. EXPECT_EQ("test.html", res->body);
  3620. }
  3621. TEST_F(ServerTest, GetMethodInvalidPath) {
  3622. auto res = cli_.Get("/dir/../test.html");
  3623. ASSERT_TRUE(res);
  3624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3625. }
  3626. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3627. auto res = cli_.Get("/../www/dir/test.html");
  3628. ASSERT_TRUE(res);
  3629. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3630. }
  3631. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3632. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3633. ASSERT_TRUE(res);
  3634. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3635. }
  3636. TEST_F(ServerTest, GetMethodDirMountTest) {
  3637. auto res = cli_.Get("/mount/dir/test.html");
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::OK_200, res->status);
  3640. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3641. EXPECT_EQ("test.html", res->body);
  3642. }
  3643. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3644. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3645. ASSERT_TRUE(res);
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3648. EXPECT_EQ("test.html", res->body);
  3649. }
  3650. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3651. auto res = cli_.Get("/mount/dir/../test.html");
  3652. ASSERT_TRUE(res);
  3653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3654. }
  3655. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3656. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3657. ASSERT_TRUE(res);
  3658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3659. }
  3660. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3661. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3662. ASSERT_TRUE(res);
  3663. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3664. }
  3665. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3666. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3667. ASSERT_TRUE(res);
  3668. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3669. }
  3670. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3671. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3672. ASSERT_TRUE(res);
  3673. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3674. }
  3675. TEST_F(ServerTest, PostMethod303) {
  3676. auto res = cli_.Post("/1", "body", "text/plain");
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3679. EXPECT_EQ("/2", res->get_header_value("Location"));
  3680. }
  3681. TEST_F(ServerTest, PostMethod303Redirect) {
  3682. cli_.set_follow_location(true);
  3683. auto res = cli_.Post("/1", "body", "text/plain");
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::OK_200, res->status);
  3686. EXPECT_EQ("redirected.", res->body);
  3687. EXPECT_EQ("/2", res->location);
  3688. }
  3689. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3690. auto res = cli_.Get("/dir/test.abcde");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::OK_200, res->status);
  3693. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3694. EXPECT_EQ("abcde", res->body);
  3695. }
  3696. TEST_F(ServerTest, StaticFileRange) {
  3697. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3698. ASSERT_TRUE(res);
  3699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3700. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3701. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3702. EXPECT_EQ(true, res->has_header("Content-Range"));
  3703. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3704. EXPECT_EQ(std::string("cd"), res->body);
  3705. }
  3706. TEST_F(ServerTest, StaticFileRanges) {
  3707. auto res =
  3708. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3711. EXPECT_TRUE(
  3712. res->get_header_value("Content-Type")
  3713. .find(
  3714. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3715. 0);
  3716. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3717. }
  3718. TEST_F(ServerTest, StaticFileRangeHead) {
  3719. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3720. ASSERT_TRUE(res);
  3721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3722. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3723. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3724. EXPECT_EQ(true, res->has_header("Content-Range"));
  3725. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3726. }
  3727. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3728. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3729. ASSERT_TRUE(res);
  3730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3731. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3732. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3733. EXPECT_EQ(true, res->has_header("Content-Range"));
  3734. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3735. res->get_header_value("Content-Range"));
  3736. EXPECT_EQ("LAST\n", res->body);
  3737. }
  3738. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3739. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3743. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3744. EXPECT_EQ(true, res->has_header("Content-Range"));
  3745. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3746. }
  3747. TEST_F(ServerTest, StaticFileBigFile) {
  3748. auto res = cli_.Get("/dir/1MB.txt");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::OK_200, res->status);
  3751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3752. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3753. }
  3754. TEST_F(ServerTest, InvalidBaseDirMount) {
  3755. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3756. }
  3757. TEST_F(ServerTest, Binary) {
  3758. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3759. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3760. "application/octet-stream");
  3761. ASSERT_TRUE(res);
  3762. ASSERT_EQ(StatusCode::OK_200, res->status);
  3763. ASSERT_EQ(4U, res->body.size());
  3764. res = cli_.Put("/binary", binary.data(), binary.size(),
  3765. "application/octet-stream");
  3766. ASSERT_TRUE(res);
  3767. ASSERT_EQ(StatusCode::OK_200, res->status);
  3768. ASSERT_EQ(4U, res->body.size());
  3769. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3770. "application/octet-stream");
  3771. ASSERT_TRUE(res);
  3772. ASSERT_EQ(StatusCode::OK_200, res->status);
  3773. ASSERT_EQ(4U, res->body.size());
  3774. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3775. "application/octet-stream");
  3776. ASSERT_TRUE(res);
  3777. ASSERT_EQ(StatusCode::OK_200, res->status);
  3778. ASSERT_EQ(4U, res->body.size());
  3779. }
  3780. TEST_F(ServerTest, BinaryString) {
  3781. auto binary = std::string("\x00\x01\x02\x03", 4);
  3782. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3783. ASSERT_TRUE(res);
  3784. ASSERT_EQ(StatusCode::OK_200, res->status);
  3785. ASSERT_EQ(4U, res->body.size());
  3786. res = cli_.Put("/binary", binary, "application/octet-stream");
  3787. ASSERT_TRUE(res);
  3788. ASSERT_EQ(StatusCode::OK_200, res->status);
  3789. ASSERT_EQ(4U, res->body.size());
  3790. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3791. ASSERT_TRUE(res);
  3792. ASSERT_EQ(StatusCode::OK_200, res->status);
  3793. ASSERT_EQ(4U, res->body.size());
  3794. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3795. ASSERT_TRUE(res);
  3796. ASSERT_EQ(StatusCode::OK_200, res->status);
  3797. ASSERT_EQ(4U, res->body.size());
  3798. }
  3799. TEST_F(ServerTest, EmptyRequest) {
  3800. auto res = cli_.Get("");
  3801. ASSERT_TRUE(!res);
  3802. EXPECT_EQ(Error::Connection, res.error());
  3803. }
  3804. TEST_F(ServerTest, LongRequest) {
  3805. std::string request;
  3806. for (size_t i = 0; i < 545; i++) {
  3807. request += "/TooLongRequest";
  3808. }
  3809. request += "OK";
  3810. auto res = cli_.Get(request.c_str());
  3811. ASSERT_TRUE(res);
  3812. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3813. }
  3814. TEST_F(ServerTest, TooLongRequest) {
  3815. std::string request;
  3816. for (size_t i = 0; i < 546; i++) {
  3817. request += "/TooLongRequest";
  3818. }
  3819. request += "_NG";
  3820. auto start = std::chrono::high_resolution_clock::now();
  3821. cli_.set_keep_alive(true);
  3822. auto res = cli_.Get(request.c_str());
  3823. auto end = std::chrono::high_resolution_clock::now();
  3824. auto elapsed =
  3825. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3826. .count();
  3827. ASSERT_TRUE(res);
  3828. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3829. EXPECT_LE(elapsed, 1000);
  3830. EXPECT_EQ("close", res->get_header_value("Connection"));
  3831. EXPECT_FALSE(cli_.is_socket_open());
  3832. }
  3833. TEST_F(ServerTest, AlmostTooLongRequest) {
  3834. // test for #2046 - URI length check shouldn't include other content on req
  3835. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3836. // leading /, space, HTTP/1.1)
  3837. std::string request =
  3838. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3839. auto res = cli_.Get(request.c_str());
  3840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3841. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3842. }
  3843. TEST_F(ServerTest, LongHeader) {
  3844. Request req;
  3845. req.method = "GET";
  3846. req.path = "/hi";
  3847. std::string host_and_port;
  3848. host_and_port += HOST;
  3849. host_and_port += ":";
  3850. host_and_port += std::to_string(PORT);
  3851. req.headers.emplace("Host", host_and_port.c_str());
  3852. req.headers.emplace("Accept", "*/*");
  3853. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3854. req.headers.emplace(
  3855. "Header-Name",
  3856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@");
  3885. auto res = std::make_shared<Response>();
  3886. auto error = Error::Success;
  3887. auto ret = cli_.send(req, *res, error);
  3888. ASSERT_TRUE(ret);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. }
  3891. TEST_F(ServerTest, LongQueryValue) {
  3892. auto start = std::chrono::high_resolution_clock::now();
  3893. cli_.set_keep_alive(true);
  3894. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3895. auto end = std::chrono::high_resolution_clock::now();
  3896. auto elapsed =
  3897. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3898. .count();
  3899. ASSERT_TRUE(res);
  3900. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3901. EXPECT_LE(elapsed, 1000);
  3902. EXPECT_EQ("close", res->get_header_value("Connection"));
  3903. EXPECT_FALSE(cli_.is_socket_open());
  3904. }
  3905. TEST_F(ServerTest, TooLongQueryValue) {
  3906. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3907. ASSERT_FALSE(res);
  3908. EXPECT_EQ(Error::Read, res.error());
  3909. }
  3910. TEST_F(ServerTest, TooLongHeader) {
  3911. Request req;
  3912. req.method = "GET";
  3913. req.path = "/hi";
  3914. std::string host_and_port;
  3915. host_and_port += HOST;
  3916. host_and_port += ":";
  3917. host_and_port += std::to_string(PORT);
  3918. req.headers.emplace("Host", host_and_port.c_str());
  3919. req.headers.emplace("Accept", "*/*");
  3920. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3921. req.headers.emplace(
  3922. "Header-Name",
  3923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@");
  3952. auto res = std::make_shared<Response>();
  3953. auto error = Error::Success;
  3954. auto ret = cli_.send(req, *res, error);
  3955. ASSERT_TRUE(ret);
  3956. EXPECT_EQ(StatusCode::OK_200, res->status);
  3957. }
  3958. TEST_F(ServerTest, HeaderCountAtLimit) {
  3959. // Test with headers just under the 100 limit
  3960. httplib::Headers headers;
  3961. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3962. // This should keep us just under the 100 header limit
  3963. for (int i = 0; i < 95; i++) {
  3964. std::string name = "X-Test-Header-" + std::to_string(i);
  3965. std::string value = "value" + std::to_string(i);
  3966. headers.emplace(name, value);
  3967. }
  3968. // This should work fine as we're under the limit
  3969. auto res = cli_.Get("/hi", headers);
  3970. EXPECT_TRUE(res);
  3971. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3972. }
  3973. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3974. // Test with many headers to exceed the 100 limit
  3975. httplib::Headers headers;
  3976. // Add 150 headers to definitely exceed the 100 limit
  3977. for (int i = 0; i < 150; i++) {
  3978. std::string name = "X-Test-Header-" + std::to_string(i);
  3979. std::string value = "value" + std::to_string(i);
  3980. headers.emplace(name, value);
  3981. }
  3982. // This should fail due to exceeding header count limit
  3983. cli_.set_keep_alive(true);
  3984. auto res = cli_.Get("/hi", headers);
  3985. // The server should respond with 400 Bad Request
  3986. ASSERT_TRUE(res);
  3987. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3988. EXPECT_EQ("close", res->get_header_value("Connection"));
  3989. EXPECT_FALSE(cli_.is_socket_open());
  3990. }
  3991. TEST_F(ServerTest, PercentEncoding) {
  3992. auto res = cli_.Get("/e%6edwith%");
  3993. ASSERT_TRUE(res);
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. }
  3996. TEST_F(ServerTest, PercentEncodingUnicode) {
  3997. auto res = cli_.Get("/e%u006edwith%");
  3998. ASSERT_TRUE(res);
  3999. EXPECT_EQ(StatusCode::OK_200, res->status);
  4000. }
  4001. TEST_F(ServerTest, InvalidPercentEncoding) {
  4002. auto res = cli_.Get("/%endwith%");
  4003. ASSERT_TRUE(res);
  4004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4005. }
  4006. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4007. auto res = cli_.Get("/%uendwith%");
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4010. }
  4011. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4012. auto res = cli_.Get("/hello?aaa=bbb%");
  4013. ASSERT_TRUE(res);
  4014. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4015. }
  4016. TEST_F(ServerTest, PlusSignEncoding) {
  4017. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("a +b", res->body);
  4021. }
  4022. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4023. // This test simulates a potential DoS attack using many headers
  4024. // to verify our security fix prevents memory exhaustion
  4025. httplib::Headers attack_headers;
  4026. // Attempt to add many headers like an attacker would (200 headers to far
  4027. // exceed limit)
  4028. for (int i = 0; i < 200; i++) {
  4029. std::string name = "X-Attack-Header-" + std::to_string(i);
  4030. std::string value = "attack_payload_" + std::to_string(i);
  4031. attack_headers.emplace(name, value);
  4032. }
  4033. // Try to POST with excessive headers
  4034. cli_.set_keep_alive(true);
  4035. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4036. // Should either fail or return 400 Bad Request due to security limit
  4037. if (res) {
  4038. // If we get a response, it should be 400 Bad Request
  4039. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4040. } else {
  4041. // Request failed, which is the expected behavior for DoS protection
  4042. EXPECT_FALSE(res);
  4043. }
  4044. EXPECT_EQ("close", res->get_header_value("Connection"));
  4045. EXPECT_FALSE(cli_.is_socket_open());
  4046. }
  4047. TEST_F(ServerTest, MultipartFormData) {
  4048. UploadFormDataItems items = {
  4049. {"text1", "text default", "", ""},
  4050. {"text2", "aωb", "", ""},
  4051. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4052. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4053. {"file3", "", "", "application/octet-stream"},
  4054. {"file4", "", "", " application/json tmp-string "}};
  4055. auto res = cli_.Post("/multipart", items);
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. }
  4059. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4060. UploadFormDataItems items = {
  4061. {"text", "default text", "", ""},
  4062. {"multi_text1", "aaaaa", "", ""},
  4063. {"multi_text1", "bbbbb", "", ""},
  4064. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4065. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4066. "application/json"},
  4067. };
  4068. auto res = cli_.Post("/multipart/multi_file_values", items);
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. }
  4072. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4073. auto res = cli_.Get("/hi");
  4074. ASSERT_TRUE(res);
  4075. EXPECT_EQ(StatusCode::OK_200, res->status);
  4076. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4077. EXPECT_EQ("Hello World!", res->body);
  4078. }
  4079. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4080. Request req;
  4081. req.method = "POST";
  4082. req.path = "/chunked";
  4083. std::string host_and_port;
  4084. host_and_port += HOST;
  4085. host_and_port += ":";
  4086. host_and_port += std::to_string(PORT);
  4087. req.headers.emplace("Host", host_and_port.c_str());
  4088. req.headers.emplace("Accept", "*/*");
  4089. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4090. req.headers.emplace("Content-Type", "text/plain");
  4091. req.headers.emplace("Content-Length", "0");
  4092. req.headers.emplace(
  4093. "Transfer-Encoding",
  4094. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4095. // Client does not chunk, so make a chunked body manually.
  4096. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4097. auto res = std::make_shared<Response>();
  4098. auto error = Error::Success;
  4099. auto ret = cli_.send(req, *res, error);
  4100. ASSERT_TRUE(ret);
  4101. EXPECT_EQ(StatusCode::OK_200, res->status);
  4102. }
  4103. TEST_F(ServerTest, GetStreamed2) {
  4104. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4107. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4108. EXPECT_EQ(true, res->has_header("Content-Range"));
  4109. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4110. EXPECT_EQ(std::string("ab"), res->body);
  4111. }
  4112. TEST_F(ServerTest, GetStreamed) {
  4113. auto res = cli_.Get("/streamed");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4117. EXPECT_EQ(std::string("aaabbb"), res->body);
  4118. }
  4119. TEST_F(ServerTest, GetStreamedWithRange1) {
  4120. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4121. ASSERT_TRUE(res);
  4122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4123. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4124. EXPECT_EQ(true, res->has_header("Content-Range"));
  4125. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4126. EXPECT_EQ(std::string("def"), res->body);
  4127. }
  4128. TEST_F(ServerTest, GetStreamedWithRange2) {
  4129. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4130. ASSERT_TRUE(res);
  4131. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4132. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4133. EXPECT_EQ(true, res->has_header("Content-Range"));
  4134. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4135. EXPECT_EQ(std::string("bcdefg"), res->body);
  4136. }
  4137. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4138. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4141. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4142. EXPECT_EQ(true, res->has_header("Content-Range"));
  4143. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4144. EXPECT_EQ(std::string("efg"), res->body);
  4145. }
  4146. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4147. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4148. ASSERT_TRUE(res);
  4149. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4150. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4151. EXPECT_EQ(false, res->has_header("Content-Range"));
  4152. EXPECT_EQ(0U, res->body.size());
  4153. }
  4154. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4155. auto res = cli_.Get("/streamed-with-range",
  4156. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4157. "92233720368547758079223372036854775807"}});
  4158. ASSERT_TRUE(res);
  4159. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4160. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4161. EXPECT_EQ(false, res->has_header("Content-Range"));
  4162. EXPECT_EQ(0U, res->body.size());
  4163. }
  4164. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4165. auto res = cli_.Get(
  4166. "/with-range",
  4167. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4168. {"Accept-Encoding", ""}});
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4171. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4172. EXPECT_EQ(true, res->has_header("Content-Range"));
  4173. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4174. EXPECT_EQ(std::string("abcdefg"), res->body);
  4175. }
  4176. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4177. auto res = cli_.Get("/with-range", {
  4178. {"Range", "bytes=0-"},
  4179. {"Accept-Encoding", ""},
  4180. });
  4181. ASSERT_TRUE(res);
  4182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4183. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4184. EXPECT_EQ(true, res->has_header("Content-Range"));
  4185. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4186. EXPECT_EQ(std::string("abcdefg"), res->body);
  4187. }
  4188. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4189. auto res =
  4190. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(false, res->has_header("Content-Range"));
  4195. EXPECT_EQ(267U, res->body.size());
  4196. // Check that both range contents are present
  4197. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4198. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4199. // Check that Content-Range headers are present for both ranges
  4200. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4201. std::string::npos);
  4202. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4203. std::string::npos);
  4204. }
  4205. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4206. Ranges ranges;
  4207. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4208. ranges.emplace_back(0, -1);
  4209. }
  4210. auto res =
  4211. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4214. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4215. EXPECT_EQ(false, res->has_header("Content-Range"));
  4216. EXPECT_EQ(0U, res->body.size());
  4217. }
  4218. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4219. auto res =
  4220. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4221. ASSERT_TRUE(res);
  4222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4223. EXPECT_EQ(5U, res->body.size());
  4224. // Check that overlapping ranges are coalesced into a single range
  4225. EXPECT_EQ("bcdef", res->body);
  4226. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4227. // Should be single range, not multipart
  4228. EXPECT_TRUE(res->has_header("Content-Range"));
  4229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4230. }
  4231. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4232. auto res =
  4233. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4236. EXPECT_EQ(268U, res->body.size());
  4237. // Check that both range contents are present
  4238. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4239. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4240. // Check that Content-Range headers are present for both ranges
  4241. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4242. std::string::npos);
  4243. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4244. std::string::npos);
  4245. }
  4246. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4247. auto res =
  4248. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4251. EXPECT_EQ(269U, res->body.size());
  4252. // Check that both duplicate range contents are present
  4253. size_t first_abc = res->body.find("abc\r\n");
  4254. EXPECT_TRUE(first_abc != std::string::npos);
  4255. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4256. EXPECT_TRUE(second_abc != std::string::npos);
  4257. // Check that Content-Range headers are present for both ranges
  4258. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4259. EXPECT_TRUE(first_range != std::string::npos);
  4260. size_t second_range =
  4261. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4262. EXPECT_TRUE(second_range != std::string::npos);
  4263. }
  4264. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4265. auto res = cli_.Get("/streamed-with-range?error",
  4266. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4269. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(false, res->has_header("Content-Range"));
  4271. EXPECT_EQ(0U, res->body.size());
  4272. }
  4273. TEST_F(ServerTest, GetStreamedEndless) {
  4274. uint64_t offset = 0;
  4275. auto res = cli_.Get("/streamed-cancel",
  4276. [&](const char * /*data*/, uint64_t data_length) {
  4277. if (offset < 100) {
  4278. offset += data_length;
  4279. return true;
  4280. }
  4281. return false;
  4282. });
  4283. ASSERT_TRUE(!res);
  4284. EXPECT_EQ(Error::Canceled, res.error());
  4285. }
  4286. TEST_F(ServerTest, ClientStop) {
  4287. std::atomic_size_t count{4};
  4288. std::vector<std::thread> threads;
  4289. for (auto i = count.load(); i != 0; --i) {
  4290. threads.emplace_back([&]() {
  4291. auto res = cli_.Get("/streamed-cancel",
  4292. [&](const char *, uint64_t) { return true; });
  4293. --count;
  4294. ASSERT_TRUE(!res);
  4295. EXPECT_TRUE(res.error() == Error::Canceled ||
  4296. res.error() == Error::Read || res.error() == Error::Write);
  4297. });
  4298. }
  4299. std::this_thread::sleep_for(std::chrono::seconds(2));
  4300. while (count != 0) {
  4301. cli_.stop();
  4302. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4303. }
  4304. for (auto &t : threads) {
  4305. t.join();
  4306. }
  4307. }
  4308. TEST_F(ServerTest, GetWithRange1) {
  4309. auto res = cli_.Get("/with-range", {
  4310. make_range_header({{3, 5}}),
  4311. {"Accept-Encoding", ""},
  4312. });
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4315. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4316. EXPECT_EQ(true, res->has_header("Content-Range"));
  4317. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4318. EXPECT_EQ(std::string("def"), res->body);
  4319. }
  4320. TEST_F(ServerTest, GetWithRange2) {
  4321. auto res = cli_.Get("/with-range", {
  4322. make_range_header({{1, -1}}),
  4323. {"Accept-Encoding", ""},
  4324. });
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4327. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4328. EXPECT_EQ(true, res->has_header("Content-Range"));
  4329. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4330. EXPECT_EQ(std::string("bcdefg"), res->body);
  4331. }
  4332. TEST_F(ServerTest, GetWithRange3) {
  4333. auto res = cli_.Get("/with-range", {
  4334. make_range_header({{0, 0}}),
  4335. {"Accept-Encoding", ""},
  4336. });
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4339. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4340. EXPECT_EQ(true, res->has_header("Content-Range"));
  4341. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4342. EXPECT_EQ(std::string("a"), res->body);
  4343. }
  4344. TEST_F(ServerTest, GetWithRange4) {
  4345. auto res = cli_.Get("/with-range", {
  4346. make_range_header({{-1, 2}}),
  4347. {"Accept-Encoding", ""},
  4348. });
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4351. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4352. EXPECT_EQ(true, res->has_header("Content-Range"));
  4353. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4354. EXPECT_EQ(std::string("fg"), res->body);
  4355. }
  4356. TEST_F(ServerTest, GetWithRange5) {
  4357. auto res = cli_.Get("/with-range", {
  4358. make_range_header({{0, 5}}),
  4359. {"Accept-Encoding", ""},
  4360. });
  4361. ASSERT_TRUE(res);
  4362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4363. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4364. EXPECT_EQ(true, res->has_header("Content-Range"));
  4365. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4366. EXPECT_EQ(std::string("abcdef"), res->body);
  4367. }
  4368. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4369. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4370. ASSERT_TRUE(res);
  4371. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4372. }
  4373. TEST_F(ServerTest, GetWithRangeMultipart) {
  4374. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4377. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(false, res->has_header("Content-Range"));
  4379. EXPECT_EQ(267U, res->body.size());
  4380. }
  4381. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4382. auto res =
  4383. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4386. }
  4387. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4388. auto res = cli_.Get("/with-range-customized-response",
  4389. {{make_range_header({{1, 2}})}});
  4390. ASSERT_TRUE(res);
  4391. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4392. EXPECT_EQ(true, res->has_header("Content-Length"));
  4393. EXPECT_EQ(false, res->has_header("Content-Range"));
  4394. EXPECT_EQ(JSON_DATA, res->body);
  4395. }
  4396. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4397. auto res = cli_.Get("/with-range-customized-response",
  4398. {{make_range_header({{1, 2}, {4, 5}})}});
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4401. EXPECT_EQ(true, res->has_header("Content-Length"));
  4402. EXPECT_EQ(false, res->has_header("Content-Range"));
  4403. EXPECT_EQ(JSON_DATA, res->body);
  4404. }
  4405. TEST_F(ServerTest, Issue1772) {
  4406. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4409. }
  4410. TEST_F(ServerTest, Issue609) {
  4411. auto res = cli_.Delete("/issue609");
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::OK_200, res->status);
  4414. EXPECT_EQ(std::string("ok"), res->body);
  4415. }
  4416. TEST_F(ServerTest, GetStreamedChunked) {
  4417. auto res = cli_.Get("/streamed-chunked");
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::OK_200, res->status);
  4420. EXPECT_EQ(std::string("123456789"), res->body);
  4421. }
  4422. TEST_F(ServerTest, GetStreamedChunked2) {
  4423. auto res = cli_.Get("/streamed-chunked2");
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::OK_200, res->status);
  4426. EXPECT_EQ(std::string("123456789"), res->body);
  4427. }
  4428. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4429. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4430. ASSERT_TRUE(res);
  4431. EXPECT_EQ(StatusCode::OK_200, res->status);
  4432. EXPECT_EQ(std::string("123456789"), res->body);
  4433. EXPECT_TRUE(res->has_header("Trailer"));
  4434. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4435. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4436. // Trailers are now stored separately from headers (security fix)
  4437. EXPECT_EQ(2U, res->trailers.size());
  4438. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4439. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4440. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4441. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4442. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4443. // Verify trailers are NOT in headers (security verification)
  4444. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4445. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4446. }
  4447. TEST_F(ServerTest, LargeChunkedPost) {
  4448. Request req;
  4449. req.method = "POST";
  4450. req.path = "/large-chunked";
  4451. std::string host_and_port;
  4452. host_and_port += HOST;
  4453. host_and_port += ":";
  4454. host_and_port += std::to_string(PORT);
  4455. req.headers.emplace("Host", host_and_port.c_str());
  4456. req.headers.emplace("Accept", "*/*");
  4457. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4458. req.headers.emplace("Content-Type", "text/plain");
  4459. req.headers.emplace("Content-Length", "0");
  4460. req.headers.emplace("Transfer-Encoding", "chunked");
  4461. std::string long_string(30 * 1024u, 'a');
  4462. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4463. // Attempt to make a large enough post to exceed OS buffers, to test that
  4464. // the server handles short reads if the full chunk data isn't available.
  4465. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4466. auto res = std::make_shared<Response>();
  4467. auto error = Error::Success;
  4468. auto ret = cli_.send(req, *res, error);
  4469. ASSERT_TRUE(ret);
  4470. EXPECT_EQ(StatusCode::OK_200, res->status);
  4471. }
  4472. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4473. auto res = cli_.Get("/remote_addr");
  4474. ASSERT_TRUE(res);
  4475. EXPECT_EQ(StatusCode::OK_200, res->status);
  4476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4477. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4478. }
  4479. TEST_F(ServerTest, GetMethodLocalAddr) {
  4480. auto res = cli_.Get("/local_addr");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4484. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4485. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4486. }
  4487. TEST_F(ServerTest, HTTPResponseSplitting) {
  4488. auto res = cli_.Get("/http_response_splitting");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. }
  4492. TEST_F(ServerTest, SlowRequest) {
  4493. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4494. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4495. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4496. }
  4497. #if 0
  4498. TEST_F(ServerTest, SlowPost) {
  4499. char buffer[64 * 1024];
  4500. memset(buffer, 0x42, sizeof(buffer));
  4501. auto res = cli_.Post(
  4502. "/slowpost", 64 * 1024 * 1024,
  4503. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4504. auto ret = sink.write(buffer, sizeof(buffer));
  4505. EXPECT_TRUE(ret);
  4506. return true;
  4507. },
  4508. "text/plain");
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. }
  4512. TEST_F(ServerTest, SlowPostFail) {
  4513. char buffer[64 * 1024];
  4514. memset(buffer, 0x42, sizeof(buffer));
  4515. cli_.set_write_timeout(std::chrono::seconds(0));
  4516. auto res = cli_.Post(
  4517. "/slowpost", 64 * 1024 * 1024,
  4518. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4519. sink.write(buffer, sizeof(buffer));
  4520. return true;
  4521. },
  4522. "text/plain");
  4523. ASSERT_TRUE(!res);
  4524. EXPECT_EQ(Error::Write, res.error());
  4525. }
  4526. #endif
  4527. TEST_F(ServerTest, Put) {
  4528. auto res = cli_.Put("/put", "PUT", "text/plain");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("PUT", res->body);
  4532. }
  4533. TEST_F(ServerTest, PutWithContentProvider) {
  4534. auto res = cli_.Put(
  4535. "/put", 3,
  4536. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4537. sink.os << "PUT";
  4538. return true;
  4539. },
  4540. "text/plain");
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(StatusCode::OK_200, res->status);
  4543. EXPECT_EQ("PUT", res->body);
  4544. }
  4545. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4546. auto res = cli_.Post(
  4547. "/post", 42,
  4548. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4549. return false;
  4550. },
  4551. "text/plain");
  4552. ASSERT_TRUE(!res);
  4553. EXPECT_EQ(Error::Canceled, res.error());
  4554. }
  4555. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4556. auto res = cli_.Put(
  4557. "/put",
  4558. [](size_t /*offset*/, DataSink &sink) {
  4559. sink.os << "PUT";
  4560. sink.done();
  4561. return true;
  4562. },
  4563. "text/plain");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ("PUT", res->body);
  4567. }
  4568. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4569. auto res = cli_.Post(
  4570. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4571. "text/plain");
  4572. ASSERT_TRUE(!res);
  4573. EXPECT_EQ(Error::Canceled, res.error());
  4574. }
  4575. TEST_F(ServerTest, PostLoopBack) {
  4576. std::string body;
  4577. auto res = cli_.Post(
  4578. "/post-loopback", 9,
  4579. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4580. EXPECT_EQ(9u, length);
  4581. sink.write("123", 3);
  4582. sink.write("456", 3);
  4583. sink.write("789", 3);
  4584. return true;
  4585. },
  4586. "text/plain",
  4587. [&body](const char *data, size_t data_length) {
  4588. body.append(data, data_length);
  4589. return true;
  4590. });
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("123456789", body);
  4594. }
  4595. TEST_F(ServerTest, PutLoopBack) {
  4596. std::string body;
  4597. auto res = cli_.Put(
  4598. "/put-loopback", 9,
  4599. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4600. EXPECT_EQ(9u, length);
  4601. sink.write("123", 3);
  4602. sink.write("456", 3);
  4603. sink.write("789", 3);
  4604. return true;
  4605. },
  4606. "text/plain",
  4607. [&body](const char *data, size_t data_length) {
  4608. body.append(data, data_length);
  4609. return true;
  4610. });
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(StatusCode::OK_200, res->status);
  4613. EXPECT_EQ("123456789", body);
  4614. }
  4615. TEST_F(ServerTest, PatchLoopBack) {
  4616. std::string body;
  4617. auto res = cli_.Patch(
  4618. "/patch-loopback", 9,
  4619. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4620. EXPECT_EQ(9u, length);
  4621. sink.write("123", 3);
  4622. sink.write("456", 3);
  4623. sink.write("789", 3);
  4624. return true;
  4625. },
  4626. "text/plain",
  4627. [&body](const char *data, size_t data_length) {
  4628. body.append(data, data_length);
  4629. return true;
  4630. });
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("123456789", body);
  4634. }
  4635. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4636. std::string body;
  4637. auto res = cli_.Post(
  4638. "/post-loopback",
  4639. [](size_t /*offset*/, DataSink &sink) {
  4640. sink.write("123", 3);
  4641. sink.write("456", 3);
  4642. sink.write("789", 3);
  4643. sink.done();
  4644. return true;
  4645. },
  4646. "text/plain",
  4647. [&body](const char *data, size_t data_length) {
  4648. body.append(data, data_length);
  4649. return true;
  4650. });
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. EXPECT_EQ("123456789", body);
  4654. }
  4655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4656. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4657. cli_.set_compress(true);
  4658. auto res = cli_.Put(
  4659. "/put", 3,
  4660. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4661. sink.os << "PUT";
  4662. return true;
  4663. },
  4664. "text/plain");
  4665. ASSERT_TRUE(res);
  4666. EXPECT_EQ(StatusCode::OK_200, res->status);
  4667. EXPECT_EQ("PUT", res->body);
  4668. }
  4669. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4670. cli_.set_compress(true);
  4671. auto res = cli_.Post(
  4672. "/post", 42,
  4673. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4674. return false;
  4675. },
  4676. "text/plain");
  4677. ASSERT_TRUE(!res);
  4678. EXPECT_EQ(Error::Canceled, res.error());
  4679. }
  4680. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4681. cli_.set_compress(true);
  4682. auto res = cli_.Put(
  4683. "/put",
  4684. [](size_t /*offset*/, DataSink &sink) {
  4685. sink.os << "PUT";
  4686. sink.done();
  4687. return true;
  4688. },
  4689. "text/plain");
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. EXPECT_EQ("PUT", res->body);
  4693. }
  4694. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4695. cli_.set_compress(true);
  4696. auto res = cli_.Post(
  4697. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4698. "text/plain");
  4699. ASSERT_TRUE(!res);
  4700. EXPECT_EQ(Error::Canceled, res.error());
  4701. }
  4702. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4703. cli_.set_compress(true);
  4704. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4705. ASSERT_TRUE(res);
  4706. EXPECT_EQ(StatusCode::OK_200, res->status);
  4707. EXPECT_EQ(LARGE_DATA, res->body);
  4708. }
  4709. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4710. #ifdef CPPHTTPLIB_SSL_ENABLED
  4711. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4712. Client cli(s.c_str());
  4713. cli.enable_server_certificate_verification(false);
  4714. #else
  4715. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4716. Client cli(s.c_str());
  4717. #endif
  4718. cli.set_compress(true);
  4719. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ(LARGE_DATA, res->body);
  4723. // The compressed size should be less than a 10th of the original. May vary
  4724. // depending on the zlib library.
  4725. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4726. static_cast<uint64_t>(10 * 1024 * 1024));
  4727. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4728. }
  4729. TEST_F(ServerTest, PutContentWithDeflate) {
  4730. cli_.set_compress(false);
  4731. Headers headers;
  4732. headers.emplace("Content-Encoding", "deflate");
  4733. // PUT in deflate format:
  4734. auto res = cli_.Put("/put", headers,
  4735. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. EXPECT_EQ("PUT", res->body);
  4739. }
  4740. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4741. Headers headers;
  4742. headers.emplace("Accept-Encoding", "gzip, deflate");
  4743. auto res = cli_.Get("/streamed-chunked", headers);
  4744. ASSERT_TRUE(res);
  4745. EXPECT_EQ(StatusCode::OK_200, res->status);
  4746. EXPECT_EQ(std::string("123456789"), res->body);
  4747. }
  4748. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4749. Headers headers;
  4750. headers.emplace("Accept-Encoding", "gzip, deflate");
  4751. auto res = cli_.Get("/streamed-chunked2", headers);
  4752. ASSERT_TRUE(res);
  4753. EXPECT_EQ(StatusCode::OK_200, res->status);
  4754. EXPECT_EQ(std::string("123456789"), res->body);
  4755. }
  4756. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4757. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4758. ASSERT_TRUE(res);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. }
  4761. TEST(GzipDecompressor, ChunkedDecompression) {
  4762. std::string data;
  4763. for (size_t i = 0; i < 32 * 1024; ++i) {
  4764. data.push_back(static_cast<char>('a' + i % 26));
  4765. }
  4766. std::string compressed_data;
  4767. {
  4768. httplib::detail::gzip_compressor compressor;
  4769. bool result = compressor.compress(
  4770. data.data(), data.size(),
  4771. /*last=*/true,
  4772. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4773. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4774. compressed_data_size);
  4775. return true;
  4776. });
  4777. ASSERT_TRUE(result);
  4778. }
  4779. std::string decompressed_data;
  4780. {
  4781. httplib::detail::gzip_decompressor decompressor;
  4782. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4783. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4784. size_t chunk_size = 130;
  4785. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4786. chunk_begin += chunk_size) {
  4787. size_t current_chunk_size =
  4788. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4789. bool result = decompressor.decompress(
  4790. compressed_data.data() + chunk_begin, current_chunk_size,
  4791. [&](const char *decompressed_data_chunk,
  4792. size_t decompressed_data_chunk_size) {
  4793. decompressed_data.insert(decompressed_data.size(),
  4794. decompressed_data_chunk,
  4795. decompressed_data_chunk_size);
  4796. return true;
  4797. });
  4798. ASSERT_TRUE(result);
  4799. }
  4800. }
  4801. ASSERT_EQ(data, decompressed_data);
  4802. }
  4803. TEST(GzipDecompressor, DeflateDecompression) {
  4804. std::string original_text = "Raw deflate without gzip";
  4805. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4806. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4807. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4808. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4809. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4810. std::string decompressed_data;
  4811. {
  4812. httplib::detail::gzip_decompressor decompressor;
  4813. bool result = decompressor.decompress(
  4814. compressed_data.data(), compressed_data.size(),
  4815. [&](const char *decompressed_data_chunk,
  4816. size_t decompressed_data_chunk_size) {
  4817. decompressed_data.insert(decompressed_data.size(),
  4818. decompressed_data_chunk,
  4819. decompressed_data_chunk_size);
  4820. return true;
  4821. });
  4822. ASSERT_TRUE(result);
  4823. }
  4824. ASSERT_EQ(original_text, decompressed_data);
  4825. }
  4826. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4827. std::string original_text = "Raw deflate without gzip";
  4828. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4829. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4830. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4831. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4832. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4833. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4834. std::string decompressed_data;
  4835. {
  4836. httplib::detail::gzip_decompressor decompressor;
  4837. bool result = decompressor.decompress(
  4838. compressed_data.data(), compressed_data.size(),
  4839. [&](const char *decompressed_data_chunk,
  4840. size_t decompressed_data_chunk_size) {
  4841. decompressed_data.insert(decompressed_data.size(),
  4842. decompressed_data_chunk,
  4843. decompressed_data_chunk_size);
  4844. return true;
  4845. });
  4846. ASSERT_TRUE(result);
  4847. }
  4848. ASSERT_EQ(original_text, decompressed_data);
  4849. }
  4850. #ifdef _WIN32
  4851. TEST(GzipDecompressor, LargeRandomData) {
  4852. // prepare large random data that is difficult to be compressed and is
  4853. // expected to have large size even when compressed
  4854. std::random_device seed_gen;
  4855. std::mt19937 random(seed_gen());
  4856. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4857. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4858. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4859. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4860. // compress data over 4GiB
  4861. std::string compressed_data;
  4862. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4863. httplib::detail::gzip_compressor compressor;
  4864. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4865. data.size() * sizeof(std::uint32_t), true,
  4866. [&](const char *data, size_t size) {
  4867. compressed_data.insert(
  4868. compressed_data.size(), data, size);
  4869. return true;
  4870. });
  4871. ASSERT_TRUE(result);
  4872. // FIXME: compressed data size is expected to be greater than 4GiB,
  4873. // but there is no guarantee
  4874. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4875. // decompress data over 4GiB
  4876. std::string decompressed_data;
  4877. decompressed_data.reserve(data_size);
  4878. httplib::detail::gzip_decompressor decompressor;
  4879. result = decompressor.decompress(
  4880. compressed_data.data(), compressed_data.size(),
  4881. [&](const char *data, size_t size) {
  4882. decompressed_data.insert(decompressed_data.size(), data, size);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(result);
  4886. // compare
  4887. ASSERT_EQ(data_size, decompressed_data.size());
  4888. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4889. 0);
  4890. }
  4891. #endif
  4892. #endif
  4893. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4894. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4895. Headers headers;
  4896. headers.emplace("Accept-Encoding", "br");
  4897. auto res = cli_.Get("/streamed-chunked", headers);
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ(std::string("123456789"), res->body);
  4901. }
  4902. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4903. Headers headers;
  4904. headers.emplace("Accept-Encoding", "br");
  4905. auto res = cli_.Get("/streamed-chunked2", headers);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ(std::string("123456789"), res->body);
  4909. }
  4910. #endif
  4911. TEST_F(ServerTest, Patch) {
  4912. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4913. ASSERT_TRUE(res);
  4914. EXPECT_EQ(StatusCode::OK_200, res->status);
  4915. EXPECT_EQ("PATCH", res->body);
  4916. }
  4917. TEST_F(ServerTest, Delete) {
  4918. auto res = cli_.Delete("/delete");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("DELETE", res->body);
  4922. }
  4923. TEST_F(ServerTest, DeleteContentReceiver) {
  4924. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4925. ASSERT_TRUE(res);
  4926. EXPECT_EQ(StatusCode::OK_200, res->status);
  4927. EXPECT_EQ("content", res->body);
  4928. }
  4929. TEST_F(ServerTest, Options) {
  4930. auto res = cli_.Options("*");
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4934. EXPECT_TRUE(res->body.empty());
  4935. }
  4936. TEST_F(ServerTest, URL) {
  4937. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4938. ASSERT_TRUE(res);
  4939. EXPECT_EQ(StatusCode::OK_200, res->status);
  4940. }
  4941. TEST_F(ServerTest, ArrayParam) {
  4942. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. }
  4946. TEST_F(ServerTest, NoMultipleHeaders) {
  4947. Headers headers = {{"Content-Length", "5"}};
  4948. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4949. "text/plain");
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ(StatusCode::OK_200, res->status);
  4952. }
  4953. TEST_F(ServerTest, PostContentReceiver) {
  4954. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4955. ASSERT_TRUE(res);
  4956. ASSERT_EQ(StatusCode::OK_200, res->status);
  4957. ASSERT_EQ("content", res->body);
  4958. }
  4959. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4960. UploadFormDataItems items = {
  4961. {"text1", "text default", "", ""},
  4962. {"text2", "aωb", "", ""},
  4963. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4964. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4965. {"file3", "", "", "application/octet-stream"},
  4966. };
  4967. auto res = cli_.Post("/content_receiver", items);
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. }
  4971. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4972. UploadFormDataItems items = {
  4973. {"text1", "text default", "", ""},
  4974. {"text2", "aωb", "", ""},
  4975. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4976. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4977. {"file3", "", "", "application/octet-stream"},
  4978. };
  4979. auto boundary = std::string("+++++");
  4980. std::string body;
  4981. for (const auto &item : items) {
  4982. body += "--" + boundary + "\r\n";
  4983. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4984. if (!item.filename.empty()) {
  4985. body += "; filename=\"" + item.filename + "\"";
  4986. }
  4987. body += "\r\n";
  4988. if (!item.content_type.empty()) {
  4989. body += "Content-Type: " + item.content_type + "\r\n";
  4990. }
  4991. body += "\r\n";
  4992. body += item.content + "\r\n";
  4993. }
  4994. body += "--" + boundary + "--\r\n";
  4995. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4996. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4997. ASSERT_TRUE(res);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. }
  5000. TEST_F(ServerTest, PostContentReceiverGzip) {
  5001. cli_.set_compress(true);
  5002. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5003. ASSERT_TRUE(res);
  5004. ASSERT_EQ(StatusCode::OK_200, res->status);
  5005. ASSERT_EQ("content", res->body);
  5006. }
  5007. TEST_F(ServerTest, PutContentReceiver) {
  5008. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5009. ASSERT_TRUE(res);
  5010. ASSERT_EQ(StatusCode::OK_200, res->status);
  5011. ASSERT_EQ("content", res->body);
  5012. }
  5013. TEST_F(ServerTest, PatchContentReceiver) {
  5014. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5015. ASSERT_TRUE(res);
  5016. ASSERT_EQ(StatusCode::OK_200, res->status);
  5017. ASSERT_EQ("content", res->body);
  5018. }
  5019. template <typename ClientType>
  5020. void TestWithHeadersAndContentReceiver(
  5021. ClientType &cli,
  5022. std::function<Result(ClientType &, const std::string &, const Headers &,
  5023. const std::string &, const std::string &,
  5024. ContentReceiver, DownloadProgress)>
  5025. request_func) {
  5026. Headers headers;
  5027. headers.emplace("X-Custom-Header", "test-value");
  5028. std::string received_body;
  5029. auto res = request_func(
  5030. cli, "/content_receiver", headers, "content", "application/json",
  5031. [&](const char *data, size_t data_length) {
  5032. received_body.append(data, data_length);
  5033. return true;
  5034. },
  5035. nullptr);
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. EXPECT_EQ("content", received_body);
  5039. }
  5040. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5041. #ifdef CPPHTTPLIB_SSL_ENABLED
  5042. using ClientT = SSLClient;
  5043. #else
  5044. using ClientT = Client;
  5045. #endif
  5046. TestWithHeadersAndContentReceiver<ClientT>(
  5047. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5048. const std::string &body, const std::string &content_type,
  5049. ContentReceiver receiver, DownloadProgress progress) {
  5050. return cli.Post(path, headers, body, content_type, receiver, progress);
  5051. });
  5052. }
  5053. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5054. #ifdef CPPHTTPLIB_SSL_ENABLED
  5055. using ClientT = SSLClient;
  5056. #else
  5057. using ClientT = Client;
  5058. #endif
  5059. TestWithHeadersAndContentReceiver<ClientT>(
  5060. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5061. const std::string &body, const std::string &content_type,
  5062. ContentReceiver receiver, DownloadProgress progress) {
  5063. return cli.Put(path, headers, body, content_type, receiver, progress);
  5064. });
  5065. }
  5066. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5067. #ifdef CPPHTTPLIB_SSL_ENABLED
  5068. using ClientT = SSLClient;
  5069. #else
  5070. using ClientT = Client;
  5071. #endif
  5072. TestWithHeadersAndContentReceiver<ClientT>(
  5073. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5074. const std::string &body, const std::string &content_type,
  5075. ContentReceiver receiver, DownloadProgress progress) {
  5076. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5077. });
  5078. }
  5079. template <typename ClientType>
  5080. void TestWithHeadersAndContentReceiverWithProgress(
  5081. ClientType &cli,
  5082. std::function<Result(ClientType &, const std::string &, const Headers &,
  5083. const std::string &, const std::string &,
  5084. ContentReceiver, DownloadProgress)>
  5085. request_func) {
  5086. Headers headers;
  5087. headers.emplace("X-Test-Header", "progress-test");
  5088. std::string received_body;
  5089. auto progress_called = false;
  5090. auto res = request_func(
  5091. cli, "/content_receiver", headers, "content", "text/plain",
  5092. [&](const char *data, size_t data_length) {
  5093. received_body.append(data, data_length);
  5094. return true;
  5095. },
  5096. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5097. progress_called = true;
  5098. return true;
  5099. });
  5100. ASSERT_TRUE(res);
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("content", received_body);
  5103. EXPECT_TRUE(progress_called);
  5104. }
  5105. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5106. #ifdef CPPHTTPLIB_SSL_ENABLED
  5107. using ClientT = SSLClient;
  5108. #else
  5109. using ClientT = Client;
  5110. #endif
  5111. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5112. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5113. const std::string &body, const std::string &content_type,
  5114. ContentReceiver receiver, DownloadProgress progress) {
  5115. return cli.Post(path, headers, body, content_type, receiver, progress);
  5116. });
  5117. }
  5118. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5119. #ifdef CPPHTTPLIB_SSL_ENABLED
  5120. using ClientT = SSLClient;
  5121. #else
  5122. using ClientT = Client;
  5123. #endif
  5124. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5125. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5126. const std::string &body, const std::string &content_type,
  5127. ContentReceiver receiver, DownloadProgress progress) {
  5128. return cli.Put(path, headers, body, content_type, receiver, progress);
  5129. });
  5130. }
  5131. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5132. #ifdef CPPHTTPLIB_SSL_ENABLED
  5133. using ClientT = SSLClient;
  5134. #else
  5135. using ClientT = Client;
  5136. #endif
  5137. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5138. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5139. const std::string &body, const std::string &content_type,
  5140. ContentReceiver receiver, DownloadProgress progress) {
  5141. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5142. });
  5143. }
  5144. template <typename ClientType>
  5145. void TestWithHeadersAndContentReceiverError(
  5146. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5147. const Headers &, const std::string &,
  5148. const std::string &, ContentReceiver)>
  5149. request_func) {
  5150. Headers headers;
  5151. headers.emplace("X-Error-Test", "true");
  5152. std::string received_body;
  5153. auto receiver_failed = false;
  5154. auto res =
  5155. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5156. [&](const char *data, size_t data_length) {
  5157. received_body.append(data, data_length);
  5158. receiver_failed = true;
  5159. return false;
  5160. });
  5161. ASSERT_FALSE(res);
  5162. EXPECT_TRUE(receiver_failed);
  5163. }
  5164. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5165. #ifdef CPPHTTPLIB_SSL_ENABLED
  5166. using ClientT = SSLClient;
  5167. #else
  5168. using ClientT = Client;
  5169. #endif
  5170. TestWithHeadersAndContentReceiverError<ClientT>(
  5171. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5172. const std::string &body, const std::string &content_type,
  5173. ContentReceiver receiver) {
  5174. return cli.Post(path, headers, body, content_type, receiver);
  5175. });
  5176. }
  5177. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5178. #ifdef CPPHTTPLIB_SSL_ENABLED
  5179. using ClientT = SSLClient;
  5180. #else
  5181. using ClientT = Client;
  5182. #endif
  5183. TestWithHeadersAndContentReceiverError<ClientT>(
  5184. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5185. const std::string &body, const std::string &content_type,
  5186. ContentReceiver receiver) {
  5187. return cli.Put(path, headers, body, content_type, receiver);
  5188. });
  5189. }
  5190. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5191. #ifdef CPPHTTPLIB_SSL_ENABLED
  5192. using ClientT = SSLClient;
  5193. #else
  5194. using ClientT = Client;
  5195. #endif
  5196. TestWithHeadersAndContentReceiverError<ClientT>(
  5197. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5198. const std::string &body, const std::string &content_type,
  5199. ContentReceiver receiver) {
  5200. return cli.Patch(path, headers, body, content_type, receiver);
  5201. });
  5202. }
  5203. TEST_F(ServerTest, PostQueryStringAndBody) {
  5204. auto res =
  5205. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5206. ASSERT_TRUE(res);
  5207. ASSERT_EQ(StatusCode::OK_200, res->status);
  5208. }
  5209. TEST_F(ServerTest, HTTP2Magic) {
  5210. Request req;
  5211. req.method = "PRI";
  5212. req.path = "*";
  5213. req.body = "SM";
  5214. auto res = std::make_shared<Response>();
  5215. auto error = Error::Success;
  5216. auto ret = cli_.send(req, *res, error);
  5217. ASSERT_TRUE(ret);
  5218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5219. }
  5220. TEST_F(ServerTest, KeepAlive) {
  5221. auto res = cli_.Get("/hi");
  5222. ASSERT_TRUE(res);
  5223. EXPECT_EQ(StatusCode::OK_200, res->status);
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("Hello World!", res->body);
  5226. res = cli_.Get("/hi");
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("Hello World!", res->body);
  5231. res = cli_.Get("/hi");
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ(StatusCode::OK_200, res->status);
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("Hello World!", res->body);
  5236. res = cli_.Get("/not-exist");
  5237. ASSERT_TRUE(res);
  5238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5239. res = cli_.Post("/empty", "", "text/plain");
  5240. ASSERT_TRUE(res);
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5243. EXPECT_EQ("empty", res->body);
  5244. EXPECT_EQ("close", res->get_header_value("Connection"));
  5245. res = cli_.Post(
  5246. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5247. "text/plain");
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5251. EXPECT_EQ("empty", res->body);
  5252. cli_.set_keep_alive(false);
  5253. res = cli_.Get("/last-request");
  5254. ASSERT_TRUE(res);
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("close", res->get_header_value("Connection"));
  5257. }
  5258. TEST_F(ServerTest, TooManyRedirect) {
  5259. cli_.set_follow_location(true);
  5260. auto res = cli_.Get("/redirect/0");
  5261. ASSERT_TRUE(!res);
  5262. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5263. }
  5264. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5265. Request req;
  5266. req.method = "FOOBAR";
  5267. req.path = "/hi";
  5268. cli_.set_keep_alive(true);
  5269. auto res = cli_.send(req);
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5272. EXPECT_EQ("close", res->get_header_value("Connection"));
  5273. EXPECT_FALSE(cli_.is_socket_open());
  5274. }
  5275. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5276. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5277. TEST_F(ServerTest, Gzip) {
  5278. Headers headers;
  5279. headers.emplace("Accept-Encoding", "gzip, deflate");
  5280. auto res = cli_.Get("/compress", headers);
  5281. ASSERT_TRUE(res);
  5282. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5285. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5286. "7890123456789012345678901234567890",
  5287. res->body);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. }
  5290. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5291. Headers headers;
  5292. headers.emplace("Accept-Encoding", "");
  5293. auto res = cli_.Get("/compress", headers);
  5294. ASSERT_TRUE(res);
  5295. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5299. "7890123456789012345678901234567890",
  5300. res->body);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. }
  5303. TEST_F(ServerTest, GzipWithContentReceiver) {
  5304. Headers headers;
  5305. headers.emplace("Accept-Encoding", "gzip, deflate");
  5306. std::string body;
  5307. auto res = cli_.Get("/compress", headers,
  5308. [&](const char *data, uint64_t data_length) {
  5309. EXPECT_EQ(100U, data_length);
  5310. body.append(data, data_length);
  5311. return true;
  5312. });
  5313. ASSERT_TRUE(res);
  5314. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5317. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5318. "7890123456789012345678901234567890",
  5319. body);
  5320. EXPECT_EQ(StatusCode::OK_200, res->status);
  5321. }
  5322. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5323. Headers headers;
  5324. headers.emplace("Accept-Encoding", "gzip, deflate");
  5325. cli_.set_decompress(false);
  5326. auto res = cli_.Get("/compress", headers);
  5327. ASSERT_TRUE(res);
  5328. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5330. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5331. EXPECT_EQ(33U, res->body.size());
  5332. EXPECT_EQ(StatusCode::OK_200, res->status);
  5333. }
  5334. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5335. Headers headers;
  5336. headers.emplace("Accept-Encoding", "");
  5337. std::string body;
  5338. auto res = cli_.Get("/compress", headers,
  5339. [&](const char *data, uint64_t data_length) {
  5340. EXPECT_EQ(100U, data_length);
  5341. body.append(data, data_length);
  5342. return true;
  5343. });
  5344. ASSERT_TRUE(res);
  5345. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5347. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5348. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5349. "7890123456789012345678901234567890",
  5350. body);
  5351. EXPECT_EQ(StatusCode::OK_200, res->status);
  5352. }
  5353. TEST_F(ServerTest, NoGzip) {
  5354. Headers headers;
  5355. headers.emplace("Accept-Encoding", "gzip, deflate");
  5356. auto res = cli_.Get("/nocompress", headers);
  5357. ASSERT_TRUE(res);
  5358. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5359. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5360. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5362. "7890123456789012345678901234567890",
  5363. res->body);
  5364. EXPECT_EQ(StatusCode::OK_200, res->status);
  5365. }
  5366. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5367. Headers headers;
  5368. headers.emplace("Accept-Encoding", "gzip, deflate");
  5369. std::string body;
  5370. auto res = cli_.Get("/nocompress", headers,
  5371. [&](const char *data, uint64_t data_length) {
  5372. EXPECT_EQ(100U, data_length);
  5373. body.append(data, data_length);
  5374. return true;
  5375. });
  5376. ASSERT_TRUE(res);
  5377. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5378. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5380. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5381. "7890123456789012345678901234567890",
  5382. body);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. }
  5385. TEST_F(ServerTest, MultipartFormDataGzip) {
  5386. UploadFormDataItems items = {
  5387. {"key1", "test", "", ""},
  5388. {"key2", "--abcdefg123", "", ""},
  5389. };
  5390. cli_.set_compress(true);
  5391. auto res = cli_.Post("/compress-multipart", items);
  5392. ASSERT_TRUE(res);
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. }
  5395. #endif
  5396. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5397. TEST_F(ServerTest, Brotli) {
  5398. Headers headers;
  5399. headers.emplace("Accept-Encoding", "br");
  5400. auto res = cli_.Get("/compress", headers);
  5401. ASSERT_TRUE(res);
  5402. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5403. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5404. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5405. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5406. "7890123456789012345678901234567890",
  5407. res->body);
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. }
  5410. #endif
  5411. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5412. TEST_F(ServerTest, Zstd) {
  5413. Headers headers;
  5414. headers.emplace("Accept-Encoding", "zstd");
  5415. auto res = cli_.Get("/compress", headers);
  5416. ASSERT_TRUE(res);
  5417. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5421. "7890123456789012345678901234567890",
  5422. res->body);
  5423. EXPECT_EQ(StatusCode::OK_200, res->status);
  5424. }
  5425. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5426. Headers headers;
  5427. headers.emplace("Accept-Encoding", "");
  5428. auto res = cli_.Get("/compress", headers);
  5429. ASSERT_TRUE(res);
  5430. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5432. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5433. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5434. "7890123456789012345678901234567890",
  5435. res->body);
  5436. EXPECT_EQ(StatusCode::OK_200, res->status);
  5437. }
  5438. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5439. Headers headers;
  5440. headers.emplace("Accept-Encoding", "zstd");
  5441. std::string body;
  5442. auto res = cli_.Get("/compress", headers,
  5443. [&](const char *data, uint64_t data_length) {
  5444. EXPECT_EQ(100U, data_length);
  5445. body.append(data, data_length);
  5446. return true;
  5447. });
  5448. ASSERT_TRUE(res);
  5449. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5451. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5453. "7890123456789012345678901234567890",
  5454. body);
  5455. EXPECT_EQ(StatusCode::OK_200, res->status);
  5456. }
  5457. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5458. Headers headers;
  5459. headers.emplace("Accept-Encoding", "zstd");
  5460. cli_.set_decompress(false);
  5461. auto res = cli_.Get("/compress", headers);
  5462. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5463. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5464. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5465. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5466. ASSERT_TRUE(res);
  5467. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5469. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5470. EXPECT_EQ(StatusCode::OK_200, res->status);
  5471. ASSERT_EQ(26U, res->body.size());
  5472. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5473. 0);
  5474. }
  5475. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5476. Headers headers;
  5477. headers.emplace("Accept-Encoding", "");
  5478. std::string body;
  5479. auto res = cli_.Get("/compress", headers,
  5480. [&](const char *data, uint64_t data_length) {
  5481. EXPECT_EQ(100U, data_length);
  5482. body.append(data, data_length);
  5483. return true;
  5484. });
  5485. ASSERT_TRUE(res);
  5486. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5490. "7890123456789012345678901234567890",
  5491. body);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. }
  5494. TEST_F(ServerTest, NoZstd) {
  5495. Headers headers;
  5496. headers.emplace("Accept-Encoding", "zstd");
  5497. auto res = cli_.Get("/nocompress", headers);
  5498. ASSERT_TRUE(res);
  5499. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5500. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5501. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5503. "7890123456789012345678901234567890",
  5504. res->body);
  5505. EXPECT_EQ(StatusCode::OK_200, res->status);
  5506. }
  5507. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5508. Headers headers;
  5509. headers.emplace("Accept-Encoding", "zstd");
  5510. std::string body;
  5511. auto res = cli_.Get("/nocompress", headers,
  5512. [&](const char *data, uint64_t data_length) {
  5513. EXPECT_EQ(100U, data_length);
  5514. body.append(data, data_length);
  5515. return true;
  5516. });
  5517. ASSERT_TRUE(res);
  5518. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5519. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5520. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5521. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5522. "7890123456789012345678901234567890",
  5523. body);
  5524. EXPECT_EQ(StatusCode::OK_200, res->status);
  5525. }
  5526. // TODO: How to enable zstd ??
  5527. TEST_F(ServerTest, MultipartFormDataZstd) {
  5528. UploadFormDataItems items = {
  5529. {"key1", "test", "", ""},
  5530. {"key2", "--abcdefg123", "", ""},
  5531. };
  5532. Headers headers;
  5533. headers.emplace("Accept-Encoding", "zstd");
  5534. cli_.set_compress(true);
  5535. auto res = cli_.Post("/compress-multipart", headers, items);
  5536. ASSERT_TRUE(res);
  5537. EXPECT_EQ(StatusCode::OK_200, res->status);
  5538. }
  5539. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5540. Headers headers;
  5541. headers.emplace("Accept-Encoding", "zstd");
  5542. cli_.set_compress(true);
  5543. auto res = cli_.Put(
  5544. "/put", headers, 3,
  5545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5546. sink.os << "PUT";
  5547. return true;
  5548. },
  5549. "text/plain");
  5550. ASSERT_TRUE(res);
  5551. EXPECT_EQ(StatusCode::OK_200, res->status);
  5552. EXPECT_EQ("PUT", res->body);
  5553. }
  5554. // Pre-compression logging tests
  5555. TEST_F(ServerTest, PreCompressionLogging) {
  5556. // Test data for compression (matches the actual /compress endpoint content)
  5557. const std::string test_content =
  5558. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5559. "3456789012345678901234567890";
  5560. // Variables to capture logging data
  5561. std::string pre_compression_body;
  5562. std::string pre_compression_content_type;
  5563. std::string pre_compression_content_encoding;
  5564. std::string post_compression_body;
  5565. std::string post_compression_content_type;
  5566. std::string post_compression_content_encoding;
  5567. // Set up pre-compression logger
  5568. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5569. const Response &res) {
  5570. pre_compression_body = res.body;
  5571. pre_compression_content_type = res.get_header_value("Content-Type");
  5572. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5573. });
  5574. // Set up post-compression logger
  5575. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5576. post_compression_body = res.body;
  5577. post_compression_content_type = res.get_header_value("Content-Type");
  5578. post_compression_content_encoding =
  5579. res.get_header_value("Content-Encoding");
  5580. });
  5581. // Test with gzip compression
  5582. Headers headers;
  5583. headers.emplace("Accept-Encoding", "gzip");
  5584. auto res = cli_.Get("/compress", headers);
  5585. // Verify response was compressed
  5586. ASSERT_TRUE(res);
  5587. EXPECT_EQ(StatusCode::OK_200, res->status);
  5588. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5589. // Verify pre-compression logger captured uncompressed content
  5590. EXPECT_EQ(test_content, pre_compression_body);
  5591. EXPECT_EQ("text/plain", pre_compression_content_type);
  5592. EXPECT_TRUE(pre_compression_content_encoding
  5593. .empty()); // No encoding header before compression
  5594. // Verify post-compression logger captured compressed content
  5595. EXPECT_NE(test_content,
  5596. post_compression_body); // Should be different after compression
  5597. EXPECT_EQ("text/plain", post_compression_content_type);
  5598. EXPECT_EQ("gzip", post_compression_content_encoding);
  5599. // Verify compressed content is smaller
  5600. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5601. }
  5602. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5603. const std::string test_content =
  5604. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5605. "3456789012345678901234567890";
  5606. std::string pre_compression_body;
  5607. std::string post_compression_body;
  5608. svr_.set_pre_compression_logger(
  5609. [&](const Request & /*req*/, const Response &res) {
  5610. pre_compression_body = res.body;
  5611. });
  5612. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5613. post_compression_body = res.body;
  5614. });
  5615. Headers headers;
  5616. headers.emplace("Accept-Encoding", "br");
  5617. auto res = cli_.Get("/compress", headers);
  5618. ASSERT_TRUE(res);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5621. // Verify pre-compression content is uncompressed
  5622. EXPECT_EQ(test_content, pre_compression_body);
  5623. // Verify post-compression content is compressed
  5624. EXPECT_NE(test_content, post_compression_body);
  5625. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5626. }
  5627. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5628. const std::string test_content =
  5629. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5630. "3456789012345678901234567890";
  5631. std::string pre_compression_body;
  5632. std::string post_compression_body;
  5633. svr_.set_pre_compression_logger(
  5634. [&](const Request & /*req*/, const Response &res) {
  5635. pre_compression_body = res.body;
  5636. });
  5637. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5638. post_compression_body = res.body;
  5639. });
  5640. // Request without compression (use /nocompress endpoint)
  5641. Headers headers;
  5642. auto res = cli_.Get("/nocompress", headers);
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ(StatusCode::OK_200, res->status);
  5645. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5646. // Pre-compression logger should not be called when no compression is applied
  5647. EXPECT_TRUE(
  5648. pre_compression_body.empty()); // Pre-compression logger not called
  5649. EXPECT_EQ(
  5650. test_content,
  5651. post_compression_body); // Post-compression logger captures final content
  5652. }
  5653. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5654. const std::string test_content =
  5655. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5656. "3456789012345678901234567890";
  5657. std::string pre_compression_body;
  5658. bool pre_logger_called = false;
  5659. // Set only pre-compression logger
  5660. svr_.set_pre_compression_logger(
  5661. [&](const Request & /*req*/, const Response &res) {
  5662. pre_compression_body = res.body;
  5663. pre_logger_called = true;
  5664. });
  5665. Headers headers;
  5666. headers.emplace("Accept-Encoding", "gzip");
  5667. auto res = cli_.Get("/compress", headers);
  5668. ASSERT_TRUE(res);
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5671. // Verify pre-compression logger was called
  5672. EXPECT_TRUE(pre_logger_called);
  5673. EXPECT_EQ(test_content, pre_compression_body);
  5674. }
  5675. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5676. {
  5677. // Test with Expect: 100-continue header - success case
  5678. // Server returns 100 Continue, client sends body, server returns 200 OK
  5679. Request req;
  5680. req.method = "POST";
  5681. req.path = "/post-large";
  5682. req.set_header("Expect", "100-continue");
  5683. req.body = LARGE_DATA;
  5684. Response res;
  5685. auto error = Error::Success;
  5686. cli_.set_keep_alive(true);
  5687. auto ret = cli_.send(req, res, error);
  5688. EXPECT_TRUE(ret);
  5689. EXPECT_EQ(StatusCode::OK_200, res.status);
  5690. EXPECT_EQ(LARGE_DATA, res.body);
  5691. }
  5692. {
  5693. // Test with Expect: 100-continue header - error case
  5694. // Client should not send the body when server returns an error
  5695. Request req;
  5696. req.method = "POST";
  5697. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5698. req.set_header("Expect", "100-continue");
  5699. req.body = LARGE_DATA;
  5700. Response res;
  5701. auto error = Error::Success;
  5702. auto start = std::chrono::high_resolution_clock::now();
  5703. cli_.set_keep_alive(true);
  5704. auto ret = cli_.send(req, res, error);
  5705. auto end = std::chrono::high_resolution_clock::now();
  5706. auto elapsed =
  5707. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5708. .count();
  5709. // With Expect: 100-continue, request completes successfully but with error
  5710. EXPECT_TRUE(ret);
  5711. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5712. EXPECT_EQ("close", res.get_header_value("Connection"));
  5713. EXPECT_FALSE(cli_.is_socket_open());
  5714. EXPECT_LE(elapsed, 200);
  5715. }
  5716. {
  5717. // Send an extra GET request to ensure error recovery without hanging
  5718. Request req;
  5719. req.method = "GET";
  5720. req.path = "/hi";
  5721. auto start = std::chrono::high_resolution_clock::now();
  5722. auto res = cli_.send(req);
  5723. auto end = std::chrono::high_resolution_clock::now();
  5724. auto elapsed =
  5725. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5726. .count();
  5727. ASSERT_TRUE(res);
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("Hello World!", res->body);
  5730. EXPECT_LE(elapsed, 500);
  5731. }
  5732. }
  5733. TEST(ZstdDecompressor, ChunkedDecompression) {
  5734. std::string data;
  5735. for (size_t i = 0; i < 32 * 1024; ++i) {
  5736. data.push_back(static_cast<char>('a' + i % 26));
  5737. }
  5738. std::string compressed_data;
  5739. {
  5740. httplib::detail::zstd_compressor compressor;
  5741. bool result = compressor.compress(
  5742. data.data(), data.size(),
  5743. /*last=*/true,
  5744. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5745. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5746. compressed_data_size);
  5747. return true;
  5748. });
  5749. ASSERT_TRUE(result);
  5750. }
  5751. std::string decompressed_data;
  5752. {
  5753. httplib::detail::zstd_decompressor decompressor;
  5754. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5755. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5756. size_t chunk_size = 130;
  5757. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5758. chunk_begin += chunk_size) {
  5759. size_t current_chunk_size =
  5760. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5761. bool result = decompressor.decompress(
  5762. compressed_data.data() + chunk_begin, current_chunk_size,
  5763. [&](const char *decompressed_data_chunk,
  5764. size_t decompressed_data_chunk_size) {
  5765. decompressed_data.insert(decompressed_data.size(),
  5766. decompressed_data_chunk,
  5767. decompressed_data_chunk_size);
  5768. return true;
  5769. });
  5770. ASSERT_TRUE(result);
  5771. }
  5772. }
  5773. ASSERT_EQ(data, decompressed_data);
  5774. }
  5775. TEST(ZstdDecompressor, Decompress) {
  5776. std::string original_text = "Compressed with ZSTD";
  5777. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5778. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5779. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5780. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5781. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5782. std::string decompressed_data;
  5783. {
  5784. httplib::detail::zstd_decompressor decompressor;
  5785. bool result = decompressor.decompress(
  5786. compressed_data.data(), compressed_data.size(),
  5787. [&](const char *decompressed_data_chunk,
  5788. size_t decompressed_data_chunk_size) {
  5789. decompressed_data.insert(decompressed_data.size(),
  5790. decompressed_data_chunk,
  5791. decompressed_data_chunk_size);
  5792. return true;
  5793. });
  5794. ASSERT_TRUE(result);
  5795. }
  5796. ASSERT_EQ(original_text, decompressed_data);
  5797. }
  5798. #endif
  5799. // Sends a raw request to a server listening at HOST:PORT.
  5800. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5801. std::string *resp = nullptr) {
  5802. auto error = Error::Success;
  5803. auto client_sock = detail::create_client_socket(
  5804. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5805. /*connection_timeout_sec=*/5, 0,
  5806. /*read_timeout_sec=*/5, 0,
  5807. /*write_timeout_sec=*/5, 0, std::string(), error);
  5808. if (client_sock == INVALID_SOCKET) { return false; }
  5809. auto ret = detail::process_client_socket(
  5810. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5811. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5812. if (req.size() !=
  5813. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5814. return false;
  5815. }
  5816. char buf[512];
  5817. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5818. while (line_reader.getline()) {
  5819. if (resp) { *resp += line_reader.ptr(); }
  5820. }
  5821. return true;
  5822. });
  5823. detail::close_socket(client_sock);
  5824. return ret;
  5825. }
  5826. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5827. Server svr;
  5828. std::string header_value;
  5829. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5830. header_value = req.get_header_value("foo");
  5831. res.set_content("ok", "text/plain");
  5832. });
  5833. thread t = thread([&] { svr.listen(HOST, PORT); });
  5834. auto se = detail::scope_exit([&] {
  5835. svr.stop();
  5836. t.join();
  5837. ASSERT_FALSE(svr.is_running());
  5838. });
  5839. svr.wait_until_ready();
  5840. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5841. // like characters are not treated the same - use vertical tab and escape.
  5842. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5843. "foo: \t \v bar \x1B\t \r\n"
  5844. "Connection: close\r\n"
  5845. "\r\n";
  5846. std::string res;
  5847. ASSERT_TRUE(send_request(5, req, &res));
  5848. EXPECT_EQ(header_value, "");
  5849. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5850. }
  5851. // Sends a raw request and verifies that there isn't a crash or exception.
  5852. static void test_raw_request(const std::string &req,
  5853. std::string *out = nullptr) {
  5854. Server svr;
  5855. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5856. res.set_content("ok", "text/plain");
  5857. });
  5858. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5859. res.set_content("ok", "text/plain");
  5860. });
  5861. svr.Get("/header_field_value_check",
  5862. [&](const Request & /*req*/, Response &res) {
  5863. res.set_content("ok", "text/plain");
  5864. });
  5865. // Server read timeout must be longer than the client read timeout for the
  5866. // bug to reproduce, probably to force the server to process a request
  5867. // without a trailing blank line.
  5868. const time_t client_read_timeout_sec = 1;
  5869. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5870. bool listen_thread_ok = false;
  5871. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5872. auto se = detail::scope_exit([&] {
  5873. svr.stop();
  5874. t.join();
  5875. ASSERT_FALSE(svr.is_running());
  5876. EXPECT_TRUE(listen_thread_ok);
  5877. });
  5878. svr.wait_until_ready();
  5879. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5880. }
  5881. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5882. // A certain header line causes an exception if the header property is parsed
  5883. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5884. test_raw_request(
  5885. "GET /hi HTTP/1.1\r\n"
  5886. " : "
  5887. " "
  5888. " ");
  5889. }
  5890. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5891. // A certain header line causes an exception if the header property *name* is
  5892. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5893. // greedy matcher and requires backtracking when there are a lot of ":"
  5894. // characters.
  5895. // This occurs with libc++ but not libstdc++.
  5896. test_raw_request(
  5897. "GET /hi HTTP/1.1\r\n"
  5898. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5899. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5900. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5901. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5902. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5903. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5904. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5905. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5906. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5907. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5908. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5909. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5910. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5911. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5912. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5913. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5914. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5915. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5916. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5917. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5918. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5919. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5920. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5921. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5922. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5923. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5924. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5925. "&&&%%%");
  5926. }
  5927. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5928. // Make sure this doesn't crash the server.
  5929. // In a previous version of the header line regex, the "\r" rendered the line
  5930. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5931. // a new position where the leading white space ended and the field value
  5932. // began.
  5933. // The crash occurs with libc++ but not libstdc++.
  5934. test_raw_request("GET /hi HTTP/1.1\r\n"
  5935. "a:" +
  5936. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5937. "\r\n"
  5938. "\r\n");
  5939. }
  5940. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5941. std::string out;
  5942. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5943. "Content-Type: text/plain\r\n"
  5944. "Transfer-Encoding: chunked\r\n"
  5945. "\r\n"
  5946. "nothex\r\n",
  5947. &out);
  5948. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5949. }
  5950. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5951. std::string out;
  5952. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5953. "Content-Type: text/plain\r\n"
  5954. "Transfer-Encoding: chunked\r\n"
  5955. "\r\n"
  5956. "3\r\n"
  5957. "xyz\r\n"
  5958. "NaN\r\n",
  5959. &out);
  5960. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5961. }
  5962. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5963. std::string out;
  5964. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5965. "Content-Type: text/plain\r\n"
  5966. "Transfer-Encoding: chunked\r\n"
  5967. "\r\n"
  5968. // Length is too large for 64 bits.
  5969. "1ffffffffffffffff\r\n"
  5970. "xyz\r\n",
  5971. &out);
  5972. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5973. }
  5974. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5975. test_raw_request("GET /hi HTTP/1.1\r\n"
  5976. "Content-Type: text/plain\r\n\r");
  5977. }
  5978. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5979. std::string out;
  5980. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5981. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5982. }
  5983. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5984. Server svr;
  5985. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5986. EXPECT_TRUE(!req.remote_addr.empty());
  5987. });
  5988. thread t = thread([&] { svr.listen(HOST, PORT); });
  5989. auto se = detail::scope_exit([&] {
  5990. svr.stop();
  5991. t.join();
  5992. ASSERT_FALSE(svr.is_running());
  5993. });
  5994. svr.wait_until_ready();
  5995. // Send an invalid request line to trigger Bad Request
  5996. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5997. std::string out;
  5998. ASSERT_TRUE(send_request(5, bad_req, &out));
  5999. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6000. }
  6001. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6002. std::string out;
  6003. std::string request(
  6004. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6005. test_raw_request(request, &out);
  6006. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6007. }
  6008. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6009. std::string out;
  6010. std::string request(
  6011. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6012. test_raw_request(request, &out);
  6013. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6014. }
  6015. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6016. std::string out;
  6017. std::string request(
  6018. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6019. test_raw_request(request, &out);
  6020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6021. }
  6022. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6023. std::string out;
  6024. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6025. "Test: \r\n\r\n",
  6026. &out);
  6027. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6028. }
  6029. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6030. Server svr;
  6031. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6032. res.set_header("Cache-Control", "no-cache");
  6033. res.set_chunked_content_provider(
  6034. "text/event-stream", [](size_t offset, DataSink &sink) {
  6035. std::string s = "data:";
  6036. s += std::to_string(offset);
  6037. s += "\n\n";
  6038. auto ret = sink.write(s.data(), s.size());
  6039. EXPECT_TRUE(ret);
  6040. std::this_thread::sleep_for(std::chrono::seconds(1));
  6041. return true;
  6042. });
  6043. });
  6044. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6045. svr.wait_until_ready();
  6046. Client client(HOST, PORT);
  6047. const Headers headers = {{"Accept", "text/event-stream"}};
  6048. auto get_thread = std::thread([&client, &headers]() {
  6049. auto res = client.Get(
  6050. "/events", headers,
  6051. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6052. });
  6053. auto se = detail::scope_exit([&] {
  6054. svr.stop();
  6055. get_thread.join();
  6056. listen_thread.join();
  6057. ASSERT_FALSE(svr.is_running());
  6058. });
  6059. // Give GET time to get a few messages.
  6060. std::this_thread::sleep_for(std::chrono::seconds(2));
  6061. }
  6062. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6063. httplib::Server svr;
  6064. svr.Post("/hi",
  6065. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6066. res.status = StatusCode::OK_200;
  6067. });
  6068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6069. svr.wait_until_ready();
  6070. Client cli(HOST, PORT);
  6071. auto res = cli.Post("/hi", "data", "text/plain");
  6072. ASSERT_TRUE(res);
  6073. EXPECT_EQ(StatusCode::OK_200, res->status);
  6074. svr.stop();
  6075. thread.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. res = cli.Post("/hi", "data", "text/plain");
  6078. ASSERT_FALSE(res);
  6079. }
  6080. TEST(ServerStopTest, ListenFailure) {
  6081. Server svr;
  6082. auto t = thread([&]() {
  6083. auto ret = svr.listen("????", PORT);
  6084. EXPECT_FALSE(ret);
  6085. });
  6086. svr.wait_until_ready();
  6087. svr.stop();
  6088. t.join();
  6089. }
  6090. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6091. TEST(ServerStopTest, Decommision) {
  6092. Server svr;
  6093. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6094. for (int i = 0; i < 4; i++) {
  6095. auto is_even = !(i % 2);
  6096. std::thread t{[&] {
  6097. try {
  6098. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6099. if (is_even) {
  6100. throw std::runtime_error("Some thing that happens to go wrong.");
  6101. }
  6102. svr.listen(HOST, PORT);
  6103. } catch (...) { svr.decommission(); }
  6104. }};
  6105. svr.wait_until_ready();
  6106. // Server is up
  6107. {
  6108. Client cli(HOST, PORT);
  6109. auto res = cli.Get("/hi");
  6110. if (is_even) {
  6111. EXPECT_FALSE(res);
  6112. } else {
  6113. EXPECT_TRUE(res);
  6114. EXPECT_EQ("hi...", res->body);
  6115. }
  6116. }
  6117. svr.stop();
  6118. t.join();
  6119. // Server is down...
  6120. {
  6121. Client cli(HOST, PORT);
  6122. auto res = cli.Get("/hi");
  6123. EXPECT_FALSE(res);
  6124. }
  6125. }
  6126. }
  6127. #endif
  6128. // Helper function for string body upload progress tests
  6129. template <typename SetupHandler, typename ClientCall>
  6130. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6131. ClientCall &&client_call,
  6132. const string &body) {
  6133. Server svr;
  6134. setup_handler(svr);
  6135. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. t.join();
  6139. });
  6140. svr.wait_until_ready();
  6141. Client cli(HOST, PORT);
  6142. vector<uint64_t> progress_values;
  6143. bool progress_called = false;
  6144. auto res =
  6145. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. progress_called = true;
  6148. return true;
  6149. });
  6150. ASSERT_TRUE(res);
  6151. EXPECT_EQ(200, res->status);
  6152. EXPECT_TRUE(progress_called);
  6153. }
  6154. TEST(UploadProgressTest, PostStringBodyBasic) {
  6155. TestStringBodyUploadProgress(
  6156. [](Server &svr) {
  6157. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6158. res.set_content("received", "text/plain");
  6159. });
  6160. },
  6161. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6162. return cli.Post("/test", body, "text/plain", progress_callback);
  6163. },
  6164. "test data for upload progress");
  6165. }
  6166. TEST(UploadProgressTest, PutStringBodyBasic) {
  6167. TestStringBodyUploadProgress(
  6168. [](Server &svr) {
  6169. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6170. res.set_content("put received", "text/plain");
  6171. });
  6172. },
  6173. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6174. return cli.Put("/test", body, "text/plain", progress_callback);
  6175. },
  6176. "put test data for upload progress");
  6177. }
  6178. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6179. TestStringBodyUploadProgress(
  6180. [](Server &svr) {
  6181. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6182. res.set_content("patch received", "text/plain");
  6183. });
  6184. },
  6185. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6186. return cli.Patch("/test", body, "text/plain", progress_callback);
  6187. },
  6188. "patch test data for upload progress");
  6189. }
  6190. // Helper function for content provider upload progress tests
  6191. template <typename SetupHandler, typename ClientCall>
  6192. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6193. ClientCall &&client_call) {
  6194. Server svr;
  6195. setup_handler(svr);
  6196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6197. auto se = detail::scope_exit([&] {
  6198. svr.stop();
  6199. t.join();
  6200. });
  6201. svr.wait_until_ready();
  6202. Client cli(HOST, PORT);
  6203. vector<uint64_t> progress_values;
  6204. auto res =
  6205. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6206. progress_values.push_back(current);
  6207. return true;
  6208. });
  6209. ASSERT_TRUE(res);
  6210. EXPECT_EQ(200, res->status);
  6211. EXPECT_FALSE(progress_values.empty());
  6212. }
  6213. TEST(UploadProgressTest, PostContentProviderProgress) {
  6214. TestContentProviderUploadProgress(
  6215. [](Server &svr) {
  6216. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6217. res.set_content("provider received", "text/plain");
  6218. });
  6219. },
  6220. [](Client &cli, UploadProgress progress_callback) {
  6221. return cli.Post(
  6222. "/test", 10,
  6223. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6224. sink.os << "test data";
  6225. return true;
  6226. },
  6227. "text/plain", progress_callback);
  6228. });
  6229. }
  6230. // Helper function for multipart upload progress tests
  6231. template <typename SetupHandler, typename ClientCall>
  6232. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6233. ClientCall &&client_call,
  6234. const string &endpoint) {
  6235. Server svr;
  6236. setup_handler(svr);
  6237. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. t.join();
  6241. });
  6242. svr.wait_until_ready();
  6243. Client cli(HOST, PORT);
  6244. vector<uint64_t> progress_values;
  6245. UploadFormDataItems items = {
  6246. {"field1", "value1", "", ""},
  6247. {"field2", "longer value for progress tracking test", "", ""},
  6248. {"file1", "file content data for upload progress", "test.txt",
  6249. "text/plain"}};
  6250. auto res = client_call(cli, endpoint, items,
  6251. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6252. progress_values.push_back(current);
  6253. return true;
  6254. });
  6255. ASSERT_TRUE(res);
  6256. EXPECT_EQ(200, res->status);
  6257. EXPECT_FALSE(progress_values.empty());
  6258. }
  6259. TEST(UploadProgressTest, PostMultipartProgress) {
  6260. TestMultipartUploadProgress(
  6261. [](Server &svr) {
  6262. svr.Post("/multipart", [](const Request &req, Response &res) {
  6263. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6264. res.set_content("multipart received", "text/plain");
  6265. });
  6266. },
  6267. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6268. UploadProgress progress_callback) {
  6269. return cli.Post(endpoint, items, progress_callback);
  6270. },
  6271. "/multipart");
  6272. }
  6273. // Helper function for basic download progress tests
  6274. template <typename SetupHandler, typename ClientCall>
  6275. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6276. ClientCall &&client_call, const string &endpoint,
  6277. size_t expected_content_size) {
  6278. Server svr;
  6279. setup_handler(svr);
  6280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6281. auto se = detail::scope_exit([&] {
  6282. svr.stop();
  6283. t.join();
  6284. });
  6285. svr.wait_until_ready();
  6286. Client cli(HOST, PORT);
  6287. vector<uint64_t> progress_values;
  6288. auto res = client_call(cli, endpoint,
  6289. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6290. progress_values.push_back(current);
  6291. return true;
  6292. });
  6293. ASSERT_TRUE(res);
  6294. EXPECT_EQ(200, res->status);
  6295. EXPECT_FALSE(progress_values.empty());
  6296. EXPECT_EQ(expected_content_size, res->body.size());
  6297. }
  6298. TEST(DownloadProgressTest, GetBasic) {
  6299. TestBasicDownloadProgress(
  6300. [](Server &svr) {
  6301. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6302. string content(1000, 'D');
  6303. res.set_content(content, "text/plain");
  6304. });
  6305. },
  6306. [](Client &cli, const string &endpoint,
  6307. DownloadProgress progress_callback) {
  6308. return cli.Get(endpoint, progress_callback);
  6309. },
  6310. "/download", 1000u);
  6311. }
  6312. // Helper function for content receiver download progress tests
  6313. template <typename SetupHandler, typename ClientCall>
  6314. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6315. ClientCall &&client_call,
  6316. const string &endpoint,
  6317. size_t expected_content_size) {
  6318. Server svr;
  6319. setup_handler(svr);
  6320. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6321. auto se = detail::scope_exit([&] {
  6322. svr.stop();
  6323. t.join();
  6324. });
  6325. svr.wait_until_ready();
  6326. Client cli(HOST, PORT);
  6327. vector<uint64_t> progress_values;
  6328. string received_body;
  6329. auto res = client_call(
  6330. cli, endpoint,
  6331. [&](const char *data, size_t data_length) -> bool {
  6332. received_body.append(data, data_length);
  6333. return true;
  6334. },
  6335. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6336. progress_values.push_back(current);
  6337. return true;
  6338. });
  6339. ASSERT_TRUE(res);
  6340. EXPECT_EQ(200, res->status);
  6341. EXPECT_FALSE(progress_values.empty());
  6342. EXPECT_EQ(expected_content_size, received_body.size());
  6343. EXPECT_TRUE(res->body.empty());
  6344. }
  6345. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6346. TestContentReceiverDownloadProgress(
  6347. [](Server &svr) {
  6348. svr.Get("/download-receiver",
  6349. [](const Request & /*req*/, Response &res) {
  6350. string content(2000, 'R');
  6351. res.set_content(content, "text/plain");
  6352. });
  6353. },
  6354. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6355. DownloadProgress progress_callback) {
  6356. return cli.Get(endpoint, content_receiver, progress_callback);
  6357. },
  6358. "/download-receiver", 2000u);
  6359. }
  6360. TEST(StreamingTest, NoContentLengthStreaming) {
  6361. Server svr;
  6362. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6363. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6364. if (offset < 6) {
  6365. sink.os << (offset < 3 ? "a" : "b");
  6366. } else {
  6367. sink.done();
  6368. }
  6369. return true;
  6370. });
  6371. });
  6372. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6373. auto listen_se = detail::scope_exit([&] {
  6374. svr.stop();
  6375. listen_thread.join();
  6376. ASSERT_FALSE(svr.is_running());
  6377. });
  6378. svr.wait_until_ready();
  6379. Client client(HOST, PORT);
  6380. auto get_thread = std::thread([&client]() {
  6381. std::string s;
  6382. auto res =
  6383. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6384. s += std::string(data, len);
  6385. return true;
  6386. });
  6387. ASSERT_TRUE(res);
  6388. EXPECT_EQ(StatusCode::OK_200, res->status);
  6389. EXPECT_EQ("aaabbb", s);
  6390. });
  6391. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6392. // Give GET time to get a few messages.
  6393. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6394. }
  6395. TEST(MountTest, Unmount) {
  6396. Server svr;
  6397. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6398. auto se = detail::scope_exit([&] {
  6399. svr.stop();
  6400. listen_thread.join();
  6401. ASSERT_FALSE(svr.is_running());
  6402. });
  6403. svr.wait_until_ready();
  6404. Client cli("localhost", PORT);
  6405. svr.set_mount_point("/mount2", "./www2");
  6406. auto res = cli.Get("/");
  6407. ASSERT_TRUE(res);
  6408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6409. res = cli.Get("/mount2/dir/test.html");
  6410. ASSERT_TRUE(res);
  6411. EXPECT_EQ(StatusCode::OK_200, res->status);
  6412. svr.set_mount_point("/", "./www");
  6413. res = cli.Get("/dir/");
  6414. ASSERT_TRUE(res);
  6415. EXPECT_EQ(StatusCode::OK_200, res->status);
  6416. svr.remove_mount_point("/");
  6417. res = cli.Get("/dir/");
  6418. ASSERT_TRUE(res);
  6419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6420. svr.remove_mount_point("/mount2");
  6421. res = cli.Get("/mount2/dir/test.html");
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6424. }
  6425. TEST(MountTest, Redicect) {
  6426. Server svr;
  6427. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6428. auto se = detail::scope_exit([&] {
  6429. svr.stop();
  6430. listen_thread.join();
  6431. ASSERT_FALSE(svr.is_running());
  6432. });
  6433. svr.set_mount_point("/", "./www");
  6434. svr.wait_until_ready();
  6435. Client cli("localhost", PORT);
  6436. auto res = cli.Get("/dir/");
  6437. ASSERT_TRUE(res);
  6438. EXPECT_EQ(StatusCode::OK_200, res->status);
  6439. res = cli.Get("/dir");
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6442. res = cli.Get("/file");
  6443. ASSERT_TRUE(res);
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. res = cli.Get("/file/");
  6446. ASSERT_TRUE(res);
  6447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6448. cli.set_follow_location(true);
  6449. res = cli.Get("/dir");
  6450. ASSERT_TRUE(res);
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. }
  6453. TEST(MountTest, MultibytesPathName) {
  6454. Server svr;
  6455. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.set_mount_point("/", "./www");
  6462. svr.wait_until_ready();
  6463. Client cli("localhost", PORT);
  6464. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6465. ASSERT_TRUE(res);
  6466. EXPECT_EQ(StatusCode::OK_200, res->status);
  6467. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6468. }
  6469. TEST(KeepAliveTest, ReadTimeout) {
  6470. Server svr;
  6471. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6472. std::this_thread::sleep_for(std::chrono::seconds(2));
  6473. res.set_content("a", "text/plain");
  6474. });
  6475. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6476. res.set_content("b", "text/plain");
  6477. });
  6478. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6479. auto se = detail::scope_exit([&] {
  6480. svr.stop();
  6481. listen_thread.join();
  6482. ASSERT_FALSE(svr.is_running());
  6483. });
  6484. svr.wait_until_ready();
  6485. Client cli("localhost", PORT);
  6486. cli.set_keep_alive(true);
  6487. cli.set_read_timeout(std::chrono::seconds(1));
  6488. auto resa = cli.Get("/a");
  6489. ASSERT_FALSE(resa);
  6490. EXPECT_EQ(Error::Read, resa.error());
  6491. auto resb = cli.Get("/b");
  6492. ASSERT_TRUE(resb);
  6493. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6494. EXPECT_EQ("b", resb->body);
  6495. }
  6496. TEST(KeepAliveTest, MaxCount) {
  6497. size_t keep_alive_max_count = 3;
  6498. Server svr;
  6499. svr.set_keep_alive_max_count(keep_alive_max_count);
  6500. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6501. res.set_content("Hello World!", "text/plain");
  6502. });
  6503. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6504. auto se = detail::scope_exit([&] {
  6505. svr.stop();
  6506. listen_thread.join();
  6507. ASSERT_FALSE(svr.is_running());
  6508. });
  6509. svr.wait_until_ready();
  6510. Client cli(HOST, PORT);
  6511. cli.set_keep_alive(true);
  6512. for (size_t i = 0; i < 5; i++) {
  6513. auto result = cli.Get("/hi");
  6514. ASSERT_TRUE(result);
  6515. EXPECT_EQ(StatusCode::OK_200, result->status);
  6516. if (i == keep_alive_max_count - 1) {
  6517. EXPECT_EQ("close", result->get_header_value("Connection"));
  6518. } else {
  6519. EXPECT_FALSE(result->has_header("Connection"));
  6520. }
  6521. }
  6522. }
  6523. TEST(KeepAliveTest, Issue1041) {
  6524. Server svr;
  6525. svr.set_keep_alive_timeout(3);
  6526. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6527. res.set_content("Hello World!", "text/plain");
  6528. });
  6529. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6530. auto se = detail::scope_exit([&] {
  6531. svr.stop();
  6532. listen_thread.join();
  6533. ASSERT_FALSE(svr.is_running());
  6534. });
  6535. svr.wait_until_ready();
  6536. Client cli(HOST, PORT);
  6537. cli.set_keep_alive(true);
  6538. auto result = cli.Get("/hi");
  6539. ASSERT_TRUE(result);
  6540. EXPECT_EQ(StatusCode::OK_200, result->status);
  6541. std::this_thread::sleep_for(std::chrono::seconds(5));
  6542. result = cli.Get("/hi");
  6543. ASSERT_TRUE(result);
  6544. EXPECT_EQ(StatusCode::OK_200, result->status);
  6545. }
  6546. TEST(KeepAliveTest, Issue1959) {
  6547. Server svr;
  6548. svr.set_keep_alive_timeout(5);
  6549. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6550. res.set_content("a", "text/plain");
  6551. });
  6552. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6553. auto se = detail::scope_exit([&] {
  6554. if (!svr.is_running()) return;
  6555. svr.stop();
  6556. listen_thread.join();
  6557. ASSERT_FALSE(svr.is_running());
  6558. });
  6559. svr.wait_until_ready();
  6560. Client cli("localhost", PORT);
  6561. cli.set_keep_alive(true);
  6562. using namespace std::chrono;
  6563. auto start = steady_clock::now();
  6564. cli.Get("/a");
  6565. svr.stop();
  6566. listen_thread.join();
  6567. auto end = steady_clock::now();
  6568. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6569. EXPECT_LT(elapsed, 5000);
  6570. }
  6571. #ifdef CPPHTTPLIB_SSL_ENABLED
  6572. TEST(KeepAliveTest, SSLClientReconnection) {
  6573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6574. ASSERT_TRUE(svr.is_valid());
  6575. svr.set_keep_alive_timeout(1);
  6576. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6577. res.set_content("Hello World!", "text/plain");
  6578. });
  6579. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6580. auto se = detail::scope_exit([&] {
  6581. svr.stop();
  6582. listen_thread.join();
  6583. ASSERT_FALSE(svr.is_running());
  6584. });
  6585. svr.wait_until_ready();
  6586. SSLClient cli(HOST, PORT);
  6587. cli.enable_server_certificate_verification(false);
  6588. cli.set_keep_alive(true);
  6589. auto result = cli.Get("/hi");
  6590. ASSERT_TRUE(result);
  6591. EXPECT_EQ(StatusCode::OK_200, result->status);
  6592. result = cli.Get("/hi");
  6593. ASSERT_TRUE(result);
  6594. EXPECT_EQ(StatusCode::OK_200, result->status);
  6595. std::this_thread::sleep_for(std::chrono::seconds(2));
  6596. // Recoonect
  6597. result = cli.Get("/hi");
  6598. ASSERT_TRUE(result);
  6599. EXPECT_EQ(StatusCode::OK_200, result->status);
  6600. result = cli.Get("/hi");
  6601. ASSERT_TRUE(result);
  6602. EXPECT_EQ(StatusCode::OK_200, result->status);
  6603. }
  6604. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6606. ASSERT_TRUE(svr.is_valid());
  6607. svr.set_keep_alive_timeout(1);
  6608. std::string content = "reconnect";
  6609. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6610. res.set_content("Hello World!", "text/plain");
  6611. });
  6612. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6613. auto se = detail::scope_exit([&] {
  6614. svr.stop();
  6615. listen_thread.join();
  6616. ASSERT_FALSE(svr.is_running());
  6617. });
  6618. svr.wait_until_ready();
  6619. SSLClient cli(HOST, PORT);
  6620. cli.enable_server_certificate_verification(false);
  6621. cli.set_keep_alive(true);
  6622. auto result = cli.Post(
  6623. "/hi", content.size(),
  6624. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6625. sink.write(content.c_str(), content.size());
  6626. return true;
  6627. },
  6628. "text/plain");
  6629. ASSERT_TRUE(result);
  6630. EXPECT_EQ(200, result->status);
  6631. std::this_thread::sleep_for(std::chrono::seconds(2));
  6632. // Recoonect
  6633. result = cli.Post(
  6634. "/hi", content.size(),
  6635. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6636. sink.write(content.c_str(), content.size());
  6637. return true;
  6638. },
  6639. "text/plain");
  6640. ASSERT_TRUE(result);
  6641. EXPECT_EQ(200, result->status);
  6642. result = cli.Post(
  6643. "/hi", content.size(),
  6644. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6645. sink.write(content.c_str(), content.size());
  6646. return true;
  6647. },
  6648. "text/plain");
  6649. ASSERT_TRUE(result);
  6650. EXPECT_EQ(200, result->status);
  6651. }
  6652. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6653. using namespace httplib::tls;
  6654. {
  6655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6656. ASSERT_TRUE(svr.is_valid());
  6657. svr.Get("/sni", [&](const Request &req, Response &res) {
  6658. std::string expected = req.sni();
  6659. EXPECT_EQ(expected, req.get_param_value("expected"));
  6660. res.set_content("ok", "text/plain");
  6661. });
  6662. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6663. auto se = detail::scope_exit([&] {
  6664. svr.stop();
  6665. listen_thread.join();
  6666. ASSERT_FALSE(svr.is_running());
  6667. });
  6668. svr.wait_until_ready();
  6669. {
  6670. SSLClient cli("localhost", PORT);
  6671. cli.enable_server_certificate_verification(false);
  6672. auto res = cli.Get("/sni?expected=localhost");
  6673. ASSERT_TRUE(res);
  6674. }
  6675. {
  6676. SSLClient cli("::1", PORT);
  6677. cli.enable_server_certificate_verification(false);
  6678. auto res = cli.Get("/sni?expected=");
  6679. // NOTE: This may fail if the server is listening on IPv4 only
  6680. // (e.g., when localhost resolves to 127.0.0.1 only)
  6681. if (res) {
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. } else {
  6684. EXPECT_EQ(Error::Connection, res.error());
  6685. }
  6686. }
  6687. }
  6688. }
  6689. #endif
  6690. TEST(ClientProblemDetectionTest, ContentProvider) {
  6691. Server svr;
  6692. size_t content_length = 1024 * 1024;
  6693. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6694. res.set_content_provider(
  6695. content_length, "text/plain",
  6696. [&](size_t offset, size_t length, DataSink &sink) {
  6697. auto out_len = std::min(length, static_cast<size_t>(1024));
  6698. std::string out(out_len, '@');
  6699. sink.write(out.data(), out_len);
  6700. return offset < 4096;
  6701. },
  6702. [](bool success) { ASSERT_FALSE(success); });
  6703. });
  6704. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6705. res.set_content_provider(
  6706. 0, "text/plain",
  6707. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6708. EXPECT_TRUE(false);
  6709. return true;
  6710. },
  6711. [](bool success) { ASSERT_FALSE(success); });
  6712. });
  6713. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6714. auto se = detail::scope_exit([&] {
  6715. svr.stop();
  6716. listen_thread.join();
  6717. ASSERT_FALSE(svr.is_running());
  6718. });
  6719. svr.wait_until_ready();
  6720. Client cli("localhost", PORT);
  6721. {
  6722. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6723. size_t /*data_length*/) { return false; });
  6724. ASSERT_FALSE(res);
  6725. }
  6726. {
  6727. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6728. size_t /*data_length*/) { return false; });
  6729. ASSERT_TRUE(res);
  6730. }
  6731. }
  6732. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6733. Server svr;
  6734. svr.set_error_handler([](Request const &, Response &res) -> void {
  6735. res.set_chunked_content_provider(
  6736. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6737. sink.os << "hello";
  6738. sink.os << "world";
  6739. sink.done();
  6740. return true;
  6741. });
  6742. });
  6743. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6744. auto se = detail::scope_exit([&] {
  6745. svr.stop();
  6746. listen_thread.join();
  6747. ASSERT_FALSE(svr.is_running());
  6748. });
  6749. svr.wait_until_ready();
  6750. Client cli("localhost", PORT);
  6751. auto res = cli.Get("/");
  6752. ASSERT_TRUE(res);
  6753. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6754. EXPECT_EQ("helloworld", res->body);
  6755. }
  6756. TEST(LongPollingTest, ClientCloseDetection) {
  6757. Server svr;
  6758. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6759. res.set_chunked_content_provider(
  6760. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6761. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6762. sink.os << "hello";
  6763. auto count = 10;
  6764. while (count > 0 && sink.is_writable()) {
  6765. this_thread::sleep_for(chrono::milliseconds(10));
  6766. count--;
  6767. }
  6768. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6769. return true;
  6770. });
  6771. });
  6772. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6773. auto se = detail::scope_exit([&] {
  6774. svr.stop();
  6775. listen_thread.join();
  6776. ASSERT_FALSE(svr.is_running());
  6777. });
  6778. svr.wait_until_ready();
  6779. Client cli("localhost", PORT);
  6780. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6781. EXPECT_EQ("hello", string(data, data_length));
  6782. return false; // close the socket immediately.
  6783. });
  6784. ASSERT_FALSE(res);
  6785. }
  6786. TEST(GetWithParametersTest, GetWithParameters) {
  6787. Server svr;
  6788. svr.Get("/", [&](const Request &req, Response &) {
  6789. EXPECT_EQ("world", req.get_param_value("hello"));
  6790. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6791. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6792. });
  6793. svr.Get("/params", [&](const Request &req, Response &) {
  6794. EXPECT_EQ("world", req.get_param_value("hello"));
  6795. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6796. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6797. });
  6798. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6799. EXPECT_EQ("resource-id", req.matches[1]);
  6800. EXPECT_EQ("foo", req.get_param_value("param1"));
  6801. EXPECT_EQ("bar", req.get_param_value("param2"));
  6802. });
  6803. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6804. EXPECT_EQ("user-id", req.path_params.at("id"));
  6805. EXPECT_EQ("foo", req.get_param_value("param1"));
  6806. EXPECT_EQ("bar", req.get_param_value("param2"));
  6807. });
  6808. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6809. auto se = detail::scope_exit([&] {
  6810. svr.stop();
  6811. listen_thread.join();
  6812. ASSERT_FALSE(svr.is_running());
  6813. });
  6814. svr.wait_until_ready();
  6815. {
  6816. Client cli(HOST, PORT);
  6817. Params params;
  6818. params.emplace("hello", "world");
  6819. params.emplace("hello2", "world2");
  6820. params.emplace("hello3", "world3");
  6821. auto res = cli.Get("/", params, Headers{});
  6822. ASSERT_TRUE(res);
  6823. EXPECT_EQ(StatusCode::OK_200, res->status);
  6824. }
  6825. {
  6826. Client cli(HOST, PORT);
  6827. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6828. ASSERT_TRUE(res);
  6829. EXPECT_EQ(StatusCode::OK_200, res->status);
  6830. }
  6831. {
  6832. Client cli(HOST, PORT);
  6833. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6834. ASSERT_TRUE(res);
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. }
  6837. {
  6838. Client cli(HOST, PORT);
  6839. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6840. ASSERT_TRUE(res);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. }
  6844. TEST(GetWithParametersTest, GetWithParameters2) {
  6845. Server svr;
  6846. svr.Get("/", [&](const Request &req, Response &res) {
  6847. auto text = req.get_param_value("hello");
  6848. res.set_content(text, "text/plain");
  6849. });
  6850. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6851. auto se = detail::scope_exit([&] {
  6852. svr.stop();
  6853. listen_thread.join();
  6854. ASSERT_FALSE(svr.is_running());
  6855. });
  6856. svr.wait_until_ready();
  6857. Client cli("localhost", PORT);
  6858. Params params;
  6859. params.emplace("hello", "world");
  6860. std::string body;
  6861. auto res = cli.Get("/", params, Headers{},
  6862. [&](const char *data, size_t data_length) {
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("world", body);
  6869. }
  6870. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6871. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6872. auto host = "httpcan.org";
  6873. auto path = std::string{"/range/32"};
  6874. #else
  6875. auto host = "nghttp2.org";
  6876. auto path = std::string{"/httpbin/range/32"};
  6877. #endif
  6878. #ifdef CPPHTTPLIB_SSL_ENABLED
  6879. SSLClient cli(host);
  6880. #else
  6881. Client cli(host);
  6882. #endif
  6883. cli.set_default_headers({make_range_header({{1, 10}})});
  6884. cli.set_connection_timeout(5);
  6885. {
  6886. auto res = cli.Get(path);
  6887. ASSERT_TRUE(res);
  6888. EXPECT_EQ("bcdefghijk", res->body);
  6889. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6890. }
  6891. {
  6892. auto res = cli.Get(path);
  6893. ASSERT_TRUE(res);
  6894. EXPECT_EQ("bcdefghijk", res->body);
  6895. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6896. }
  6897. }
  6898. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6899. Server svr;
  6900. svr.set_default_headers({{"Hello", "World"}});
  6901. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6902. res.set_content("ok", "text/plain");
  6903. });
  6904. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6905. auto se = detail::scope_exit([&] {
  6906. svr.stop();
  6907. listen_thread.join();
  6908. ASSERT_FALSE(svr.is_running());
  6909. });
  6910. svr.wait_until_ready();
  6911. Client cli("localhost", PORT);
  6912. auto res = cli.Get("/");
  6913. ASSERT_TRUE(res);
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. EXPECT_EQ("ok", res->body);
  6916. EXPECT_EQ("World", res->get_header_value("Hello"));
  6917. }
  6918. #ifdef CPPHTTPLIB_SSL_ENABLED
  6919. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6921. ASSERT_TRUE(svr.is_valid());
  6922. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6923. std::this_thread::sleep_for(std::chrono::seconds(2));
  6924. res.set_content("a", "text/plain");
  6925. });
  6926. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6927. res.set_content("b", "text/plain");
  6928. });
  6929. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6930. auto se = detail::scope_exit([&] {
  6931. svr.stop();
  6932. listen_thread.join();
  6933. ASSERT_FALSE(svr.is_running());
  6934. });
  6935. svr.wait_until_ready();
  6936. SSLClient cli("localhost", PORT);
  6937. cli.enable_server_certificate_verification(false);
  6938. cli.set_keep_alive(true);
  6939. cli.set_read_timeout(std::chrono::seconds(1));
  6940. auto resa = cli.Get("/a");
  6941. ASSERT_TRUE(!resa);
  6942. EXPECT_EQ(Error::Read, resa.error());
  6943. auto resb = cli.Get("/b");
  6944. ASSERT_TRUE(resb);
  6945. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6946. EXPECT_EQ("b", resb->body);
  6947. }
  6948. #endif
  6949. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6950. protected:
  6951. ServerTestWithAI_PASSIVE()
  6952. : cli_(HOST, PORT)
  6953. #ifdef CPPHTTPLIB_SSL_ENABLED
  6954. ,
  6955. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6956. #endif
  6957. {
  6958. #ifdef CPPHTTPLIB_SSL_ENABLED
  6959. cli_.enable_server_certificate_verification(false);
  6960. #endif
  6961. }
  6962. virtual void SetUp() {
  6963. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6964. res.set_content("Hello World!", "text/plain");
  6965. });
  6966. t_ = thread(
  6967. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6968. svr_.wait_until_ready();
  6969. }
  6970. virtual void TearDown() {
  6971. svr_.stop();
  6972. t_.join();
  6973. }
  6974. #ifdef CPPHTTPLIB_SSL_ENABLED
  6975. SSLClient cli_;
  6976. SSLServer svr_;
  6977. #else
  6978. Client cli_;
  6979. Server svr_;
  6980. #endif
  6981. thread t_;
  6982. };
  6983. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6984. auto res = cli_.Get("/hi");
  6985. ASSERT_TRUE(res);
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6988. EXPECT_EQ("Hello World!", res->body);
  6989. }
  6990. class ServerUpDownTest : public ::testing::Test {
  6991. protected:
  6992. ServerUpDownTest() : cli_(HOST, PORT) {}
  6993. virtual void SetUp() {
  6994. t_ = thread([&]() {
  6995. svr_.bind_to_any_port(HOST);
  6996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6997. ASSERT_TRUE(svr_.listen_after_bind());
  6998. });
  6999. svr_.wait_until_ready();
  7000. }
  7001. virtual void TearDown() {
  7002. svr_.stop();
  7003. t_.join();
  7004. }
  7005. Client cli_;
  7006. Server svr_;
  7007. thread t_;
  7008. };
  7009. TEST_F(ServerUpDownTest, QuickStartStop) {
  7010. // Should not crash, especially when run with
  7011. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7012. }
  7013. class PayloadMaxLengthTest : public ::testing::Test {
  7014. protected:
  7015. PayloadMaxLengthTest()
  7016. : cli_(HOST, PORT)
  7017. #ifdef CPPHTTPLIB_SSL_ENABLED
  7018. ,
  7019. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7020. #endif
  7021. {
  7022. #ifdef CPPHTTPLIB_SSL_ENABLED
  7023. cli_.enable_server_certificate_verification(false);
  7024. #endif
  7025. }
  7026. virtual void SetUp() {
  7027. svr_.set_payload_max_length(8);
  7028. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7029. res.set_content("test", "text/plain");
  7030. });
  7031. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7032. svr_.wait_until_ready();
  7033. }
  7034. virtual void TearDown() {
  7035. svr_.stop();
  7036. t_.join();
  7037. }
  7038. #ifdef CPPHTTPLIB_SSL_ENABLED
  7039. SSLClient cli_;
  7040. SSLServer svr_;
  7041. #else
  7042. Client cli_;
  7043. Server svr_;
  7044. #endif
  7045. thread t_;
  7046. };
  7047. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7048. auto res = cli_.Post("/test", "123456789", "text/plain");
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7051. res = cli_.Post("/test", "12345678", "text/plain");
  7052. ASSERT_TRUE(res);
  7053. EXPECT_EQ(StatusCode::OK_200, res->status);
  7054. }
  7055. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7056. // Test chunked encoding with payload exceeding the 8-byte limit
  7057. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7058. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7059. ASSERT_TRUE(res);
  7060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7061. }
  7062. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7063. // Test chunked encoding with payload within the 8-byte limit
  7064. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7065. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7066. ASSERT_TRUE(res);
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. }
  7069. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7070. // Test using send_request to send chunked data exceeding payload limit
  7071. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7072. "Host: " +
  7073. std::string(HOST) + ":" + std::to_string(PORT) +
  7074. "\r\n"
  7075. "Transfer-Encoding: chunked\r\n"
  7076. "Connection: close\r\n"
  7077. "\r\n"
  7078. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7079. "0123456789\r\n"
  7080. "0\r\n" // End chunk
  7081. "\r\n";
  7082. std::string response;
  7083. bool result = send_request(1, chunked_request, &response);
  7084. if (!result) {
  7085. // If send_request fails, it might be because the server closed the
  7086. // connection due to payload limit enforcement, which is acceptable
  7087. SUCCEED()
  7088. << "Server rejected oversized chunked request (connection closed)";
  7089. } else {
  7090. // If we got a response, check if it's an error response or connection was
  7091. // closed early Short response length indicates connection was closed due to
  7092. // payload limit
  7093. if (response.length() <= 10) {
  7094. SUCCEED() << "Server closed connection for oversized chunked request";
  7095. } else {
  7096. // Check for error status codes
  7097. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7098. response.find("Payload Too Large") != std::string::npos ||
  7099. response.find("400") != std::string::npos);
  7100. }
  7101. }
  7102. }
  7103. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7104. // Test request without Content-Length header exceeding payload limit
  7105. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7106. "Host: " +
  7107. std::string(HOST) + ":" +
  7108. std::to_string(PORT) +
  7109. "\r\n"
  7110. "Connection: close\r\n"
  7111. "\r\n";
  7112. // Add payload exceeding the 8-byte limit
  7113. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7114. request_without_content_length += large_payload;
  7115. std::string response;
  7116. bool result = send_request(1, request_without_content_length, &response);
  7117. if (!result) {
  7118. // If send_request fails, server likely closed connection due to payload
  7119. // limit
  7120. SUCCEED() << "Server rejected oversized request without Content-Length "
  7121. "(connection closed)";
  7122. } else {
  7123. // Check if server responded with error or closed connection early
  7124. if (response.length() <= 10) {
  7125. SUCCEED() << "Server closed connection for oversized request without "
  7126. "Content-Length";
  7127. } else {
  7128. // Check for error status codes
  7129. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7130. response.find("Payload Too Large") != std::string::npos ||
  7131. response.find("400") != std::string::npos);
  7132. }
  7133. }
  7134. }
  7135. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7136. // Test request without Content-Length header within payload limit
  7137. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7138. "Host: " +
  7139. std::string(HOST) + ":" +
  7140. std::to_string(PORT) +
  7141. "\r\n"
  7142. "Connection: close\r\n"
  7143. "\r\n";
  7144. // Add payload within the 8-byte limit
  7145. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7146. request_without_content_length += small_payload;
  7147. std::string response;
  7148. bool result = send_request(1, request_without_content_length, &response);
  7149. // For requests without Content-Length, the server may have different behavior
  7150. // The key is that it should not reject due to payload limit for small
  7151. // payloads
  7152. if (result) {
  7153. // Check for any HTTP response (success or error, but not connection closed)
  7154. if (response.length() > 10) {
  7155. SUCCEED()
  7156. << "Server processed request without Content-Length within limit";
  7157. } else {
  7158. // Short response might indicate connection closed, which is acceptable
  7159. SUCCEED() << "Server closed connection for request without "
  7160. "Content-Length (acceptable behavior)";
  7161. }
  7162. } else {
  7163. // Connection failure might be due to protocol requirements
  7164. SUCCEED() << "Connection issue with request without Content-Length "
  7165. "(environment-specific)";
  7166. }
  7167. }
  7168. class LargePayloadMaxLengthTest : public ::testing::Test {
  7169. protected:
  7170. LargePayloadMaxLengthTest()
  7171. : cli_(HOST, PORT)
  7172. #ifdef CPPHTTPLIB_SSL_ENABLED
  7173. ,
  7174. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7175. #endif
  7176. {
  7177. #ifdef CPPHTTPLIB_SSL_ENABLED
  7178. cli_.enable_server_certificate_verification(false);
  7179. #endif
  7180. }
  7181. virtual void SetUp() {
  7182. // Set 10MB payload limit
  7183. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7184. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7185. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7186. res.set_content("Large payload test", "text/plain");
  7187. });
  7188. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7189. svr_.wait_until_ready();
  7190. }
  7191. virtual void TearDown() {
  7192. svr_.stop();
  7193. t_.join();
  7194. }
  7195. #ifdef CPPHTTPLIB_SSL_ENABLED
  7196. SSLClient cli_;
  7197. SSLServer svr_;
  7198. #else
  7199. Client cli_;
  7200. Server svr_;
  7201. #endif
  7202. thread t_;
  7203. };
  7204. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7205. // Test chunked encoding with payload within 10MB limit
  7206. std::string medium_payload(5 * 1024 * 1024,
  7207. 'A'); // 5MB payload, within 10MB limit
  7208. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7209. ASSERT_TRUE(res);
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. }
  7212. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7213. // Test chunked encoding with payload exceeding 10MB limit
  7214. std::string large_payload(12 * 1024 * 1024,
  7215. 'B'); // 12MB payload, exceeds 10MB limit
  7216. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7217. // Server may either return 413 or close the connection
  7218. if (res) {
  7219. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7220. } else {
  7221. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7222. }
  7223. }
  7224. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7225. // Test request without Content-Length header within 10MB limit
  7226. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7227. "Host: " +
  7228. std::string(HOST) + ":" +
  7229. std::to_string(PORT) +
  7230. "\r\n"
  7231. "Connection: close\r\n"
  7232. "\r\n";
  7233. // Add 1MB payload (within 10MB limit)
  7234. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7235. request_without_content_length += medium_payload;
  7236. std::string response;
  7237. bool result = send_request(5, request_without_content_length, &response);
  7238. if (result) {
  7239. // Should get a proper HTTP response for payloads within limit
  7240. if (response.length() > 10) {
  7241. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7242. "10MB limit";
  7243. } else {
  7244. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7245. "Content-Length)";
  7246. }
  7247. } else {
  7248. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7249. }
  7250. }
  7251. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7252. // Test request without Content-Length header exceeding 10MB limit
  7253. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7254. "Host: " +
  7255. std::string(HOST) + ":" +
  7256. std::to_string(PORT) +
  7257. "\r\n"
  7258. "Connection: close\r\n"
  7259. "\r\n";
  7260. // Add 12MB payload (exceeds 10MB limit)
  7261. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7262. request_without_content_length += large_payload;
  7263. std::string response;
  7264. bool result = send_request(10, request_without_content_length, &response);
  7265. if (!result) {
  7266. // Server should close connection due to payload limit
  7267. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7268. "(connection closed)";
  7269. } else {
  7270. // Check for error response
  7271. if (response.length() <= 10) {
  7272. SUCCEED()
  7273. << "Server closed connection for 12MB request exceeding 10MB limit";
  7274. } else {
  7275. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7276. response.find("Payload Too Large") != std::string::npos ||
  7277. response.find("400") != std::string::npos);
  7278. }
  7279. }
  7280. }
  7281. // Regression test for DoS vulnerability: a malicious server sending a response
  7282. // without Content-Length header must not cause unbounded memory consumption on
  7283. // the client side. The client should stop reading after a reasonable limit,
  7284. // similar to the server-side set_payload_max_length protection.
  7285. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7286. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7287. #ifndef _WIN32
  7288. signal(SIGPIPE, SIG_IGN);
  7289. #endif
  7290. auto server_thread = std::thread([] {
  7291. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7292. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7293. default_socket_options(srv);
  7294. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7295. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7296. sockaddr_in addr{};
  7297. addr.sin_family = AF_INET;
  7298. addr.sin_port = htons(PORT + 2);
  7299. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7300. int opt = 1;
  7301. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7302. #ifdef _WIN32
  7303. reinterpret_cast<const char *>(&opt),
  7304. #else
  7305. &opt,
  7306. #endif
  7307. sizeof(opt));
  7308. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7309. ::listen(srv, 1);
  7310. sockaddr_in cli_addr{};
  7311. socklen_t cli_len = sizeof(cli_addr);
  7312. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7313. if (cli != INVALID_SOCKET) {
  7314. char buf[4096];
  7315. ::recv(cli, buf, sizeof(buf), 0);
  7316. // Malicious response: no Content-Length, no chunked encoding
  7317. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7318. "Connection: close\r\n"
  7319. "\r\n";
  7320. ::send(cli,
  7321. #ifdef _WIN32
  7322. static_cast<const char *>(response_header.c_str()),
  7323. static_cast<int>(response_header.size()),
  7324. #else
  7325. response_header.c_str(), response_header.size(),
  7326. #endif
  7327. 0);
  7328. // Send 10MB of data
  7329. std::string chunk(64 * 1024, 'A');
  7330. size_t total_sent = 0;
  7331. while (total_sent < MALICIOUS_DATA_SIZE) {
  7332. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7333. auto sent = ::send(cli,
  7334. #ifdef _WIN32
  7335. static_cast<const char *>(chunk.c_str()),
  7336. static_cast<int>(to_send),
  7337. #else
  7338. chunk.c_str(), to_send,
  7339. #endif
  7340. 0);
  7341. if (sent <= 0) break;
  7342. total_sent += static_cast<size_t>(sent);
  7343. }
  7344. detail::close_socket(cli);
  7345. }
  7346. detail::close_socket(srv);
  7347. });
  7348. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7349. size_t total_read = 0;
  7350. {
  7351. Client cli("127.0.0.1", PORT + 2);
  7352. cli.set_read_timeout(5, 0);
  7353. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7354. auto stream = cli.open_stream("GET", "/malicious");
  7355. ASSERT_TRUE(stream.is_valid());
  7356. char buffer[64 * 1024];
  7357. ssize_t n;
  7358. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7359. total_read += static_cast<size_t>(n);
  7360. }
  7361. } // StreamHandle and Client destroyed here, closing the socket
  7362. server_thread.join();
  7363. // With set_payload_max_length, the client must stop reading before consuming
  7364. // all 10MB. The read loop should be cut off at or near the configured limit.
  7365. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7366. << "Client read " << total_read << " bytes, exceeding the configured "
  7367. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7368. }
  7369. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7370. // the entire response body without truncation.
  7371. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7372. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7373. #ifndef _WIN32
  7374. signal(SIGPIPE, SIG_IGN);
  7375. #endif
  7376. auto server_thread = std::thread([] {
  7377. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7378. default_socket_options(srv);
  7379. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7380. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7381. sockaddr_in addr{};
  7382. addr.sin_family = AF_INET;
  7383. addr.sin_port = htons(PORT + 2);
  7384. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7385. int opt = 1;
  7386. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7387. #ifdef _WIN32
  7388. reinterpret_cast<const char *>(&opt),
  7389. #else
  7390. &opt,
  7391. #endif
  7392. sizeof(opt));
  7393. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7394. ::listen(srv, 1);
  7395. sockaddr_in cli_addr{};
  7396. socklen_t cli_len = sizeof(cli_addr);
  7397. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7398. if (cli != INVALID_SOCKET) {
  7399. char buf[4096];
  7400. ::recv(cli, buf, sizeof(buf), 0);
  7401. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7402. "Connection: close\r\n"
  7403. "\r\n";
  7404. ::send(cli,
  7405. #ifdef _WIN32
  7406. static_cast<const char *>(response_header.c_str()),
  7407. static_cast<int>(response_header.size()),
  7408. #else
  7409. response_header.c_str(), response_header.size(),
  7410. #endif
  7411. 0);
  7412. std::string chunk(64 * 1024, 'A');
  7413. size_t total_sent = 0;
  7414. while (total_sent < DATA_SIZE) {
  7415. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7416. auto sent = ::send(cli,
  7417. #ifdef _WIN32
  7418. static_cast<const char *>(chunk.c_str()),
  7419. static_cast<int>(to_send),
  7420. #else
  7421. chunk.c_str(), to_send,
  7422. #endif
  7423. 0);
  7424. if (sent <= 0) break;
  7425. total_sent += static_cast<size_t>(sent);
  7426. }
  7427. #ifdef _WIN32
  7428. ::shutdown(cli, SD_SEND);
  7429. #else
  7430. ::shutdown(cli, SHUT_WR);
  7431. #endif
  7432. // Drain until the client closes its end, ensuring all data is delivered
  7433. char drain[1024];
  7434. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7435. detail::close_socket(cli);
  7436. }
  7437. detail::close_socket(srv);
  7438. });
  7439. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7440. size_t total_read = 0;
  7441. {
  7442. Client cli("127.0.0.1", PORT + 2);
  7443. cli.set_read_timeout(5, 0);
  7444. cli.set_payload_max_length(0); // 0 means no limit
  7445. auto stream = cli.open_stream("GET", "/data");
  7446. ASSERT_TRUE(stream.is_valid());
  7447. char buffer[64 * 1024];
  7448. ssize_t n;
  7449. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7450. total_read += static_cast<size_t>(n);
  7451. }
  7452. }
  7453. server_thread.join();
  7454. EXPECT_EQ(total_read, DATA_SIZE)
  7455. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7456. << " bytes without truncation, but only read " << total_read << " bytes.";
  7457. }
  7458. // Verify that content_receiver bypasses the default payload_max_length,
  7459. // allowing streaming downloads larger than 100MB without requiring an explicit
  7460. // set_payload_max_length call.
  7461. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7462. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7463. #ifndef _WIN32
  7464. signal(SIGPIPE, SIG_IGN);
  7465. #endif
  7466. auto server_thread = std::thread([] {
  7467. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7468. default_socket_options(srv);
  7469. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7470. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7471. sockaddr_in addr{};
  7472. addr.sin_family = AF_INET;
  7473. addr.sin_port = htons(PORT + 2);
  7474. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7475. int opt = 1;
  7476. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7477. #ifdef _WIN32
  7478. reinterpret_cast<const char *>(&opt),
  7479. #else
  7480. &opt,
  7481. #endif
  7482. sizeof(opt));
  7483. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7484. ::listen(srv, 1);
  7485. sockaddr_in cli_addr{};
  7486. socklen_t cli_len = sizeof(cli_addr);
  7487. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7488. if (cli != INVALID_SOCKET) {
  7489. char buf[4096];
  7490. ::recv(cli, buf, sizeof(buf), 0);
  7491. // Response with Content-Length larger than default 100MB limit
  7492. auto content_length = std::to_string(DATA_SIZE);
  7493. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7494. "Content-Length: " +
  7495. content_length +
  7496. "\r\n"
  7497. "Connection: close\r\n"
  7498. "\r\n";
  7499. ::send(cli,
  7500. #ifdef _WIN32
  7501. static_cast<const char *>(response_header.c_str()),
  7502. static_cast<int>(response_header.size()),
  7503. #else
  7504. response_header.c_str(), response_header.size(),
  7505. #endif
  7506. 0);
  7507. std::string chunk(64 * 1024, 'A');
  7508. size_t total_sent = 0;
  7509. while (total_sent < DATA_SIZE) {
  7510. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7511. auto sent = ::send(cli,
  7512. #ifdef _WIN32
  7513. static_cast<const char *>(chunk.c_str()),
  7514. static_cast<int>(to_send),
  7515. #else
  7516. chunk.c_str(), to_send,
  7517. #endif
  7518. 0);
  7519. if (sent <= 0) break;
  7520. total_sent += static_cast<size_t>(sent);
  7521. }
  7522. detail::close_socket(cli);
  7523. }
  7524. detail::close_socket(srv);
  7525. });
  7526. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7527. size_t total_received = 0;
  7528. {
  7529. Client cli("127.0.0.1", PORT + 2);
  7530. cli.set_read_timeout(10, 0);
  7531. // Do NOT call set_payload_max_length — use the default 100MB limit
  7532. auto res =
  7533. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7534. total_received += data_length;
  7535. return true;
  7536. });
  7537. ASSERT_TRUE(res);
  7538. EXPECT_EQ(StatusCode::OK_200, res->status);
  7539. }
  7540. server_thread.join();
  7541. EXPECT_EQ(total_received, DATA_SIZE)
  7542. << "With content_receiver, the client should read all " << DATA_SIZE
  7543. << " bytes despite the default 100MB payload_max_length, but only read "
  7544. << total_received << " bytes.";
  7545. }
  7546. // Verify that an explicit set_payload_max_length smaller than the response is
  7547. // enforced even when a content_receiver is used.
  7548. TEST(ClientVulnerabilityTest,
  7549. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7550. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7551. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7552. #ifndef _WIN32
  7553. signal(SIGPIPE, SIG_IGN);
  7554. #endif
  7555. auto server_thread = std::thread([] {
  7556. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7557. default_socket_options(srv);
  7558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7559. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7560. sockaddr_in addr{};
  7561. addr.sin_family = AF_INET;
  7562. addr.sin_port = htons(PORT + 2);
  7563. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7564. int opt = 1;
  7565. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7566. #ifdef _WIN32
  7567. reinterpret_cast<const char *>(&opt),
  7568. #else
  7569. &opt,
  7570. #endif
  7571. sizeof(opt));
  7572. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7573. ::listen(srv, 1);
  7574. sockaddr_in cli_addr{};
  7575. socklen_t cli_len = sizeof(cli_addr);
  7576. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7577. if (cli != INVALID_SOCKET) {
  7578. char buf[4096];
  7579. ::recv(cli, buf, sizeof(buf), 0);
  7580. auto content_length = std::to_string(DATA_SIZE);
  7581. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7582. "Content-Length: " +
  7583. content_length +
  7584. "\r\n"
  7585. "Connection: close\r\n"
  7586. "\r\n";
  7587. ::send(cli,
  7588. #ifdef _WIN32
  7589. static_cast<const char *>(response_header.c_str()),
  7590. static_cast<int>(response_header.size()),
  7591. #else
  7592. response_header.c_str(), response_header.size(),
  7593. #endif
  7594. 0);
  7595. std::string chunk(64 * 1024, 'A');
  7596. size_t total_sent = 0;
  7597. while (total_sent < DATA_SIZE) {
  7598. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7599. auto sent = ::send(cli,
  7600. #ifdef _WIN32
  7601. static_cast<const char *>(chunk.c_str()),
  7602. static_cast<int>(to_send),
  7603. #else
  7604. chunk.c_str(), to_send,
  7605. #endif
  7606. 0);
  7607. if (sent <= 0) break;
  7608. total_sent += static_cast<size_t>(sent);
  7609. }
  7610. detail::close_socket(cli);
  7611. }
  7612. detail::close_socket(srv);
  7613. });
  7614. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7615. size_t total_received = 0;
  7616. {
  7617. Client cli("127.0.0.1", PORT + 2);
  7618. cli.set_read_timeout(10, 0);
  7619. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7620. auto res =
  7621. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7622. total_received += data_length;
  7623. return true;
  7624. });
  7625. // Should fail because 200MB exceeds the explicit 150MB limit
  7626. EXPECT_FALSE(res);
  7627. }
  7628. server_thread.join();
  7629. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7630. << "Client with content_receiver should respect the explicit "
  7631. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7632. << total_received << " bytes.";
  7633. }
  7634. // Verify that an explicit set_payload_max_length larger than the response
  7635. // allows the content_receiver to read all data successfully.
  7636. TEST(ClientVulnerabilityTest,
  7637. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7638. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7639. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7640. #ifndef _WIN32
  7641. signal(SIGPIPE, SIG_IGN);
  7642. #endif
  7643. auto server_thread = std::thread([] {
  7644. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7645. default_socket_options(srv);
  7646. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7647. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7648. sockaddr_in addr{};
  7649. addr.sin_family = AF_INET;
  7650. addr.sin_port = htons(PORT + 2);
  7651. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7652. int opt = 1;
  7653. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7654. #ifdef _WIN32
  7655. reinterpret_cast<const char *>(&opt),
  7656. #else
  7657. &opt,
  7658. #endif
  7659. sizeof(opt));
  7660. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7661. ::listen(srv, 1);
  7662. sockaddr_in cli_addr{};
  7663. socklen_t cli_len = sizeof(cli_addr);
  7664. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7665. if (cli != INVALID_SOCKET) {
  7666. char buf[4096];
  7667. ::recv(cli, buf, sizeof(buf), 0);
  7668. auto content_length = std::to_string(DATA_SIZE);
  7669. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7670. "Content-Length: " +
  7671. content_length +
  7672. "\r\n"
  7673. "Connection: close\r\n"
  7674. "\r\n";
  7675. ::send(cli,
  7676. #ifdef _WIN32
  7677. static_cast<const char *>(response_header.c_str()),
  7678. static_cast<int>(response_header.size()),
  7679. #else
  7680. response_header.c_str(), response_header.size(),
  7681. #endif
  7682. 0);
  7683. std::string chunk(64 * 1024, 'A');
  7684. size_t total_sent = 0;
  7685. while (total_sent < DATA_SIZE) {
  7686. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7687. auto sent = ::send(cli,
  7688. #ifdef _WIN32
  7689. static_cast<const char *>(chunk.c_str()),
  7690. static_cast<int>(to_send),
  7691. #else
  7692. chunk.c_str(), to_send,
  7693. #endif
  7694. 0);
  7695. if (sent <= 0) break;
  7696. total_sent += static_cast<size_t>(sent);
  7697. }
  7698. #ifdef _WIN32
  7699. ::shutdown(cli, SD_SEND);
  7700. #else
  7701. ::shutdown(cli, SHUT_WR);
  7702. #endif
  7703. char drain[1024];
  7704. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7705. detail::close_socket(cli);
  7706. }
  7707. detail::close_socket(srv);
  7708. });
  7709. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7710. size_t total_received = 0;
  7711. {
  7712. Client cli("127.0.0.1", PORT + 2);
  7713. cli.set_read_timeout(10, 0);
  7714. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7715. auto res =
  7716. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7717. total_received += data_length;
  7718. return true;
  7719. });
  7720. ASSERT_TRUE(res);
  7721. EXPECT_EQ(StatusCode::OK_200, res->status);
  7722. }
  7723. server_thread.join();
  7724. EXPECT_EQ(total_received, DATA_SIZE)
  7725. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7726. << " bytes (larger than " << DATA_SIZE
  7727. << " bytes response), content_receiver should read all data, but only "
  7728. "read "
  7729. << total_received << " bytes.";
  7730. }
  7731. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7732. // Regression test for "zip bomb" attack on the client side: a malicious server
  7733. // sends a small gzip-compressed response that decompresses to a huge payload.
  7734. // The client must enforce payload_max_length on the decompressed size.
  7735. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7736. constexpr size_t DECOMPRESSED_SIZE =
  7737. 10 * 1024 * 1024; // 10MB after decompression
  7738. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7739. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7740. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7741. std::string compressed;
  7742. {
  7743. httplib::detail::gzip_compressor compressor;
  7744. bool ok =
  7745. compressor.compress(uncompressed.data(), uncompressed.size(),
  7746. /*last=*/true, [&](const char *buf, size_t len) {
  7747. compressed.append(buf, len);
  7748. return true;
  7749. });
  7750. ASSERT_TRUE(ok);
  7751. }
  7752. // Sanity: compressed data should be much smaller than the decompressed size
  7753. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7754. #ifndef _WIN32
  7755. signal(SIGPIPE, SIG_IGN);
  7756. #endif
  7757. // Set up the listening socket in the main thread so the server is guaranteed
  7758. // to be ready before the client connects (eliminates race condition).
  7759. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7760. default_socket_options(srv);
  7761. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7763. sockaddr_in addr{};
  7764. addr.sin_family = AF_INET;
  7765. addr.sin_port = htons(PORT + 3);
  7766. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7767. int opt = 1;
  7768. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7769. #ifdef _WIN32
  7770. reinterpret_cast<const char *>(&opt),
  7771. #else
  7772. &opt,
  7773. #endif
  7774. sizeof(opt));
  7775. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7776. ASSERT_EQ(0, ::listen(srv, 1));
  7777. auto server_thread = std::thread([&compressed, srv] {
  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. // Read the full HTTP request (until \r\n\r\n)
  7783. char buf[4096];
  7784. size_t total = 0;
  7785. while (total < sizeof(buf)) {
  7786. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7787. if (n <= 0) break;
  7788. total += static_cast<size_t>(n);
  7789. // Check for end of headers
  7790. if (total >= 4) {
  7791. std::string req(buf, total);
  7792. if (req.find("\r\n\r\n") != std::string::npos) break;
  7793. }
  7794. }
  7795. // Malicious response: gzip-compressed body, no Content-Length
  7796. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7797. "Content-Encoding: gzip\r\n"
  7798. "Connection: close\r\n"
  7799. "\r\n";
  7800. ::send(cli,
  7801. #ifdef _WIN32
  7802. static_cast<const char *>(response_header.c_str()),
  7803. static_cast<int>(response_header.size()),
  7804. #else
  7805. response_header.c_str(), response_header.size(),
  7806. #endif
  7807. 0);
  7808. // Send the compressed payload (small on the wire, huge when decompressed)
  7809. size_t total_sent = 0;
  7810. while (total_sent < compressed.size()) {
  7811. auto to_send = std::min(compressed.size() - total_sent,
  7812. static_cast<size_t>(64 * 1024));
  7813. auto sent =
  7814. ::send(cli,
  7815. #ifdef _WIN32
  7816. static_cast<const char *>(compressed.c_str() + total_sent),
  7817. static_cast<int>(to_send),
  7818. #else
  7819. compressed.c_str() + total_sent, to_send,
  7820. #endif
  7821. 0);
  7822. if (sent <= 0) break;
  7823. total_sent += static_cast<size_t>(sent);
  7824. }
  7825. detail::close_socket(cli);
  7826. }
  7827. });
  7828. auto se = detail::scope_exit([&] {
  7829. detail::close_socket(srv);
  7830. server_thread.join();
  7831. });
  7832. size_t total_decompressed = 0;
  7833. {
  7834. Client cli("127.0.0.1", PORT + 3);
  7835. cli.set_read_timeout(5, 0);
  7836. cli.set_decompress(true);
  7837. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7838. auto stream = cli.open_stream("GET", "/zipbomb");
  7839. ASSERT_TRUE(stream.is_valid());
  7840. char buffer[64 * 1024];
  7841. ssize_t n;
  7842. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7843. total_decompressed += static_cast<size_t>(n);
  7844. }
  7845. }
  7846. // The decompressed size must be capped by payload_max_length. Without
  7847. // protection, the client would decompress the full 10MB from a tiny
  7848. // compressed payload, enabling a zip bomb DoS attack.
  7849. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7850. << "Client decompressed " << total_decompressed
  7851. << " bytes from a gzip response. The decompressed size should be "
  7852. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7853. }
  7854. #endif
  7855. TEST(HostAndPortPropertiesTest, NoSSL) {
  7856. httplib::Client cli("www.google.com", 1234);
  7857. ASSERT_EQ("www.google.com", cli.host());
  7858. ASSERT_EQ(1234, cli.port());
  7859. }
  7860. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7861. httplib::Client cli("www.google.com:1234");
  7862. ASSERT_EQ("www.google.com", cli.host());
  7863. ASSERT_EQ(1234, cli.port());
  7864. }
  7865. #ifdef CPPHTTPLIB_SSL_ENABLED
  7866. TEST(HostAndPortPropertiesTest, SSL) {
  7867. httplib::SSLClient cli("www.google.com");
  7868. ASSERT_EQ("www.google.com", cli.host());
  7869. ASSERT_EQ(443, cli.port());
  7870. }
  7871. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7872. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7873. std::string cert;
  7874. read_file(CA_CERT_FILE, cert);
  7875. httplib::SSLClient httplib_client("www.google.com");
  7876. // Load CA store first time
  7877. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7878. // Load CA store second time (update)
  7879. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7880. // Verify client is still valid and can make connections
  7881. httplib_client.enable_server_certificate_verification(true);
  7882. auto res = httplib_client.Get("/");
  7883. ASSERT_TRUE(res);
  7884. // Google may return 200 or 301 depending on various factors
  7885. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7886. res->status == StatusCode::MovedPermanently_301);
  7887. }
  7888. TEST(SSLClientTest, ServerNameIndication_Online) {
  7889. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7890. auto host = "httpcan.org";
  7891. auto path = std::string{"/get"};
  7892. #else
  7893. auto host = "nghttp2.org";
  7894. auto path = std::string{"/httpbin/get"};
  7895. #endif
  7896. SSLClient cli(host, 443);
  7897. auto res = cli.Get(path);
  7898. ASSERT_TRUE(res);
  7899. ASSERT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7902. // Use a site that will cause SSL verification failure due to self-signed cert
  7903. SSLClient cli("self-signed.badssl.com", 443);
  7904. cli.enable_server_certificate_verification(true);
  7905. auto res = cli.Get("/");
  7906. ASSERT_TRUE(!res);
  7907. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7908. // Verify backend error is captured for SSLServerVerification
  7909. // This occurs when certificate verification fails
  7910. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7911. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7912. EXPECT_NE(0UL, res.ssl_backend_error());
  7913. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7914. // For OpenSSL, ssl_error is 0 for verification errors
  7915. EXPECT_EQ(0, res.ssl_error());
  7916. #if !defined(_WIN32) || \
  7917. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7918. // On non-Windows or when Windows Schannel is disabled, the error comes
  7919. // from OpenSSL's verification
  7920. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7921. res.ssl_backend_error());
  7922. #endif
  7923. #endif
  7924. }
  7925. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7926. // Use a site where hostname doesn't match the certificate
  7927. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7928. SSLClient cli("wrong.host.badssl.com", 443);
  7929. cli.enable_server_certificate_verification(true);
  7930. cli.enable_server_hostname_verification(true);
  7931. auto res = cli.Get("/");
  7932. ASSERT_TRUE(!res);
  7933. // The error type depends on when hostname verification occurs:
  7934. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7935. // - Mbed TLS: SSLServerVerification (during handshake)
  7936. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7937. res.error() == Error::SSLServerVerification);
  7938. // Verify backend error is captured for hostname verification failure
  7939. EXPECT_NE(0UL, res.ssl_backend_error());
  7940. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7941. // For OpenSSL, ssl_error is 0 for verification errors
  7942. EXPECT_EQ(0, res.ssl_error());
  7943. #if !defined(_WIN32) || \
  7944. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7945. // On non-Windows or when Windows Schannel is disabled, the error comes
  7946. // from OpenSSL's hostname verification
  7947. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7948. res.ssl_backend_error());
  7949. #endif
  7950. #endif
  7951. }
  7952. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  7953. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7954. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  7955. SSLClient cli("www.google.com", 443);
  7956. cli.enable_server_certificate_verification(true);
  7957. auto res = cli.Get("/");
  7958. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7959. }
  7960. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  7961. SSLClient cli("www.google.com", 443);
  7962. cli.enable_server_certificate_verification(true);
  7963. cli.enable_windows_certificate_verification(false);
  7964. auto res = cli.Get("/");
  7965. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  7966. }
  7967. #endif
  7968. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7969. Client cli("https://google.com");
  7970. auto res = cli.Get("/");
  7971. ASSERT_TRUE(res);
  7972. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7973. }
  7974. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7975. SSLClient cli("google.com");
  7976. cli.set_ca_cert_path(CA_CERT_FILE);
  7977. auto res = cli.Get("/");
  7978. ASSERT_TRUE(res);
  7979. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7980. }
  7981. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7982. SSLClient cli("google.com");
  7983. cli.enable_server_certificate_verification(true);
  7984. cli.set_ca_cert_path("hello");
  7985. auto res = cli.Get("/");
  7986. ASSERT_TRUE(!res);
  7987. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7988. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7989. // should be set
  7990. EXPECT_EQ(0, res.ssl_error());
  7991. // Verify backend error is captured for SSLLoadingCerts
  7992. // This error occurs when loading CA certificates fails
  7993. EXPECT_NE(0UL, res.ssl_backend_error());
  7994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7995. // OpenSSL specific error codes:
  7996. // > openssl errstr 0x80000002
  7997. // error:80000002:system library::No such file or directory
  7998. // > openssl errstr 0xA000126
  7999. // error:0A000126:SSL routines::unexpected eof while reading
  8000. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8001. res.ssl_backend_error() == 0xA000126);
  8002. #endif
  8003. }
  8004. TEST(SSLClientTest, ServerCertificateVerification4) {
  8005. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8006. ASSERT_TRUE(svr.is_valid());
  8007. svr.Get("/test", [&](const Request &, Response &res) {
  8008. res.set_content("test", "text/plain");
  8009. svr.stop();
  8010. ASSERT_TRUE(true);
  8011. });
  8012. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8013. auto se = detail::scope_exit([&] {
  8014. t.join();
  8015. ASSERT_FALSE(svr.is_running());
  8016. });
  8017. svr.wait_until_ready();
  8018. SSLClient cli("127.0.0.1", PORT);
  8019. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8020. cli.enable_server_certificate_verification(true);
  8021. cli.set_connection_timeout(30);
  8022. auto res = cli.Get("/test");
  8023. ASSERT_TRUE(res);
  8024. ASSERT_EQ(StatusCode::OK_200, res->status);
  8025. }
  8026. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8027. std::string cert;
  8028. read_file(CA_CERT_FILE, cert);
  8029. SSLClient cli("google.com");
  8030. cli.load_ca_cert_store(cert.data(), cert.size());
  8031. const auto res = cli.Get("/");
  8032. ASSERT_TRUE(res);
  8033. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8034. }
  8035. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8036. // clang-format off
  8037. static constexpr char cert[] =
  8038. "GlobalSign Root CA\n"
  8039. "==================\n"
  8040. "-----BEGIN CERTIFICATE-----\n"
  8041. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8042. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8043. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8044. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8045. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8046. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8047. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8048. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8049. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8050. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8051. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8052. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8053. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8054. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8055. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8056. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8057. "-----END CERTIFICATE-----\n";
  8058. // clang-format on
  8059. SSLClient cli("google.com");
  8060. cli.load_ca_cert_store(cert, sizeof(cert));
  8061. const auto res = cli.Get("/");
  8062. ASSERT_TRUE(res);
  8063. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8064. }
  8065. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8066. SSLClient cli("www.youtube.com");
  8067. cli.set_ca_cert_path(CA_CERT_FILE);
  8068. cli.enable_server_certificate_verification(true);
  8069. cli.set_follow_location(true);
  8070. auto res = cli.Get("/");
  8071. ASSERT_TRUE(res);
  8072. ASSERT_EQ(StatusCode::OK_200, res->status);
  8073. }
  8074. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8075. SSLClient cli("wWw.YouTube.Com");
  8076. cli.set_ca_cert_path(CA_CERT_FILE);
  8077. cli.enable_server_certificate_verification(true);
  8078. cli.enable_server_hostname_verification(true);
  8079. cli.set_follow_location(true);
  8080. auto res = cli.Get("/");
  8081. ASSERT_TRUE(res);
  8082. ASSERT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8085. SSLClient cli("gOoGlE.COm");
  8086. cli.enable_server_certificate_verification(true);
  8087. cli.enable_server_hostname_verification(true);
  8088. cli.set_follow_location(true);
  8089. auto res = cli.Get("/");
  8090. ASSERT_TRUE(res);
  8091. ASSERT_EQ(StatusCode::OK_200, res->status);
  8092. }
  8093. TEST(SSLClientTest, Issue2004_Online) {
  8094. Client client("https://google.com");
  8095. client.set_follow_location(true);
  8096. auto res = client.Get("/");
  8097. ASSERT_TRUE(res);
  8098. ASSERT_EQ(StatusCode::OK_200, res->status);
  8099. auto body = res->body;
  8100. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8101. }
  8102. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8103. // Create SSLClient with invalid cert/key to make is_valid() return false
  8104. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8105. "nonexistent_key.pem");
  8106. // is_valid() should be false due to cert loading failure
  8107. ASSERT_FALSE(cli.is_valid());
  8108. auto res = cli.Get("/");
  8109. ASSERT_FALSE(res);
  8110. EXPECT_EQ(Error::SSLConnection, res.error());
  8111. }
  8112. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8113. // Test for Issue #2251: SSL error not properly reported when client cert
  8114. // and key paths are swapped or mismatched
  8115. // This simulates the scenario where user accidentally swaps the cert and key
  8116. // files
  8117. // Using client cert file as private key and vice versa (completely wrong)
  8118. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8119. // Should fail validation due to cert/key mismatch
  8120. ASSERT_FALSE(cli.is_valid());
  8121. // Attempt to make a request should fail with proper error
  8122. auto res = cli.Get("/");
  8123. ASSERT_FALSE(res);
  8124. EXPECT_EQ(Error::SSLConnection, res.error());
  8125. // SSL error should be recorded in the Result object (this is the key fix for
  8126. // Issue #2251)
  8127. auto backend_error = res.ssl_backend_error();
  8128. EXPECT_NE(0u, backend_error);
  8129. }
  8130. // Tests cert/key mismatch detection at the TLS context level
  8131. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8132. // Test that using mismatched cert/key causes connection failure.
  8133. // We verify this at the SSLClient level rather than through internal
  8134. // TLS API functions.
  8135. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8136. cli.enable_server_certificate_verification(false);
  8137. cli.set_connection_timeout(2);
  8138. // The mismatch should cause a connection or handshake error
  8139. auto res = cli.Get("/test");
  8140. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8141. // Either way, the request should fail
  8142. EXPECT_FALSE(res);
  8143. }
  8144. #endif
  8145. #if 0
  8146. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8147. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8148. ASSERT_TRUE(cli != nullptr);
  8149. cli->set_address_family(AF_INET6);
  8150. cli->set_interface("en0");
  8151. auto res = cli->Get("/get");
  8152. ASSERT_TRUE(res);
  8153. ASSERT_EQ(StatusCode::OK_200, res->status);
  8154. }
  8155. #endif
  8156. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8157. #ifdef CPPHTTPLIB_SSL_ENABLED
  8158. void ClientCertPresent(
  8159. const std::string &client_cert_file,
  8160. const std::string &client_private_key_file,
  8161. const std::string &client_encrypted_private_key_pass = std::string()) {
  8162. using namespace httplib::tls;
  8163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8164. CLIENT_CA_CERT_DIR);
  8165. ASSERT_TRUE(svr.is_valid());
  8166. svr.Get("/test", [&](const Request &req, Response &res) {
  8167. res.set_content("test", "text/plain");
  8168. auto cert = req.peer_cert();
  8169. ASSERT_TRUE(static_cast<bool>(cert));
  8170. std::string common_name = cert.subject_cn();
  8171. EXPECT_EQ("Common Name", common_name);
  8172. });
  8173. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8174. auto se = detail::scope_exit([&] {
  8175. svr.stop();
  8176. t.join();
  8177. ASSERT_FALSE(svr.is_running());
  8178. });
  8179. svr.wait_until_ready();
  8180. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8181. client_encrypted_private_key_pass);
  8182. cli.enable_server_certificate_verification(false);
  8183. cli.set_connection_timeout(30);
  8184. auto res = cli.Get("/test");
  8185. ASSERT_TRUE(res);
  8186. ASSERT_EQ(StatusCode::OK_200, res->status);
  8187. }
  8188. TEST(SSLClientServerTest, ClientCertPresent) {
  8189. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8190. }
  8191. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8192. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8193. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8194. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8195. }
  8196. // PEM memory-based constructor tests (works with all TLS backends)
  8197. void PemMemoryClientCertPresent(
  8198. const std::string &client_cert_file,
  8199. const std::string &client_private_key_file,
  8200. const std::string &client_encrypted_private_key_pass = std::string()) {
  8201. // Read PEM files into memory
  8202. std::string server_cert_pem, server_key_pem;
  8203. std::string client_ca_pem;
  8204. std::string client_cert_pem, client_key_pem;
  8205. read_file(SERVER_CERT_FILE, server_cert_pem);
  8206. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8207. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8208. read_file(client_cert_file, client_cert_pem);
  8209. read_file(client_private_key_file, client_key_pem);
  8210. // Create server with PEM memory
  8211. SSLServer::PemMemory server_pem = {
  8212. server_cert_pem.c_str(),
  8213. server_cert_pem.size(),
  8214. server_key_pem.c_str(),
  8215. server_key_pem.size(),
  8216. client_ca_pem.c_str(),
  8217. client_ca_pem.size(),
  8218. nullptr // no password for server key
  8219. };
  8220. SSLServer svr(server_pem);
  8221. ASSERT_TRUE(svr.is_valid());
  8222. svr.Get("/test", [&](const Request &, Response &res) {
  8223. res.set_content("test", "text/plain");
  8224. });
  8225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8226. auto se = detail::scope_exit([&] {
  8227. svr.stop();
  8228. t.join();
  8229. ASSERT_FALSE(svr.is_running());
  8230. });
  8231. svr.wait_until_ready();
  8232. // Create client with PEM memory
  8233. const char *password = client_encrypted_private_key_pass.empty()
  8234. ? nullptr
  8235. : client_encrypted_private_key_pass.c_str();
  8236. SSLClient::PemMemory client_pem = {
  8237. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8238. client_key_pem.size(), password};
  8239. SSLClient cli(HOST, PORT, client_pem);
  8240. cli.enable_server_certificate_verification(false);
  8241. cli.set_connection_timeout(30);
  8242. auto res = cli.Get("/test");
  8243. ASSERT_TRUE(res);
  8244. ASSERT_EQ(StatusCode::OK_200, res->status);
  8245. }
  8246. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8247. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8248. }
  8249. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8250. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8251. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8252. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8253. }
  8254. TEST(SSLClientServerTest, ClientCertMissing) {
  8255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8256. CLIENT_CA_CERT_DIR);
  8257. ASSERT_TRUE(svr.is_valid());
  8258. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8259. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8260. auto se = detail::scope_exit([&] {
  8261. svr.stop();
  8262. t.join();
  8263. ASSERT_FALSE(svr.is_running());
  8264. });
  8265. svr.wait_until_ready();
  8266. SSLClient cli(HOST, PORT);
  8267. cli.set_connection_timeout(30);
  8268. auto res = cli.Get("/test");
  8269. ASSERT_TRUE(!res);
  8270. // When client cert is missing and server requires it, connection fails
  8271. // Error type depends on backend implementation
  8272. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8273. res.error() == Error::SSLConnection);
  8274. // Verify backend error is captured
  8275. // Note: This test may have different error codes depending on the exact
  8276. // verification failure
  8277. EXPECT_NE(0UL, res.ssl_backend_error());
  8278. }
  8279. TEST(SSLClientServerTest, TrustDirOptional) {
  8280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8281. ASSERT_TRUE(svr.is_valid());
  8282. svr.Get("/test", [&](const Request &, Response &res) {
  8283. res.set_content("test", "text/plain");
  8284. });
  8285. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8286. auto se = detail::scope_exit([&] {
  8287. svr.stop();
  8288. t.join();
  8289. ASSERT_FALSE(svr.is_running());
  8290. });
  8291. svr.wait_until_ready();
  8292. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8293. cli.enable_server_certificate_verification(false);
  8294. cli.set_connection_timeout(30);
  8295. auto res = cli.Get("/test");
  8296. ASSERT_TRUE(res);
  8297. ASSERT_EQ(StatusCode::OK_200, res->status);
  8298. }
  8299. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8300. class NoListenSSLServer : public SSLServer {
  8301. public:
  8302. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8303. const char *client_ca_cert_file_path,
  8304. const char *client_ca_cert_dir_path = nullptr)
  8305. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8306. client_ca_cert_dir_path),
  8307. stop_(false) {}
  8308. std::atomic_bool stop_;
  8309. private:
  8310. bool process_and_close_socket(socket_t /*sock*/) override {
  8311. // Don't create SSL context
  8312. while (!stop_.load()) {
  8313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8314. }
  8315. return true;
  8316. }
  8317. };
  8318. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8319. CLIENT_CA_CERT_FILE);
  8320. ASSERT_TRUE(svr.is_valid());
  8321. svr.Get("/test", [&](const Request &, Response &res) {
  8322. res.set_content("test", "text/plain");
  8323. });
  8324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8325. auto se = detail::scope_exit([&] {
  8326. svr.stop_ = true;
  8327. svr.stop();
  8328. t.join();
  8329. ASSERT_FALSE(svr.is_running());
  8330. });
  8331. svr.wait_until_ready();
  8332. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8333. cli.enable_server_certificate_verification(false);
  8334. cli.set_connection_timeout(1);
  8335. auto res = cli.Get("/test");
  8336. ASSERT_TRUE(!res);
  8337. EXPECT_EQ(Error::SSLConnection, res.error());
  8338. // Timeout results in WantRead error code (maps to backend-specific value)
  8339. EXPECT_NE(0, res.ssl_error());
  8340. }
  8341. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8342. // Test SSLServer with client certificate verification using the standard
  8343. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8345. CLIENT_CA_CERT_DIR);
  8346. ASSERT_TRUE(svr.is_valid());
  8347. svr.Get("/test", [&](const Request &req, Response &res) {
  8348. res.set_content("test", "text/plain");
  8349. auto cert = req.peer_cert();
  8350. ASSERT_TRUE(static_cast<bool>(cert));
  8351. auto common_name = cert.subject_cn();
  8352. EXPECT_EQ("Common Name", common_name);
  8353. });
  8354. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8355. auto se = detail::scope_exit([&] {
  8356. svr.stop();
  8357. t.join();
  8358. ASSERT_FALSE(svr.is_running());
  8359. });
  8360. svr.wait_until_ready();
  8361. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8362. cli.enable_server_certificate_verification(false);
  8363. cli.set_connection_timeout(30);
  8364. auto res = cli.Get("/test");
  8365. ASSERT_TRUE(res);
  8366. ASSERT_EQ(StatusCode::OK_200, res->status);
  8367. }
  8368. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8369. // Verifies that wildcard matching and exact matching work consistently
  8370. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8371. using namespace httplib::tls;
  8372. // We need a running server to test against
  8373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8374. ASSERT_TRUE(svr.is_valid());
  8375. svr.Get("/test", [](const Request &, Response &res) {
  8376. res.set_content("ok", "text/plain");
  8377. });
  8378. thread t([&]() { svr.listen(HOST, PORT); });
  8379. auto se = detail::scope_exit([&] {
  8380. svr.stop();
  8381. t.join();
  8382. });
  8383. svr.wait_until_ready();
  8384. bool verify_callback_called = false;
  8385. bool verify_result_wrong = false;
  8386. SSLClient cli(HOST, PORT);
  8387. cli.enable_server_certificate_verification(true);
  8388. cli.set_ca_cert_path(CA_CERT_FILE);
  8389. cli.set_connection_timeout(5);
  8390. // Note: Test certificate has CN="Common Name", not "localhost"
  8391. bool verify_result_cn = false;
  8392. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8393. verify_callback_called = true;
  8394. if (!ctx.cert) return false;
  8395. // Test 1: "Common Name" should match (our test server cert CN)
  8396. verify_result_cn = ctx.check_hostname("Common Name");
  8397. // Test 2: wrong hostname should not match
  8398. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8399. return true; // Accept for the purpose of this test
  8400. });
  8401. auto res = cli.Get("/test");
  8402. // The request may succeed or fail depending on cert configuration
  8403. // but the callback should have been called
  8404. ASSERT_TRUE(verify_callback_called)
  8405. << "Verify callback should have been called";
  8406. // CN="Common Name" should match our test certificate
  8407. EXPECT_TRUE(verify_result_cn)
  8408. << "verify_hostname should match 'Common Name' (certificate CN)";
  8409. // Wrong hostname should not match
  8410. EXPECT_FALSE(verify_result_wrong)
  8411. << "verify_hostname should not match 'wronghost.example.com'";
  8412. }
  8413. #endif
  8414. // mbedTLS-specific callback constructor test
  8415. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8416. #ifdef CPPHTTPLIB_SSL_ENABLED
  8417. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8419. ASSERT_TRUE(svr.is_valid());
  8420. // Set up a handler to verify client certificate is present
  8421. bool client_cert_verified = false;
  8422. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8423. // Verify that client certificate was provided
  8424. client_cert_verified = true;
  8425. res.set_content("success", "text/plain");
  8426. });
  8427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8428. auto se = detail::scope_exit([&] {
  8429. svr.stop();
  8430. t.join();
  8431. ASSERT_FALSE(svr.is_running());
  8432. });
  8433. svr.wait_until_ready();
  8434. // Client with certificate
  8435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8436. cli.enable_server_certificate_verification(false);
  8437. cli.set_connection_timeout(30);
  8438. auto res = cli.Get("/test");
  8439. ASSERT_TRUE(res);
  8440. ASSERT_EQ(StatusCode::OK_200, res->status);
  8441. ASSERT_TRUE(client_cert_verified);
  8442. EXPECT_EQ("success", res->body);
  8443. }
  8444. #endif
  8445. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8446. // backends
  8447. #ifdef CPPHTTPLIB_SSL_ENABLED
  8448. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8449. using namespace httplib::tls;
  8450. // Test that when client CA cert file is provided,
  8451. // the server properly requests and validates client certificates
  8452. // Create a server with client authentication
  8453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8454. ASSERT_TRUE(svr.is_valid());
  8455. bool handler_called = false;
  8456. svr.Get("/test", [&](const Request &req, Response &res) {
  8457. handler_called = true;
  8458. // Verify that a client certificate was provided
  8459. auto cert = req.peer_cert();
  8460. ASSERT_TRUE(static_cast<bool>(cert));
  8461. // Get the issuer name
  8462. std::string issuer_str = cert.issuer_name();
  8463. ASSERT_FALSE(issuer_str.empty());
  8464. // The client certificate should be issued by our test CA
  8465. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8466. res.set_content("authenticated", "text/plain");
  8467. });
  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. // Connect with a client certificate issued by the CA
  8476. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8477. cli.enable_server_certificate_verification(false);
  8478. cli.set_connection_timeout(30);
  8479. auto res = cli.Get("/test");
  8480. ASSERT_TRUE(res);
  8481. ASSERT_EQ(StatusCode::OK_200, res->status);
  8482. ASSERT_TRUE(handler_called);
  8483. EXPECT_EQ("authenticated", res->body);
  8484. }
  8485. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8486. using namespace httplib::tls;
  8487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8488. ASSERT_TRUE(svr.is_valid());
  8489. svr.Get("/test", [](const Request &, Response &res) {
  8490. res.set_content("ok", "text/plain");
  8491. });
  8492. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8493. auto se = detail::scope_exit([&] {
  8494. svr.stop();
  8495. t.join();
  8496. });
  8497. svr.wait_until_ready();
  8498. SSLClient cli(HOST, PORT);
  8499. cli.enable_server_certificate_verification(false);
  8500. cli.set_connection_timeout(30);
  8501. bool cert_checked = false;
  8502. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8503. if (ctx.cert) {
  8504. auto sans = ctx.sans();
  8505. // Test certificate may or may not have SANs - just verify the API
  8506. // works If SANs exist, verify the types are valid
  8507. for (const auto &san : sans) {
  8508. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8509. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8510. san.type == SanType::OTHER);
  8511. EXPECT_FALSE(san.value.empty());
  8512. }
  8513. cert_checked = true;
  8514. }
  8515. return true;
  8516. });
  8517. auto res = cli.Get("/test");
  8518. ASSERT_TRUE(res);
  8519. EXPECT_TRUE(cert_checked);
  8520. }
  8521. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8522. using namespace httplib::tls;
  8523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8524. ASSERT_TRUE(svr.is_valid());
  8525. svr.Get("/test", [](const Request &, Response &res) {
  8526. res.set_content("ok", "text/plain");
  8527. });
  8528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8529. auto se = detail::scope_exit([&] {
  8530. svr.stop();
  8531. t.join();
  8532. });
  8533. svr.wait_until_ready();
  8534. SSLClient cli(HOST, PORT);
  8535. cli.enable_server_certificate_verification(false);
  8536. cli.set_connection_timeout(30);
  8537. bool validity_checked = false;
  8538. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8539. if (ctx.cert) {
  8540. time_t not_before = 0, not_after = 0;
  8541. bool result = ctx.validity(not_before, not_after);
  8542. EXPECT_TRUE(result);
  8543. // Verify that not_before < now < not_after for a valid cert
  8544. time_t now = time(nullptr);
  8545. EXPECT_LT(not_before, now);
  8546. EXPECT_GT(not_after, now);
  8547. validity_checked = true;
  8548. }
  8549. return true;
  8550. });
  8551. auto res = cli.Get("/test");
  8552. ASSERT_TRUE(res);
  8553. EXPECT_TRUE(validity_checked);
  8554. }
  8555. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8556. using namespace httplib::tls;
  8557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8558. ASSERT_TRUE(svr.is_valid());
  8559. svr.Get("/test", [](const Request &, Response &res) {
  8560. res.set_content("ok", "text/plain");
  8561. });
  8562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8563. auto se = detail::scope_exit([&] {
  8564. svr.stop();
  8565. t.join();
  8566. });
  8567. svr.wait_until_ready();
  8568. SSLClient cli(HOST, PORT);
  8569. cli.enable_server_certificate_verification(false);
  8570. cli.set_connection_timeout(30);
  8571. bool serial_checked = false;
  8572. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8573. if (ctx.cert) {
  8574. std::string serial = ctx.serial();
  8575. EXPECT_FALSE(serial.empty());
  8576. // Serial should be a hex string
  8577. for (char c : serial) {
  8578. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8579. (c >= 'a' && c <= 'f'));
  8580. }
  8581. serial_checked = true;
  8582. }
  8583. return true;
  8584. });
  8585. auto res = cli.Get("/test");
  8586. ASSERT_TRUE(res);
  8587. EXPECT_TRUE(serial_checked);
  8588. }
  8589. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8590. // Test 1: Valid CA file - no error should be recorded
  8591. {
  8592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8593. CLIENT_CA_CERT_FILE);
  8594. ASSERT_TRUE(svr.is_valid());
  8595. // With valid setup, last_ssl_error should be 0
  8596. EXPECT_EQ(0, svr.ssl_last_error());
  8597. }
  8598. // Test 2: Invalid CA file content
  8599. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8600. {
  8601. // Create a temporary file with completely invalid content
  8602. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8603. {
  8604. std::ofstream ofs(temp_invalid_ca);
  8605. ofs << "This is not a certificate file at all\n";
  8606. ofs << "Just plain text content\n";
  8607. }
  8608. // Create server with invalid CA file
  8609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8610. // Clean up temporary file
  8611. std::remove(temp_invalid_ca);
  8612. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8613. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8614. // Note: SSL_CTX_load_verify_locations typically fails first,
  8615. // but our error handling code path is still exercised
  8616. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8617. }
  8618. }
  8619. TEST(VerifyCallbackTest, VerifyContextFields) {
  8620. using namespace httplib::tls;
  8621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8622. ASSERT_TRUE(svr.is_valid());
  8623. svr.Get("/test", [](const Request &, Response &res) {
  8624. res.set_content("ok", "text/plain");
  8625. });
  8626. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8627. auto se = detail::scope_exit([&] {
  8628. svr.stop();
  8629. t.join();
  8630. });
  8631. svr.wait_until_ready();
  8632. SSLClient cli(HOST, PORT);
  8633. cli.enable_server_certificate_verification(false);
  8634. cli.set_connection_timeout(30);
  8635. int callback_count = 0;
  8636. bool saw_leaf_cert = false;
  8637. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8638. if (ctx.cert) {
  8639. callback_count++;
  8640. // We should see at least one certificate (the leaf)
  8641. std::string cn = ctx.subject_cn();
  8642. if (!cn.empty()) { saw_leaf_cert = true; }
  8643. // Verify context fields are populated
  8644. EXPECT_NE(ctx.session, nullptr);
  8645. EXPECT_GE(ctx.depth, 0);
  8646. }
  8647. return true;
  8648. });
  8649. auto res = cli.Get("/test");
  8650. ASSERT_TRUE(res);
  8651. EXPECT_GT(callback_count, 0);
  8652. EXPECT_TRUE(saw_leaf_cert);
  8653. }
  8654. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8655. using httplib::tls::TlsError;
  8656. // Test that verify_error_to_string returns empty for success
  8657. std::string success_str = TlsError::verify_error_to_string(0);
  8658. EXPECT_TRUE(success_str.empty());
  8659. // Test that verify_error_to_string returns non-empty for error codes
  8660. // Using a common error code (certificate expired)
  8661. std::string error_str =
  8662. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8663. EXPECT_FALSE(error_str.empty());
  8664. }
  8665. TEST(SessionVerifierTest, CertificateAccepted) {
  8666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8667. ASSERT_TRUE(svr.is_valid());
  8668. svr.Get("/test", [](const Request &, Response &res) {
  8669. res.set_content("ok", "text/plain");
  8670. });
  8671. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8672. auto se = detail::scope_exit([&] {
  8673. svr.stop();
  8674. t.join();
  8675. });
  8676. svr.wait_until_ready();
  8677. SSLClient cli(HOST, PORT);
  8678. cli.enable_server_certificate_verification(false);
  8679. cli.set_connection_timeout(30);
  8680. bool callback_called = false;
  8681. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8682. EXPECT_NE(session, nullptr);
  8683. callback_called = true;
  8684. return SSLVerifierResponse::CertificateAccepted;
  8685. });
  8686. auto res = cli.Get("/test");
  8687. ASSERT_TRUE(res);
  8688. EXPECT_EQ(200, res->status);
  8689. EXPECT_TRUE(callback_called);
  8690. }
  8691. TEST(SessionVerifierTest, CertificateRejected) {
  8692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8693. ASSERT_TRUE(svr.is_valid());
  8694. svr.Get("/test", [](const Request &, Response &res) {
  8695. res.set_content("ok", "text/plain");
  8696. });
  8697. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8698. auto se = detail::scope_exit([&] {
  8699. svr.stop();
  8700. t.join();
  8701. });
  8702. svr.wait_until_ready();
  8703. SSLClient cli(HOST, PORT);
  8704. cli.enable_server_certificate_verification(false);
  8705. cli.set_connection_timeout(30);
  8706. bool callback_called = false;
  8707. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8708. EXPECT_NE(session, nullptr);
  8709. callback_called = true;
  8710. return SSLVerifierResponse::CertificateRejected;
  8711. });
  8712. auto res = cli.Get("/test");
  8713. EXPECT_FALSE(res);
  8714. EXPECT_TRUE(callback_called);
  8715. }
  8716. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8718. ASSERT_TRUE(svr.is_valid());
  8719. svr.Get("/test", [](const Request &, Response &res) {
  8720. res.set_content("ok", "text/plain");
  8721. });
  8722. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8723. auto se = detail::scope_exit([&] {
  8724. svr.stop();
  8725. t.join();
  8726. });
  8727. svr.wait_until_ready();
  8728. // NoDecisionMade with verification disabled should succeed (no default check)
  8729. SSLClient cli(HOST, PORT);
  8730. cli.enable_server_certificate_verification(false);
  8731. cli.set_connection_timeout(30);
  8732. bool callback_called = false;
  8733. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8734. EXPECT_NE(session, nullptr);
  8735. callback_called = true;
  8736. return SSLVerifierResponse::NoDecisionMade;
  8737. });
  8738. auto res = cli.Get("/test");
  8739. ASSERT_TRUE(res);
  8740. EXPECT_EQ(200, res->status);
  8741. EXPECT_TRUE(callback_called);
  8742. }
  8743. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8745. ASSERT_TRUE(svr.is_valid());
  8746. svr.Get("/test", [](const Request &, Response &res) {
  8747. res.set_content("ok", "text/plain");
  8748. });
  8749. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8750. auto se = detail::scope_exit([&] {
  8751. svr.stop();
  8752. t.join();
  8753. });
  8754. svr.wait_until_ready();
  8755. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8756. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8757. // so we only check that the request fails, not whether the callback was
  8758. // called.
  8759. SSLClient cli(HOST, PORT);
  8760. cli.enable_server_certificate_verification(true);
  8761. cli.set_connection_timeout(30);
  8762. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8763. EXPECT_NE(session, nullptr);
  8764. return SSLVerifierResponse::NoDecisionMade;
  8765. });
  8766. auto res = cli.Get("/test");
  8767. EXPECT_FALSE(res);
  8768. }
  8769. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8770. // Test SSL server using PemMemory constructor with client CA certificates
  8771. // Read PEM files
  8772. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8773. read_file(SERVER_CERT_FILE, server_cert_pem);
  8774. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8775. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8776. // Create SSLServer with PemMemory constructor including client CA
  8777. SSLServer::PemMemory server_pem = {
  8778. server_cert_pem.c_str(),
  8779. server_cert_pem.size(),
  8780. server_key_pem.c_str(),
  8781. server_key_pem.size(),
  8782. client_ca_pem.c_str(),
  8783. client_ca_pem.size(),
  8784. nullptr // no password for server key
  8785. };
  8786. SSLServer svr(server_pem);
  8787. ASSERT_TRUE(svr.is_valid());
  8788. // No SSL error should be recorded for valid setup
  8789. EXPECT_EQ(0, svr.ssl_last_error());
  8790. // Set up server endpoints
  8791. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8792. res.set_content("ok", "text/plain");
  8793. });
  8794. // Start server in a thread
  8795. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8796. svr.wait_until_ready();
  8797. // Connect with client certificate (using constructor with paths)
  8798. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8799. cli.enable_server_certificate_verification(false);
  8800. auto res = cli.Get("/test-pem-ca");
  8801. ASSERT_TRUE(res);
  8802. EXPECT_EQ(200, res->status);
  8803. EXPECT_EQ("ok", res->body);
  8804. svr.stop();
  8805. server_thread.join();
  8806. }
  8807. #endif
  8808. #ifdef _WIN32
  8809. TEST(CleanupTest, WSACleanup) {
  8810. int ret = WSACleanup();
  8811. ASSERT_EQ(0, ret);
  8812. }
  8813. #endif
  8814. #ifndef CPPHTTPLIB_SSL_ENABLED
  8815. TEST(NoSSLSupport, SimpleInterface) {
  8816. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8817. }
  8818. #endif
  8819. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8820. TEST(InvalidScheme, SimpleInterface) {
  8821. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8822. }
  8823. #endif
  8824. TEST(NoScheme, SimpleInterface) {
  8825. Client cli("yahoo.com:80");
  8826. ASSERT_TRUE(cli.is_valid());
  8827. }
  8828. TEST(SendAPI, SimpleInterface_Online) {
  8829. Client cli("http://yahoo.com");
  8830. Request req;
  8831. req.method = "GET";
  8832. req.path = "/";
  8833. auto res = cli.send(req);
  8834. ASSERT_TRUE(res);
  8835. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8836. }
  8837. TEST(SendAPI, WithParamsInRequest) {
  8838. Server svr;
  8839. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8840. EXPECT_TRUE(req.has_param("test"));
  8841. EXPECT_EQ("test_value", req.get_param_value("test"));
  8842. });
  8843. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8844. auto se = detail::scope_exit([&] {
  8845. svr.stop();
  8846. t.join();
  8847. ASSERT_FALSE(svr.is_running());
  8848. });
  8849. svr.wait_until_ready();
  8850. Client cli(HOST, PORT);
  8851. {
  8852. Request req;
  8853. req.method = "GET";
  8854. req.path = "/";
  8855. req.params.emplace("test", "test_value");
  8856. auto res = cli.send(req);
  8857. ASSERT_TRUE(res);
  8858. }
  8859. {
  8860. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8861. ASSERT_TRUE(res);
  8862. }
  8863. }
  8864. TEST(ClientImplMethods, GetSocketTest) {
  8865. httplib::Server svr;
  8866. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8867. res.status = StatusCode::OK_200;
  8868. });
  8869. auto port = svr.bind_to_any_port("127.0.0.1");
  8870. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8871. auto se = detail::scope_exit([&] {
  8872. svr.stop();
  8873. thread.join();
  8874. ASSERT_FALSE(svr.is_running());
  8875. });
  8876. svr.wait_until_ready();
  8877. {
  8878. httplib::Client cli("127.0.0.1", port);
  8879. cli.set_keep_alive(true);
  8880. // Use the behavior of cpp-httplib of opening the connection
  8881. // only when the first request happens. If that changes,
  8882. // this test would be obsolete.
  8883. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8884. // This also implicitly tests the server. But other tests would fail much
  8885. // earlier than this one to be considered.
  8886. auto res = cli.Get("/");
  8887. ASSERT_TRUE(res);
  8888. EXPECT_EQ(StatusCode::OK_200, res->status);
  8889. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8890. }
  8891. }
  8892. // Disabled due to out-of-memory problem on GitHub Actions
  8893. #ifdef _WIN64
  8894. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8895. // allocate content size larger than 2GB in memory
  8896. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8897. char *content = (char *)malloc(content_size);
  8898. ASSERT_TRUE(content);
  8899. Server svr;
  8900. svr.Get("/foo",
  8901. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8902. res.set_content(content, content_size, "application/octet-stream");
  8903. });
  8904. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8905. auto se = detail::scope_exit([&] {
  8906. svr.stop();
  8907. listen_thread.join();
  8908. if (content) free(content);
  8909. ASSERT_FALSE(svr.is_running());
  8910. });
  8911. svr.wait_until_ready();
  8912. Client cli(HOST, PORT);
  8913. auto res = cli.Get("/foo");
  8914. ASSERT_TRUE(res);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. EXPECT_EQ(content_size, res->body.length());
  8917. }
  8918. #endif
  8919. #ifdef CPPHTTPLIB_SSL_ENABLED
  8920. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8921. Client cli("http://yahoo.com");
  8922. auto res = cli.Get("/");
  8923. ASSERT_TRUE(res);
  8924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8925. cli.set_follow_location(true);
  8926. res = cli.Get("/");
  8927. ASSERT_TRUE(res);
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8930. }
  8931. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8932. Client cli("https://yahoo.com");
  8933. auto res = cli.Get("/");
  8934. ASSERT_TRUE(res);
  8935. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8936. cli.set_follow_location(true);
  8937. res = cli.Get("/");
  8938. ASSERT_TRUE(res);
  8939. EXPECT_EQ(StatusCode::OK_200, res->status);
  8940. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8941. }
  8942. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8943. Client cli("https://yahoo.com");
  8944. auto res = cli.Get("/");
  8945. ASSERT_TRUE(res);
  8946. ASSERT_FALSE(!res);
  8947. ASSERT_TRUE(res);
  8948. ASSERT_FALSE(res == nullptr);
  8949. ASSERT_TRUE(res != nullptr);
  8950. EXPECT_EQ(Error::Success, res.error());
  8951. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8952. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8953. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8954. cli.set_follow_location(true);
  8955. res = cli.Get("/");
  8956. ASSERT_TRUE(res);
  8957. EXPECT_EQ(Error::Success, res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8959. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8962. }
  8963. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8964. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8965. Client cli("https://cdnjs.cloudflare.com");
  8966. auto res =
  8967. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8968. ASSERT_TRUE(res);
  8969. EXPECT_EQ(StatusCode::OK_200, res->status);
  8970. EXPECT_EQ(287630U, res->body.size());
  8971. EXPECT_EQ("application/javascript; charset=utf-8",
  8972. res->get_header_value("Content-Type"));
  8973. }
  8974. #endif
  8975. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8976. #undef REDIR_HOST // Silence compiler warning
  8977. #define REDIR_HOST "https://httpbingo.org"
  8978. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8979. Client cli(REDIR_HOST);
  8980. cli.set_follow_location(true);
  8981. auto res =
  8982. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8983. ASSERT_TRUE(res);
  8984. EXPECT_EQ(StatusCode::OK_200, res->status);
  8985. }
  8986. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8987. Client cli(REDIR_HOST);
  8988. cli.set_follow_location(true);
  8989. Params params;
  8990. params.emplace("url", "http://example.com");
  8991. params.emplace("status_code", "302");
  8992. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8993. ASSERT_TRUE(res);
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. }
  8996. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8997. Client cli(REDIR_HOST);
  8998. cli.set_follow_location(true);
  8999. Params params;
  9000. params.emplace("url", "http://example.com");
  9001. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9002. ASSERT_TRUE(res);
  9003. EXPECT_EQ(StatusCode::OK_200, res->status);
  9004. }
  9005. TEST(HttpToHttpsRedirectTest, CertFile) {
  9006. auto ssl_port = PORT + 1;
  9007. Server svr;
  9008. ASSERT_TRUE(svr.is_valid());
  9009. svr.Get("/index", [&](const Request &, Response &res) {
  9010. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9011. "/index");
  9012. svr.stop();
  9013. });
  9014. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9015. ASSERT_TRUE(ssl_svr.is_valid());
  9016. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9017. res.set_content("test", "text/plain");
  9018. ssl_svr.stop();
  9019. });
  9020. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9021. thread t2 =
  9022. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9023. auto se = detail::scope_exit([&] {
  9024. t2.join();
  9025. t.join();
  9026. ASSERT_FALSE(svr.is_running());
  9027. });
  9028. svr.wait_until_ready();
  9029. ssl_svr.wait_until_ready();
  9030. Client cli("127.0.0.1", PORT);
  9031. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9032. cli.enable_server_certificate_verification(true);
  9033. cli.set_follow_location(true);
  9034. cli.set_connection_timeout(30);
  9035. auto res = cli.Get("/index");
  9036. ASSERT_TRUE(res);
  9037. ASSERT_EQ(StatusCode::OK_200, res->status);
  9038. }
  9039. TEST(SSLClientRedirectTest, CertFile) {
  9040. auto ssl_port = PORT + 1;
  9041. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9042. ASSERT_TRUE(ssl_svr1.is_valid());
  9043. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9044. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9045. "/index");
  9046. ssl_svr1.stop();
  9047. });
  9048. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9049. ASSERT_TRUE(ssl_svr2.is_valid());
  9050. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9051. res.set_content("test", "text/plain");
  9052. ssl_svr2.stop();
  9053. });
  9054. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9055. thread t2 =
  9056. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9057. auto se = detail::scope_exit([&] {
  9058. t2.join();
  9059. t.join();
  9060. ASSERT_FALSE(ssl_svr1.is_running());
  9061. });
  9062. ssl_svr1.wait_until_ready();
  9063. ssl_svr2.wait_until_ready();
  9064. SSLClient cli("127.0.0.1", PORT);
  9065. std::string cert;
  9066. read_file(SERVER_CERT2_FILE, cert);
  9067. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9068. cli.enable_server_certificate_verification(true);
  9069. cli.set_follow_location(true);
  9070. cli.set_connection_timeout(30);
  9071. auto res = cli.Get("/index");
  9072. ASSERT_TRUE(res);
  9073. ASSERT_EQ(StatusCode::OK_200, res->status);
  9074. }
  9075. #endif
  9076. #ifdef CPPHTTPLIB_SSL_ENABLED
  9077. // Test that set_ca_cert_store() skips system certs (consistent with
  9078. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9079. // should be trusted - system certs should NOT be loaded.
  9080. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9081. // Load a specific cert that is NOT a system CA cert
  9082. std::string cert;
  9083. read_file(SERVER_CERT2_FILE, cert);
  9084. SSLClient cli("google.com");
  9085. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9086. cli.enable_server_certificate_verification(true);
  9087. // This should FAIL because:
  9088. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9089. // 2. System certs should NOT be loaded when custom store is set
  9090. // If system certs WERE loaded, this would succeed
  9091. auto res = cli.Get("/");
  9092. ASSERT_FALSE(res);
  9093. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9094. }
  9095. TEST(MultipartFormDataTest, LargeData) {
  9096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9097. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9098. const ContentReader &content_reader) {
  9099. if (req.is_multipart_form_data()) {
  9100. std::vector<FormData> items;
  9101. content_reader(
  9102. [&](const FormData &file) {
  9103. items.push_back(file);
  9104. return true;
  9105. },
  9106. [&](const char *data, size_t data_length) {
  9107. items.back().content.append(data, data_length);
  9108. return true;
  9109. });
  9110. EXPECT_TRUE(std::string(items[0].name) == "document");
  9111. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9112. EXPECT_TRUE(items[0].filename == "2MB_data");
  9113. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9114. EXPECT_TRUE(items[1].name == "hello");
  9115. EXPECT_TRUE(items[1].content == "world");
  9116. EXPECT_TRUE(items[1].filename == "");
  9117. EXPECT_TRUE(items[1].content_type == "");
  9118. } else {
  9119. std::string body;
  9120. content_reader([&](const char *data, size_t data_length) {
  9121. body.append(data, data_length);
  9122. return true;
  9123. });
  9124. }
  9125. });
  9126. auto port = svr.bind_to_any_port(HOST);
  9127. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9128. auto se = detail::scope_exit([&] {
  9129. svr.stop();
  9130. t.join();
  9131. ASSERT_FALSE(svr.is_running());
  9132. });
  9133. svr.wait_until_ready();
  9134. {
  9135. std::string data(1024 * 1024 * 2, '.');
  9136. std::stringstream buffer;
  9137. buffer << data;
  9138. SSLClient cli(HOST, port);
  9139. cli.enable_server_certificate_verification(false);
  9140. UploadFormDataItems items{
  9141. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9142. {"hello", "world", "", ""},
  9143. };
  9144. auto res = cli.Post("/post", items);
  9145. ASSERT_TRUE(res);
  9146. ASSERT_EQ(StatusCode::OK_200, res->status);
  9147. }
  9148. }
  9149. TEST(MultipartFormDataTest, DataProviderItems) {
  9150. std::random_device seed_gen;
  9151. std::mt19937 random(seed_gen());
  9152. std::string rand1;
  9153. rand1.resize(1000);
  9154. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9155. std::string rand2;
  9156. rand2.resize(3000);
  9157. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9159. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9160. const ContentReader &content_reader) {
  9161. ASSERT_FALSE(req.is_multipart_form_data());
  9162. std::string body;
  9163. content_reader([&](const char *data, size_t data_length) {
  9164. body.append(data, data_length);
  9165. return true;
  9166. });
  9167. EXPECT_EQ(body, "");
  9168. });
  9169. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9170. const ContentReader &content_reader) {
  9171. ASSERT_TRUE(req.is_multipart_form_data());
  9172. std::vector<FormData> items;
  9173. content_reader(
  9174. [&](const FormData &file) {
  9175. items.push_back(file);
  9176. return true;
  9177. },
  9178. [&](const char *data, size_t data_length) {
  9179. items.back().content.append(data, data_length);
  9180. return true;
  9181. });
  9182. ASSERT_TRUE(items.size() == 2);
  9183. EXPECT_EQ(std::string(items[0].name), "name1");
  9184. EXPECT_EQ(items[0].content, "Testing123");
  9185. EXPECT_EQ(items[0].filename, "filename1");
  9186. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9187. EXPECT_EQ(items[1].name, "name2");
  9188. EXPECT_EQ(items[1].content, "Testing456");
  9189. EXPECT_EQ(items[1].filename, "");
  9190. EXPECT_EQ(items[1].content_type, "");
  9191. });
  9192. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9193. const ContentReader &content_reader) {
  9194. ASSERT_TRUE(req.is_multipart_form_data());
  9195. std::vector<FormData> items;
  9196. content_reader(
  9197. [&](const FormData &file) {
  9198. items.push_back(file);
  9199. return true;
  9200. },
  9201. [&](const char *data, size_t data_length) {
  9202. items.back().content.append(data, data_length);
  9203. return true;
  9204. });
  9205. ASSERT_TRUE(items.size() == 2);
  9206. EXPECT_EQ(items[0].name, "name3");
  9207. EXPECT_EQ(items[0].content, rand1);
  9208. EXPECT_EQ(items[0].filename, "filename3");
  9209. EXPECT_EQ(items[0].content_type, "");
  9210. EXPECT_EQ(items[1].name, "name4");
  9211. EXPECT_EQ(items[1].content, rand2);
  9212. EXPECT_EQ(items[1].filename, "filename4");
  9213. EXPECT_EQ(items[1].content_type, "");
  9214. });
  9215. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9216. const ContentReader &content_reader) {
  9217. ASSERT_TRUE(req.is_multipart_form_data());
  9218. std::vector<FormData> items;
  9219. content_reader(
  9220. [&](const FormData &file) {
  9221. items.push_back(file);
  9222. return true;
  9223. },
  9224. [&](const char *data, size_t data_length) {
  9225. items.back().content.append(data, data_length);
  9226. return true;
  9227. });
  9228. ASSERT_TRUE(items.size() == 4);
  9229. EXPECT_EQ(std::string(items[0].name), "name1");
  9230. EXPECT_EQ(items[0].content, "Testing123");
  9231. EXPECT_EQ(items[0].filename, "filename1");
  9232. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9233. EXPECT_EQ(items[1].name, "name2");
  9234. EXPECT_EQ(items[1].content, "Testing456");
  9235. EXPECT_EQ(items[1].filename, "");
  9236. EXPECT_EQ(items[1].content_type, "");
  9237. EXPECT_EQ(items[2].name, "name3");
  9238. EXPECT_EQ(items[2].content, rand1);
  9239. EXPECT_EQ(items[2].filename, "filename3");
  9240. EXPECT_EQ(items[2].content_type, "");
  9241. EXPECT_EQ(items[3].name, "name4");
  9242. EXPECT_EQ(items[3].content, rand2);
  9243. EXPECT_EQ(items[3].filename, "filename4");
  9244. EXPECT_EQ(items[3].content_type, "");
  9245. });
  9246. auto port = svr.bind_to_any_port("localhost");
  9247. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9248. auto se = detail::scope_exit([&] {
  9249. svr.stop();
  9250. t.join();
  9251. ASSERT_FALSE(svr.is_running());
  9252. });
  9253. svr.wait_until_ready();
  9254. {
  9255. SSLClient cli("localhost", port);
  9256. cli.enable_server_certificate_verification(false);
  9257. UploadFormDataItems items{
  9258. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9259. {"name2", "Testing456", "", ""}, // not a file
  9260. };
  9261. {
  9262. auto res = cli.Post("/post-none", {}, {}, {});
  9263. ASSERT_TRUE(res);
  9264. ASSERT_EQ(StatusCode::OK_200, res->status);
  9265. }
  9266. FormDataProviderItems providers;
  9267. {
  9268. auto res =
  9269. cli.Post("/post-items", {}, items, providers); // empty providers
  9270. ASSERT_TRUE(res);
  9271. ASSERT_EQ(StatusCode::OK_200, res->status);
  9272. }
  9273. providers.push_back({"name3",
  9274. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9275. // test the offset is given correctly at each step
  9276. if (!offset)
  9277. sink.os.write(rand1.data(), 30);
  9278. else if (offset == 30)
  9279. sink.os.write(rand1.data() + 30, 300);
  9280. else if (offset == 330)
  9281. sink.os.write(rand1.data() + 330, 670);
  9282. else if (offset == rand1.size())
  9283. sink.done();
  9284. return true;
  9285. },
  9286. "filename3",
  9287. {}});
  9288. providers.push_back({"name4",
  9289. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9290. // test the offset is given correctly at each step
  9291. if (!offset)
  9292. sink.os.write(rand2.data(), 2000);
  9293. else if (offset == 2000)
  9294. sink.os.write(rand2.data() + 2000, 1);
  9295. else if (offset == 2001)
  9296. sink.os.write(rand2.data() + 2001, 999);
  9297. else if (offset == rand2.size())
  9298. sink.done();
  9299. return true;
  9300. },
  9301. "filename4",
  9302. {}});
  9303. {
  9304. auto res = cli.Post("/post-providers", {}, {}, providers);
  9305. ASSERT_TRUE(res);
  9306. ASSERT_EQ(StatusCode::OK_200, res->status);
  9307. }
  9308. {
  9309. auto res = cli.Post("/post-both", {}, items, providers);
  9310. ASSERT_TRUE(res);
  9311. ASSERT_EQ(StatusCode::OK_200, res->status);
  9312. }
  9313. }
  9314. }
  9315. TEST(MultipartFormDataTest, BadHeader) {
  9316. Server svr;
  9317. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9318. res.set_content("ok", "text/plain");
  9319. });
  9320. thread t = thread([&] { svr.listen(HOST, PORT); });
  9321. auto se = detail::scope_exit([&] {
  9322. svr.stop();
  9323. t.join();
  9324. ASSERT_FALSE(svr.is_running());
  9325. });
  9326. svr.wait_until_ready();
  9327. const std::string body =
  9328. "This is the preamble. It is to be ignored, though it\r\n"
  9329. "is a handy place for composition agents to include an\r\n"
  9330. "explanatory note to non-MIME conformant readers.\r\n"
  9331. "\r\n"
  9332. "\r\n"
  9333. "--simple boundary\r\n"
  9334. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9335. ": BAD...\r\n"
  9336. "\r\n"
  9337. "value1\r\n"
  9338. "--simple boundary\r\n"
  9339. "Content-Disposition: form-data; name=\"field2\"; "
  9340. "filename=\"example.txt\"\r\n"
  9341. "\r\n"
  9342. "value2\r\n"
  9343. "--simple boundary--\r\n"
  9344. "This is the epilogue. It is also to be ignored.\r\n";
  9345. std::string content_type =
  9346. R"(multipart/form-data; boundary="simple boundary")";
  9347. Client cli(HOST, PORT);
  9348. auto res = cli.Post("/post", body, content_type.c_str());
  9349. ASSERT_TRUE(res);
  9350. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9351. }
  9352. TEST(MultipartFormDataTest, WithPreamble) {
  9353. Server svr;
  9354. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9355. res.set_content("ok", "text/plain");
  9356. });
  9357. thread t = thread([&] { svr.listen(HOST, PORT); });
  9358. auto se = detail::scope_exit([&] {
  9359. svr.stop();
  9360. t.join();
  9361. ASSERT_FALSE(svr.is_running());
  9362. });
  9363. svr.wait_until_ready();
  9364. const std::string body =
  9365. "This is the preamble. It is to be ignored, though it\r\n"
  9366. "is a handy place for composition agents to include an\r\n"
  9367. "explanatory note to non-MIME conformant readers.\r\n"
  9368. "\r\n"
  9369. "\r\n"
  9370. "--simple boundary\r\n"
  9371. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9372. "\r\n"
  9373. "value1\r\n"
  9374. "--simple boundary\r\n"
  9375. "Content-Disposition: form-data; name=\"field2\"; "
  9376. "filename=\"example.txt\"\r\n"
  9377. "\r\n"
  9378. "value2\r\n"
  9379. "--simple boundary--\r\n"
  9380. "This is the epilogue. It is also to be ignored.\r\n";
  9381. std::string content_type =
  9382. R"(multipart/form-data; boundary="simple boundary")";
  9383. Client cli(HOST, PORT);
  9384. auto res = cli.Post("/post", body, content_type.c_str());
  9385. ASSERT_TRUE(res);
  9386. EXPECT_EQ(StatusCode::OK_200, res->status);
  9387. }
  9388. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9390. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9391. const ContentReader &content_reader) {
  9392. if (req.is_multipart_form_data()) {
  9393. std::vector<FormData> items;
  9394. content_reader(
  9395. [&](const FormData &file) {
  9396. items.push_back(file);
  9397. return true;
  9398. },
  9399. [&](const char *data, size_t data_length) {
  9400. items.back().content.append(data, data_length);
  9401. return true;
  9402. });
  9403. EXPECT_TRUE(std::string(items[0].name) == "document");
  9404. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9405. EXPECT_TRUE(items[0].filename == "2MB_data");
  9406. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9407. EXPECT_TRUE(items[1].name == "hello");
  9408. EXPECT_TRUE(items[1].content == "world");
  9409. EXPECT_TRUE(items[1].filename == "");
  9410. EXPECT_TRUE(items[1].content_type == "");
  9411. } else {
  9412. std::string body;
  9413. content_reader([&](const char *data, size_t data_length) {
  9414. body.append(data, data_length);
  9415. return true;
  9416. });
  9417. }
  9418. });
  9419. auto port = svr.bind_to_any_port("localhost");
  9420. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9421. auto se = detail::scope_exit([&] {
  9422. svr.stop();
  9423. t.join();
  9424. ASSERT_FALSE(svr.is_running());
  9425. });
  9426. svr.wait_until_ready();
  9427. {
  9428. std::string data(1024 * 1024 * 2, '.');
  9429. std::stringstream buffer;
  9430. buffer << data;
  9431. SSLClient cli("localhost", port);
  9432. cli.enable_server_certificate_verification(false);
  9433. UploadFormDataItems items{
  9434. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9435. {"hello", "world", "", ""},
  9436. };
  9437. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9438. ASSERT_TRUE(res);
  9439. ASSERT_EQ(StatusCode::OK_200, res->status);
  9440. }
  9441. }
  9442. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9443. std::string data(1024 * 1024 * 2, '&');
  9444. std::stringstream buffer;
  9445. buffer << data;
  9446. Client cli("https://localhost:8080");
  9447. UploadFormDataItems items{
  9448. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9449. {"hello", "world", "", ""},
  9450. };
  9451. for (const char &c : " \t\r\n") {
  9452. auto res =
  9453. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9454. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9455. ASSERT_FALSE(res);
  9456. }
  9457. }
  9458. TEST(MultipartFormDataTest, PutFormData) {
  9459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9460. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9461. const ContentReader &content_reader) {
  9462. if (req.is_multipart_form_data()) {
  9463. std::vector<FormData> items;
  9464. content_reader(
  9465. [&](const FormData &file) {
  9466. items.push_back(file);
  9467. return true;
  9468. },
  9469. [&](const char *data, size_t data_length) {
  9470. items.back().content.append(data, data_length);
  9471. return true;
  9472. });
  9473. EXPECT_TRUE(std::string(items[0].name) == "document");
  9474. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9475. EXPECT_TRUE(items[0].filename == "2MB_data");
  9476. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9477. EXPECT_TRUE(items[1].name == "hello");
  9478. EXPECT_TRUE(items[1].content == "world");
  9479. EXPECT_TRUE(items[1].filename == "");
  9480. EXPECT_TRUE(items[1].content_type == "");
  9481. } else {
  9482. std::string body;
  9483. content_reader([&](const char *data, size_t data_length) {
  9484. body.append(data, data_length);
  9485. return true;
  9486. });
  9487. }
  9488. });
  9489. auto port = svr.bind_to_any_port("localhost");
  9490. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. {
  9498. std::string data(1024 * 1024 * 2, '&');
  9499. std::stringstream buffer;
  9500. buffer << data;
  9501. SSLClient cli("localhost", port);
  9502. cli.enable_server_certificate_verification(false);
  9503. UploadFormDataItems items{
  9504. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9505. {"hello", "world", "", ""},
  9506. };
  9507. auto res = cli.Put("/put", items);
  9508. ASSERT_TRUE(res);
  9509. ASSERT_EQ(StatusCode::OK_200, res->status);
  9510. }
  9511. }
  9512. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9514. svr.Put("/put_customboundary",
  9515. [&](const Request &req, const Response & /*res*/,
  9516. const ContentReader &content_reader) {
  9517. if (req.is_multipart_form_data()) {
  9518. std::vector<FormData> items;
  9519. content_reader(
  9520. [&](const FormData &file) {
  9521. items.push_back(file);
  9522. return true;
  9523. },
  9524. [&](const char *data, size_t data_length) {
  9525. items.back().content.append(data, data_length);
  9526. return true;
  9527. });
  9528. EXPECT_TRUE(std::string(items[0].name) == "document");
  9529. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9530. EXPECT_TRUE(items[0].filename == "2MB_data");
  9531. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9532. EXPECT_TRUE(items[1].name == "hello");
  9533. EXPECT_TRUE(items[1].content == "world");
  9534. EXPECT_TRUE(items[1].filename == "");
  9535. EXPECT_TRUE(items[1].content_type == "");
  9536. } else {
  9537. std::string body;
  9538. content_reader([&](const char *data, size_t data_length) {
  9539. body.append(data, data_length);
  9540. return true;
  9541. });
  9542. }
  9543. });
  9544. auto port = svr.bind_to_any_port("localhost");
  9545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9546. auto se = detail::scope_exit([&] {
  9547. svr.stop();
  9548. t.join();
  9549. ASSERT_FALSE(svr.is_running());
  9550. });
  9551. svr.wait_until_ready();
  9552. {
  9553. std::string data(1024 * 1024 * 2, '&');
  9554. std::stringstream buffer;
  9555. buffer << data;
  9556. SSLClient cli("localhost", port);
  9557. cli.enable_server_certificate_verification(false);
  9558. UploadFormDataItems items{
  9559. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9560. {"hello", "world", "", ""},
  9561. };
  9562. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9563. ASSERT_TRUE(res);
  9564. ASSERT_EQ(StatusCode::OK_200, res->status);
  9565. }
  9566. }
  9567. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9568. std::string data(1024 * 1024 * 2, '&');
  9569. std::stringstream buffer;
  9570. buffer << data;
  9571. Client cli("https://localhost:8080");
  9572. cli.enable_server_certificate_verification(false);
  9573. UploadFormDataItems items{
  9574. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9575. {"hello", "world", "", ""},
  9576. };
  9577. for (const char &c : " \t\r\n") {
  9578. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9579. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9580. ASSERT_FALSE(res);
  9581. }
  9582. }
  9583. TEST(MultipartFormDataTest, AlternateFilename) {
  9584. auto handled = false;
  9585. Server svr;
  9586. svr.Post("/test", [&](const Request &req, Response &res) {
  9587. ASSERT_EQ(2u, req.form.files.size());
  9588. ASSERT_EQ(1u, req.form.fields.size());
  9589. // Test files
  9590. const auto &file1 = req.form.get_file("file1");
  9591. ASSERT_EQ("file1", file1.name);
  9592. ASSERT_EQ("A.txt", file1.filename);
  9593. ASSERT_EQ("text/plain", file1.content_type);
  9594. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9595. const auto &file2 = req.form.get_file("file2");
  9596. ASSERT_EQ("file2", file2.name);
  9597. ASSERT_EQ("a.html", file2.filename);
  9598. ASSERT_EQ("text/html", file2.content_type);
  9599. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9600. file2.content);
  9601. // Test text field
  9602. const auto &text = req.form.get_field("text");
  9603. ASSERT_EQ("text default", text);
  9604. res.set_content("ok", "text/plain");
  9605. handled = true;
  9606. });
  9607. thread t = thread([&] { svr.listen(HOST, PORT); });
  9608. auto se = detail::scope_exit([&] {
  9609. svr.stop();
  9610. t.join();
  9611. ASSERT_FALSE(svr.is_running());
  9612. ASSERT_TRUE(handled);
  9613. });
  9614. svr.wait_until_ready();
  9615. auto req = "POST /test HTTP/1.1\r\n"
  9616. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9617. "Content-Length: 399\r\n"
  9618. "\r\n"
  9619. "----------\r\n"
  9620. "Content-Disposition: form-data; name=\"text\"\r\n"
  9621. "\r\n"
  9622. "text default\r\n"
  9623. "----------\r\n"
  9624. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9625. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9626. "Content-Type: text/plain\r\n"
  9627. "\r\n"
  9628. "Content of a.txt.\r\n"
  9629. "\r\n"
  9630. "----------\r\n"
  9631. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9632. "\"a.html\"\r\n"
  9633. "Content-Type: text/html\r\n"
  9634. "\r\n"
  9635. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9636. "\r\n"
  9637. "------------\r\n";
  9638. ASSERT_TRUE(send_request(1, req));
  9639. }
  9640. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9641. auto handled = false;
  9642. Server svr;
  9643. svr.Post("/test", [&](const Request &req, Response &) {
  9644. ASSERT_EQ(2u, req.form.fields.size());
  9645. const auto &text1 = req.form.get_field("text1");
  9646. ASSERT_EQ("text1", text1);
  9647. const auto &text2 = req.form.get_field("text2");
  9648. ASSERT_EQ("text2", text2);
  9649. handled = true;
  9650. });
  9651. thread t = thread([&] { svr.listen(HOST, PORT); });
  9652. auto se = detail::scope_exit([&] {
  9653. svr.stop();
  9654. t.join();
  9655. ASSERT_FALSE(svr.is_running());
  9656. ASSERT_TRUE(handled);
  9657. });
  9658. svr.wait_until_ready();
  9659. auto req = "POST /test HTTP/1.1\r\n"
  9660. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9661. "Content-Length: 146\r\n"
  9662. "\r\n----------\r\n"
  9663. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9664. "\r\n"
  9665. "text1"
  9666. "\r\n----------\r\n"
  9667. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9668. "\r\n"
  9669. "text2"
  9670. "\r\n------------";
  9671. std::string response;
  9672. ASSERT_TRUE(send_request(1, req, &response));
  9673. ASSERT_EQ("200", response.substr(9, 3));
  9674. }
  9675. TEST(MultipartFormDataTest, ContentLength) {
  9676. auto handled = false;
  9677. Server svr;
  9678. svr.Post("/test", [&](const Request &req, Response &) {
  9679. ASSERT_EQ(2u, req.form.fields.size());
  9680. const auto &text1 = req.form.get_field("text1");
  9681. ASSERT_EQ("text1", text1);
  9682. const auto &text2 = req.form.get_field("text2");
  9683. ASSERT_EQ("text2", text2);
  9684. handled = true;
  9685. });
  9686. thread t = thread([&] { svr.listen(HOST, PORT); });
  9687. auto se = detail::scope_exit([&] {
  9688. svr.stop();
  9689. t.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. ASSERT_TRUE(handled);
  9692. });
  9693. svr.wait_until_ready();
  9694. auto req = "POST /test HTTP/1.1\r\n"
  9695. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9696. "Content-Length: 167\r\n"
  9697. "\r\n----------\r\n"
  9698. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9699. "Content-Length: 5\r\n"
  9700. "\r\n"
  9701. "text1"
  9702. "\r\n----------\r\n"
  9703. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9704. "\r\n"
  9705. "text2"
  9706. "\r\n------------\r\n";
  9707. std::string response;
  9708. ASSERT_TRUE(send_request(1, req, &response));
  9709. ASSERT_EQ("200", response.substr(9, 3));
  9710. }
  9711. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9712. auto handled = false;
  9713. Server svr;
  9714. svr.Post("/test", [&](const Request &req, Response &) {
  9715. ASSERT_EQ(2u, req.form.fields.size());
  9716. const auto &text1 = req.form.get_field("text1");
  9717. ASSERT_EQ("text1", text1);
  9718. // TODO: Add header access for text fields if needed
  9719. const auto &text2 = req.form.get_field("text2");
  9720. ASSERT_EQ("text2", text2);
  9721. // TODO: Header access for text fields needs to be implemented
  9722. // auto &headers = it->second.headers;
  9723. // ASSERT_EQ(3U, headers.size());
  9724. // auto custom_header = headers.find("x-whatever");
  9725. // ASSERT_TRUE(custom_header != headers.end());
  9726. // ASSERT_NE("customvalue", custom_header->second);
  9727. // ASSERT_EQ("CustomValue", custom_header->second);
  9728. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9729. handled = true;
  9730. });
  9731. thread t = thread([&] { svr.listen(HOST, PORT); });
  9732. auto se = detail::scope_exit([&] {
  9733. svr.stop();
  9734. t.join();
  9735. ASSERT_FALSE(svr.is_running());
  9736. ASSERT_TRUE(handled);
  9737. });
  9738. svr.wait_until_ready();
  9739. auto req = "POST /test HTTP/1.1\r\n"
  9740. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9741. "Content-Length: 232\r\n"
  9742. "\r\n----------\r\n"
  9743. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9744. "Content-Length: 5\r\n"
  9745. "X-Test: 1\r\n"
  9746. "\r\n"
  9747. "text1"
  9748. "\r\n----------\r\n"
  9749. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9750. "Content-Type: text/plain\r\n"
  9751. "X-Whatever: CustomValue\r\n"
  9752. "\r\n"
  9753. "text2"
  9754. "\r\n------------\r\n"
  9755. "That should be disregarded. Not even read";
  9756. std::string response;
  9757. ASSERT_TRUE(send_request(1, req, &response));
  9758. ASSERT_EQ("200", response.substr(9, 3));
  9759. }
  9760. TEST(MultipartFormDataTest, LargeHeader) {
  9761. auto handled = false;
  9762. Server svr;
  9763. svr.Post("/test", [&](const Request &req, Response &) {
  9764. ASSERT_EQ(1u, req.form.fields.size());
  9765. const auto &text = req.form.get_field("name1");
  9766. ASSERT_EQ("text1", text);
  9767. handled = true;
  9768. });
  9769. thread t = thread([&] { svr.listen(HOST, PORT); });
  9770. auto se = detail::scope_exit([&] {
  9771. svr.stop();
  9772. t.join();
  9773. ASSERT_FALSE(svr.is_running());
  9774. ASSERT_TRUE(handled);
  9775. });
  9776. svr.wait_until_ready();
  9777. auto boundary = std::string("cpp-httplib-multipart-data");
  9778. std::string content = "--" + boundary +
  9779. "\r\n"
  9780. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9781. "\r\n"
  9782. "text1\r\n"
  9783. "--" +
  9784. boundary + "--\r\n";
  9785. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9786. "Content-Type: multipart/form-data;boundary=" +
  9787. boundary +
  9788. "\r\n"
  9789. "Content-Length: " +
  9790. std::to_string(content.size()) +
  9791. "\r\n"
  9792. "Dummy-Header: ";
  9793. std::string header_suffix = "\r\n"
  9794. "\r\n";
  9795. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9796. size_t header_dummy_size =
  9797. read_buff_size -
  9798. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9799. auto header_dummy = std::string(header_dummy_size, '@');
  9800. auto req = header_prefix + header_dummy + header_suffix + content;
  9801. std::string response;
  9802. ASSERT_TRUE(send_request(1, req, &response));
  9803. ASSERT_EQ("200", response.substr(9, 3));
  9804. }
  9805. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9806. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9807. // (not chunked Transfer-Encoding) after the streaming refactor.
  9808. auto handled = false;
  9809. Server svr;
  9810. svr.Post("/upload", [&](const Request &req, Response &res) {
  9811. auto cl_it = req.headers.find("Content-Length");
  9812. EXPECT_TRUE(cl_it != req.headers.end());
  9813. auto te_it = req.headers.find("Transfer-Encoding");
  9814. EXPECT_TRUE(te_it == req.headers.end());
  9815. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9816. res.set_content("ok", "text/plain");
  9817. handled = true;
  9818. });
  9819. auto port = svr.bind_to_any_port(HOST);
  9820. auto t = thread([&] { svr.listen_after_bind(); });
  9821. auto se = detail::scope_exit([&] {
  9822. svr.stop();
  9823. t.join();
  9824. ASSERT_FALSE(svr.is_running());
  9825. ASSERT_TRUE(handled);
  9826. });
  9827. svr.wait_until_ready();
  9828. UploadFormDataItems items = {
  9829. {"field1", "hello", "", "text/plain"},
  9830. {"file1", "world", "test.txt", "application/octet-stream"},
  9831. };
  9832. Client cli(HOST, port);
  9833. auto res = cli.Post("/upload", {}, items);
  9834. ASSERT_TRUE(res);
  9835. EXPECT_EQ(StatusCode::OK_200, res->status);
  9836. }
  9837. TEST(MultipartFormDataTest, MakeFileProvider) {
  9838. // Verify make_file_provider sends a file's contents correctly.
  9839. const std::string file_content(4096, 'Z');
  9840. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  9841. {
  9842. std::ofstream ofs(tmp_path, std::ios::binary);
  9843. ofs.write(file_content.data(),
  9844. static_cast<std::streamsize>(file_content.size()));
  9845. }
  9846. auto handled = false;
  9847. Server svr;
  9848. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  9849. const ContentReader &content_reader) {
  9850. ASSERT_TRUE(req.is_multipart_form_data());
  9851. std::vector<FormData> items;
  9852. content_reader(
  9853. [&](const FormData &file) {
  9854. items.push_back(file);
  9855. return true;
  9856. },
  9857. [&](const char *data, size_t data_length) {
  9858. items.back().content.append(data, data_length);
  9859. return true;
  9860. });
  9861. ASSERT_EQ(1u, items.size());
  9862. EXPECT_EQ("myfile", items[0].name);
  9863. EXPECT_EQ("data.bin", items[0].filename);
  9864. EXPECT_EQ("application/octet-stream", items[0].content_type);
  9865. EXPECT_EQ(file_content, items[0].content);
  9866. handled = true;
  9867. });
  9868. auto port = svr.bind_to_any_port(HOST);
  9869. auto t = thread([&] { svr.listen_after_bind(); });
  9870. auto se = detail::scope_exit([&] {
  9871. svr.stop();
  9872. t.join();
  9873. ASSERT_FALSE(svr.is_running());
  9874. ASSERT_TRUE(handled);
  9875. std::remove(tmp_path.c_str());
  9876. });
  9877. svr.wait_until_ready();
  9878. FormDataProviderItems providers;
  9879. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  9880. "application/octet-stream"));
  9881. Client cli(HOST, port);
  9882. auto res = cli.Post("/upload", {}, {}, providers);
  9883. ASSERT_TRUE(res);
  9884. EXPECT_EQ(StatusCode::OK_200, res->status);
  9885. }
  9886. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9887. static constexpr unsigned int number_of_tasks{1000000};
  9888. std::atomic_uint count{0};
  9889. std::unique_ptr<TaskQueue> task_queue{
  9890. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9891. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9892. auto queued = task_queue->enqueue(
  9893. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9894. EXPECT_TRUE(queued);
  9895. }
  9896. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9897. task_queue->shutdown();
  9898. #else
  9899. EXPECT_NO_THROW(task_queue->shutdown());
  9900. #endif
  9901. EXPECT_EQ(number_of_tasks, count.load());
  9902. }
  9903. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9904. static constexpr unsigned int number_of_tasks{1000000};
  9905. static constexpr unsigned int qlimit{2};
  9906. unsigned int queued_count{0};
  9907. std::atomic_uint count{0};
  9908. std::unique_ptr<TaskQueue> task_queue{
  9909. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  9910. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9911. if (task_queue->enqueue(
  9912. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9913. queued_count++;
  9914. }
  9915. }
  9916. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9917. task_queue->shutdown();
  9918. #else
  9919. EXPECT_NO_THROW(task_queue->shutdown());
  9920. #endif
  9921. EXPECT_EQ(queued_count, count.load());
  9922. EXPECT_TRUE(queued_count <= number_of_tasks);
  9923. EXPECT_TRUE(queued_count >= qlimit);
  9924. }
  9925. TEST(TaskQueueTest, MaxQueuedRequests) {
  9926. static constexpr unsigned int qlimit{3};
  9927. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  9928. std::condition_variable sem_cv;
  9929. std::mutex sem_mtx;
  9930. int credits = 0;
  9931. bool queued;
  9932. /* Fill up the queue with tasks that will block until we give them credits to
  9933. * complete. */
  9934. for (unsigned int n = 0; n <= qlimit;) {
  9935. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9936. std::unique_lock<std::mutex> lock(sem_mtx);
  9937. while (credits <= 0) {
  9938. sem_cv.wait(lock);
  9939. }
  9940. /* Consume the credit and signal the test code if they are all gone. */
  9941. if (--credits == 0) { sem_cv.notify_one(); }
  9942. });
  9943. if (n < qlimit) {
  9944. /* The first qlimit enqueues must succeed. */
  9945. EXPECT_TRUE(queued);
  9946. } else {
  9947. /* The last one will succeed only when the worker thread
  9948. * starts and dequeues the first blocking task. Although
  9949. * not necessary for the correctness of this test, we sleep for
  9950. * a short while to avoid busy waiting. */
  9951. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9952. }
  9953. if (queued) { n++; }
  9954. }
  9955. /* Further enqueues must fail since the queue is full. */
  9956. for (auto i = 0; i < 4; i++) {
  9957. queued = task_queue->enqueue([] {});
  9958. EXPECT_FALSE(queued);
  9959. }
  9960. /* Give the credits to allow the previous tasks to complete. */
  9961. {
  9962. std::unique_lock<std::mutex> lock(sem_mtx);
  9963. credits += qlimit + 1;
  9964. }
  9965. sem_cv.notify_all();
  9966. /* Wait for all the credits to be consumed. */
  9967. {
  9968. std::unique_lock<std::mutex> lock(sem_mtx);
  9969. while (credits > 0) {
  9970. sem_cv.wait(lock);
  9971. }
  9972. }
  9973. /* Check that we are able again to enqueue at least qlimit tasks. */
  9974. for (unsigned int i = 0; i < qlimit; i++) {
  9975. queued = task_queue->enqueue([] {});
  9976. EXPECT_TRUE(queued);
  9977. }
  9978. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9979. task_queue->shutdown();
  9980. #else
  9981. EXPECT_NO_THROW(task_queue->shutdown());
  9982. #endif
  9983. }
  9984. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9985. Server svr;
  9986. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9987. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9988. });
  9989. svr.Get("/hello", [](const Request &req, Response &res) {
  9990. res.set_content(req.get_param_value("key"), "text/plain");
  9991. });
  9992. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. thread.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. });
  9998. svr.wait_until_ready();
  9999. {
  10000. Client cli(HOST, PORT);
  10001. cli.set_follow_location(true);
  10002. auto res = cli.Get("/");
  10003. ASSERT_TRUE(res);
  10004. EXPECT_EQ(StatusCode::OK_200, res->status);
  10005. EXPECT_EQ("val&key2=val2", res->body);
  10006. }
  10007. }
  10008. #endif
  10009. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10010. Server svr;
  10011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10012. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10013. });
  10014. svr.Get("/hello", [](const Request &req, Response &res) {
  10015. res.set_content(req.get_param_value("key"), "text/plain");
  10016. });
  10017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10018. auto se = detail::scope_exit([&] {
  10019. svr.stop();
  10020. thread.join();
  10021. ASSERT_FALSE(svr.is_running());
  10022. });
  10023. svr.wait_until_ready();
  10024. {
  10025. Client cli(HOST, PORT);
  10026. cli.set_follow_location(true);
  10027. auto res = cli.Get("/");
  10028. ASSERT_TRUE(res);
  10029. EXPECT_EQ(StatusCode::OK_200, res->status);
  10030. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10031. }
  10032. }
  10033. #ifdef CPPHTTPLIB_SSL_ENABLED
  10034. TEST(RedirectTest, Issue2185_Online) {
  10035. SSLClient client("github.com");
  10036. client.set_follow_location(true);
  10037. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10038. "Coollab-Windows.zip");
  10039. ASSERT_TRUE(res);
  10040. EXPECT_EQ(StatusCode::OK_200, res->status);
  10041. EXPECT_EQ(9920427U, res->body.size());
  10042. }
  10043. #endif
  10044. TEST(VulnerabilityTest, CRLFInjection) {
  10045. Server svr;
  10046. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10047. res.set_content("Hello 1", "text/plain");
  10048. });
  10049. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10050. res.set_content("Hello 2", "text/plain");
  10051. });
  10052. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10053. res.set_content("Hello 3", "text/plain");
  10054. });
  10055. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10056. res.set_content("Hello 4", "text/plain");
  10057. });
  10058. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10059. for (const auto &x : req.headers) {
  10060. auto key = x.first;
  10061. EXPECT_STRNE("evil", key.c_str());
  10062. }
  10063. });
  10064. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10065. auto se = detail::scope_exit([&] {
  10066. svr.stop();
  10067. thread.join();
  10068. ASSERT_FALSE(svr.is_running());
  10069. });
  10070. svr.wait_until_ready();
  10071. {
  10072. Client cli(HOST, PORT);
  10073. cli.Post("/test1", "A=B",
  10074. "application/x-www-form-urlencoded\r\nevil: hello1");
  10075. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10076. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10077. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10078. }
  10079. }
  10080. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10081. auto server_thread = std::thread([] {
  10082. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10083. default_socket_options(srv);
  10084. sockaddr_in addr{};
  10085. addr.sin_family = AF_INET;
  10086. addr.sin_port = htons(PORT + 1);
  10087. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10088. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10089. ::listen(srv, 1);
  10090. sockaddr_in cli_addr{};
  10091. socklen_t cli_len = sizeof(cli_addr);
  10092. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10093. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10094. std::string buf_all;
  10095. char buf[2048];
  10096. ssize_t n;
  10097. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10098. buf_all.append(buf, static_cast<size_t>(n));
  10099. size_t pos;
  10100. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10101. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10102. auto e = request_block.find("\r\n");
  10103. if (e != std::string::npos) {
  10104. auto request_line = request_block.substr(0, e);
  10105. std::string msg =
  10106. "CRLF injection detected in request line: '" + request_line + "'";
  10107. EXPECT_FALSE(true) << msg;
  10108. }
  10109. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10110. ::send(cli,
  10111. #ifdef _WIN32
  10112. static_cast<const char *>(resp.c_str()),
  10113. static_cast<int>(resp.size()),
  10114. #else
  10115. resp.c_str(), resp.size(),
  10116. #endif
  10117. 0);
  10118. buf_all.erase(0, pos + 4);
  10119. }
  10120. }
  10121. detail::close_socket(cli);
  10122. detail::close_socket(srv);
  10123. });
  10124. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10125. auto cli = Client("127.0.0.1", PORT + 1);
  10126. auto headers = Headers{
  10127. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10128. {"Connection", "keep-alive"}};
  10129. auto res = cli.Get("/hi", headers);
  10130. EXPECT_FALSE(res);
  10131. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10132. server_thread.join();
  10133. }
  10134. TEST(PathParamsTest, StaticMatch) {
  10135. const auto pattern = "/users/all";
  10136. detail::PathParamsMatcher matcher(pattern);
  10137. Request request;
  10138. request.path = "/users/all";
  10139. ASSERT_TRUE(matcher.match(request));
  10140. std::unordered_map<std::string, std::string> expected_params = {};
  10141. EXPECT_EQ(request.path_params, expected_params);
  10142. }
  10143. TEST(PathParamsTest, StaticMismatch) {
  10144. const auto pattern = "/users/all";
  10145. detail::PathParamsMatcher matcher(pattern);
  10146. Request request;
  10147. request.path = "/users/1";
  10148. ASSERT_FALSE(matcher.match(request));
  10149. }
  10150. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10151. const auto pattern = "/users/:id/subscriptions";
  10152. detail::PathParamsMatcher matcher(pattern);
  10153. Request request;
  10154. request.path = "/users/42/subscriptions";
  10155. ASSERT_TRUE(matcher.match(request));
  10156. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10157. EXPECT_EQ(request.path_params, expected_params);
  10158. }
  10159. TEST(PathParamsTest, SingleParamInTheEnd) {
  10160. const auto pattern = "/users/:id";
  10161. detail::PathParamsMatcher matcher(pattern);
  10162. Request request;
  10163. request.path = "/users/24";
  10164. ASSERT_TRUE(matcher.match(request));
  10165. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10166. EXPECT_EQ(request.path_params, expected_params);
  10167. }
  10168. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10169. const auto pattern = "/users/:id/";
  10170. detail::PathParamsMatcher matcher(pattern);
  10171. Request request;
  10172. request.path = "/users/42/";
  10173. ASSERT_TRUE(matcher.match(request));
  10174. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10175. EXPECT_EQ(request.path_params, expected_params);
  10176. }
  10177. TEST(PathParamsTest, EmptyParam) {
  10178. const auto pattern = "/users/:id/";
  10179. detail::PathParamsMatcher matcher(pattern);
  10180. Request request;
  10181. request.path = "/users//";
  10182. ASSERT_TRUE(matcher.match(request));
  10183. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10184. EXPECT_EQ(request.path_params, expected_params);
  10185. }
  10186. TEST(PathParamsTest, FragmentMismatch) {
  10187. const auto pattern = "/users/:id/";
  10188. detail::PathParamsMatcher matcher(pattern);
  10189. Request request;
  10190. request.path = "/admins/24/";
  10191. ASSERT_FALSE(matcher.match(request));
  10192. }
  10193. TEST(PathParamsTest, ExtraFragments) {
  10194. const auto pattern = "/users/:id";
  10195. detail::PathParamsMatcher matcher(pattern);
  10196. Request request;
  10197. request.path = "/users/42/subscriptions";
  10198. ASSERT_FALSE(matcher.match(request));
  10199. }
  10200. TEST(PathParamsTest, MissingTrailingParam) {
  10201. const auto pattern = "/users/:id";
  10202. detail::PathParamsMatcher matcher(pattern);
  10203. Request request;
  10204. request.path = "/users";
  10205. ASSERT_FALSE(matcher.match(request));
  10206. }
  10207. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10208. const auto pattern = "/users/:id/subscriptions";
  10209. detail::PathParamsMatcher matcher(pattern);
  10210. Request request;
  10211. request.path = "/users/subscriptions";
  10212. ASSERT_FALSE(matcher.match(request));
  10213. }
  10214. TEST(PathParamsTest, MultipleParams) {
  10215. const auto pattern = "/users/:userid/subscriptions/:subid";
  10216. detail::PathParamsMatcher matcher(pattern);
  10217. Request request;
  10218. request.path = "/users/42/subscriptions/2";
  10219. ASSERT_TRUE(matcher.match(request));
  10220. std::unordered_map<std::string, std::string> expected_params = {
  10221. {"userid", "42"}, {"subid", "2"}};
  10222. EXPECT_EQ(request.path_params, expected_params);
  10223. }
  10224. TEST(PathParamsTest, SequenceOfParams) {
  10225. const auto pattern = "/values/:x/:y/:z";
  10226. detail::PathParamsMatcher matcher(pattern);
  10227. Request request;
  10228. request.path = "/values/1/2/3";
  10229. ASSERT_TRUE(matcher.match(request));
  10230. std::unordered_map<std::string, std::string> expected_params = {
  10231. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10232. EXPECT_EQ(request.path_params, expected_params);
  10233. }
  10234. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10235. const auto pattern = "/prefix:suffix";
  10236. detail::PathParamsMatcher matcher(pattern);
  10237. Request request;
  10238. request.path = "/prefix:suffix";
  10239. ASSERT_TRUE(matcher.match(request));
  10240. const std::unordered_map<std::string, std::string> expected_params = {};
  10241. EXPECT_EQ(request.path_params, expected_params);
  10242. }
  10243. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10244. // If ipv6 regex working, regex match codepath is taken.
  10245. // else port will default to 80 in Client impl
  10246. int clientImplMagicPort = 80;
  10247. int port = 4321;
  10248. // above ports must be different to avoid false negative
  10249. EXPECT_NE(clientImplMagicPort, port);
  10250. std::string ipV6TestURL = "http://[ff06::c3]";
  10251. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10252. CLIENT_PRIVATE_KEY_FILE);
  10253. EXPECT_EQ(cli.port(), port);
  10254. }
  10255. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10256. auto file_path = "./www/dir/index.html";
  10257. auto dir_path = "./www/dir";
  10258. detail::FileStat stat_file(file_path);
  10259. EXPECT_TRUE(stat_file.is_file());
  10260. EXPECT_FALSE(stat_file.is_dir());
  10261. detail::FileStat stat_dir(dir_path);
  10262. EXPECT_FALSE(stat_dir.is_file());
  10263. EXPECT_TRUE(stat_dir.is_dir());
  10264. }
  10265. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10266. // IPv4 with default HTTP port (80)
  10267. EXPECT_EQ("example.com",
  10268. detail::make_host_and_port_string("example.com", 80, false));
  10269. // IPv4 with default HTTPS port (443)
  10270. EXPECT_EQ("example.com",
  10271. detail::make_host_and_port_string("example.com", 443, true));
  10272. // IPv4 with non-default HTTP port
  10273. EXPECT_EQ("example.com:8080",
  10274. detail::make_host_and_port_string("example.com", 8080, false));
  10275. // IPv4 with non-default HTTPS port
  10276. EXPECT_EQ("example.com:8443",
  10277. detail::make_host_and_port_string("example.com", 8443, true));
  10278. // IPv6 with default HTTP port (80)
  10279. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10280. // IPv6 with default HTTPS port (443)
  10281. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10282. // IPv6 with non-default HTTP port
  10283. EXPECT_EQ("[::1]:8080",
  10284. detail::make_host_and_port_string("::1", 8080, false));
  10285. // IPv6 with non-default HTTPS port
  10286. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10287. // IPv6 full address with default port
  10288. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10289. detail::make_host_and_port_string(
  10290. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10291. // IPv6 full address with non-default port
  10292. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10293. detail::make_host_and_port_string(
  10294. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10295. // IPv6 localhost with non-default port
  10296. EXPECT_EQ("[::1]:3000",
  10297. detail::make_host_and_port_string("::1", 3000, false));
  10298. // IPv6 with zone ID (link-local address) with default port
  10299. EXPECT_EQ("[fe80::1%eth0]",
  10300. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10301. // IPv6 with zone ID (link-local address) with non-default port
  10302. EXPECT_EQ("[fe80::1%eth0]:8080",
  10303. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10304. // Edge case: Port 443 with is_ssl=false (should add port)
  10305. EXPECT_EQ("example.com:443",
  10306. detail::make_host_and_port_string("example.com", 443, false));
  10307. // Edge case: Port 80 with is_ssl=true (should add port)
  10308. EXPECT_EQ("example.com:80",
  10309. detail::make_host_and_port_string("example.com", 80, true));
  10310. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10311. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10312. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10313. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10314. // Security fix: Already bracketed IPv6 should not get double brackets
  10315. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10316. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10317. EXPECT_EQ("[::1]:8080",
  10318. detail::make_host_and_port_string("[::1]", 8080, false));
  10319. EXPECT_EQ("[2001:db8::1]:8080",
  10320. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10321. EXPECT_EQ("[fe80::1%eth0]",
  10322. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10323. EXPECT_EQ("[fe80::1%eth0]:8080",
  10324. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10325. // Edge case: Empty host (should return as-is)
  10326. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10327. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10328. // This is a known limitation but shouldn't crash
  10329. EXPECT_EQ("[host:name]",
  10330. detail::make_host_and_port_string("host:name", 80, false));
  10331. // Port number edge cases (no validation, but should not crash)
  10332. EXPECT_EQ("example.com:0",
  10333. detail::make_host_and_port_string("example.com", 0, false));
  10334. EXPECT_EQ("example.com:-1",
  10335. detail::make_host_and_port_string("example.com", -1, false));
  10336. EXPECT_EQ("example.com:65535",
  10337. detail::make_host_and_port_string("example.com", 65535, false));
  10338. EXPECT_EQ("example.com:65536",
  10339. detail::make_host_and_port_string("example.com", 65536, false));
  10340. }
  10341. #ifdef CPPHTTPLIB_SSL_ENABLED
  10342. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10343. httplib::SSLClient cli("roblox.com", 443);
  10344. cli.set_follow_location(true);
  10345. auto res = cli.Get("/");
  10346. ASSERT_TRUE(res);
  10347. EXPECT_EQ(StatusCode::OK_200, res->status);
  10348. }
  10349. #endif
  10350. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10351. Server svr;
  10352. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10353. EXPECT_EQ(res.status, 400);
  10354. });
  10355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10356. auto se = detail::scope_exit([&] {
  10357. svr.stop();
  10358. thread.join();
  10359. ASSERT_FALSE(svr.is_running());
  10360. });
  10361. svr.wait_until_ready();
  10362. Client cli(HOST, PORT);
  10363. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10364. }
  10365. TEST(InvalidHeaderCharsTest, is_field_name) {
  10366. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10367. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10368. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10369. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10370. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10371. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10372. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10373. EXPECT_FALSE(detail::fields::is_field_name(""));
  10374. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10375. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10376. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10377. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10378. }
  10379. TEST(InvalidHeaderCharsTest, is_field_value) {
  10380. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10381. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10382. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10383. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10384. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10385. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10386. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10387. EXPECT_TRUE(detail::fields::is_field_value(""));
  10388. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10389. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10390. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10391. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10392. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10393. }
  10394. TEST(InvalidHeaderCharsTest, OnServer) {
  10395. Server svr;
  10396. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10397. std::string header = "Not Set";
  10398. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10399. res.set_header(header, "value");
  10400. res.set_content("Page Content Page Content", "text/plain");
  10401. });
  10402. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10403. std::string header = "Not Set";
  10404. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10405. res.set_header("X-Test", header);
  10406. res.set_content("Page Content Page Content", "text/plain");
  10407. });
  10408. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10409. auto se = detail::scope_exit([&] {
  10410. svr.stop();
  10411. thread.join();
  10412. ASSERT_FALSE(svr.is_running());
  10413. });
  10414. svr.wait_until_ready();
  10415. Client cli(HOST, PORT);
  10416. {
  10417. auto res = cli.Get(
  10418. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10419. ASSERT_TRUE(res);
  10420. EXPECT_EQ("Page Content Page Content", res->body);
  10421. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10422. }
  10423. {
  10424. auto res = cli.Get(
  10425. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10426. ASSERT_TRUE(res);
  10427. EXPECT_EQ("Page Content Page Content", res->body);
  10428. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10429. }
  10430. }
  10431. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10432. auto handled = false;
  10433. Server svr;
  10434. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10435. thread t = thread([&] { svr.listen(HOST, PORT); });
  10436. auto se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. t.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. ASSERT_FALSE(handled);
  10441. });
  10442. svr.wait_until_ready();
  10443. auto req = "POST /test HTTP/1.1\r\n"
  10444. "Content-Length: x\r\n"
  10445. "\r\n";
  10446. std::string response;
  10447. ASSERT_TRUE(send_request(1, req, &response));
  10448. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10449. response.substr(0, response.find("\r\n")));
  10450. }
  10451. #ifndef _WIN32
  10452. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10453. static constexpr char reject[] = "Unauthorized";
  10454. static constexpr char accept[] = "Upload accepted";
  10455. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10456. Server svr;
  10457. svr.set_expect_100_continue_handler(
  10458. [](const Request & /*req*/, Response &res) {
  10459. res.status = StatusCode::Unauthorized_401;
  10460. res.set_content(reject, "text/plain");
  10461. return res.status;
  10462. });
  10463. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10464. res.set_content(accept, "text/plain");
  10465. });
  10466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10467. auto se = detail::scope_exit([&] {
  10468. svr.stop();
  10469. thread.join();
  10470. ASSERT_FALSE(svr.is_running());
  10471. });
  10472. svr.wait_until_ready();
  10473. {
  10474. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10475. curl_easy_init(), &curl_easy_cleanup};
  10476. ASSERT_NE(curl, nullptr);
  10477. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10478. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10479. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10480. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10481. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10482. &curl_slist_free_all};
  10483. ASSERT_NE(list, nullptr);
  10484. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10485. struct read_data {
  10486. size_t read_size;
  10487. size_t total_size;
  10488. } data = {0, total_size};
  10489. using read_callback_t =
  10490. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10491. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10492. void *userdata) -> size_t {
  10493. read_data *data = (read_data *)userdata;
  10494. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10495. std::fill_n(ptr, size * nmemb, 'A');
  10496. data->read_size += size * nmemb;
  10497. return size * nmemb;
  10498. };
  10499. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10500. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10501. std::vector<char> buffer;
  10502. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10503. using write_callback_t =
  10504. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10505. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10506. void *userdata) -> size_t {
  10507. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10508. buffer->reserve(buffer->size() + size * nmemb + 1);
  10509. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10510. return size * nmemb;
  10511. };
  10512. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10513. {
  10514. const auto res = curl_easy_perform(curl.get());
  10515. ASSERT_EQ(res, CURLE_OK);
  10516. }
  10517. {
  10518. auto response_code = long{};
  10519. const auto res =
  10520. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10521. ASSERT_EQ(res, CURLE_OK);
  10522. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10523. }
  10524. {
  10525. auto dl = curl_off_t{};
  10526. const auto res =
  10527. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10528. ASSERT_EQ(res, CURLE_OK);
  10529. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10530. }
  10531. {
  10532. buffer.push_back('\0');
  10533. ASSERT_STRCASEEQ(buffer.data(), reject);
  10534. }
  10535. }
  10536. }
  10537. #endif
  10538. template <typename S, typename C>
  10539. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10540. svr.Get("/stream", [&](const Request &, Response &res) {
  10541. auto data = new std::string("01234567890123456789");
  10542. res.set_content_provider(
  10543. data->size(), "text/plain",
  10544. [&, data](size_t offset, size_t length, DataSink &sink) {
  10545. const size_t DATA_CHUNK_SIZE = 4;
  10546. const auto &d = *data;
  10547. std::this_thread::sleep_for(std::chrono::seconds(1));
  10548. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10549. return true;
  10550. },
  10551. [data](bool success) {
  10552. EXPECT_FALSE(success);
  10553. delete data;
  10554. });
  10555. });
  10556. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10557. auto i = new size_t(0);
  10558. res.set_content_provider(
  10559. "text/plain",
  10560. [i](size_t, DataSink &sink) {
  10561. if (*i < 5) {
  10562. std::this_thread::sleep_for(std::chrono::seconds(1));
  10563. sink.write("abcd", 4);
  10564. (*i)++;
  10565. } else {
  10566. sink.done();
  10567. }
  10568. return true;
  10569. },
  10570. [i](bool success) {
  10571. EXPECT_FALSE(success);
  10572. delete i;
  10573. });
  10574. });
  10575. svr.Get("/chunked", [&](const Request &, Response &res) {
  10576. auto i = new size_t(0);
  10577. res.set_chunked_content_provider(
  10578. "text/plain",
  10579. [i](size_t, DataSink &sink) {
  10580. if (*i < 5) {
  10581. std::this_thread::sleep_for(std::chrono::seconds(1));
  10582. sink.os << "abcd";
  10583. (*i)++;
  10584. } else {
  10585. sink.done();
  10586. }
  10587. return true;
  10588. },
  10589. [i](bool success) {
  10590. EXPECT_FALSE(success);
  10591. delete i;
  10592. });
  10593. });
  10594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10595. auto se = detail::scope_exit([&] {
  10596. svr.stop();
  10597. listen_thread.join();
  10598. ASSERT_FALSE(svr.is_running());
  10599. });
  10600. svr.wait_until_ready();
  10601. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10602. {
  10603. auto start = std::chrono::steady_clock::now();
  10604. auto res = cli.Get("/stream");
  10605. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10606. std::chrono::steady_clock::now() - start)
  10607. .count();
  10608. ASSERT_FALSE(res);
  10609. EXPECT_EQ(Error::Read, res.error());
  10610. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10611. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10612. }
  10613. {
  10614. auto start = std::chrono::steady_clock::now();
  10615. auto res = cli.Get("/stream_without_length");
  10616. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10617. std::chrono::steady_clock::now() - start)
  10618. .count();
  10619. ASSERT_FALSE(res);
  10620. EXPECT_EQ(Error::Read, res.error());
  10621. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10622. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10623. }
  10624. {
  10625. auto start = std::chrono::steady_clock::now();
  10626. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10627. EXPECT_EQ("abcd", string(data, data_length));
  10628. return true;
  10629. });
  10630. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10631. std::chrono::steady_clock::now() - start)
  10632. .count();
  10633. ASSERT_FALSE(res);
  10634. EXPECT_EQ(Error::Read, res.error());
  10635. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10636. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10637. }
  10638. }
  10639. TEST(MaxTimeoutTest, ContentStream) {
  10640. time_t timeout = 2000;
  10641. time_t threshold = 200;
  10642. Server svr;
  10643. Client cli("localhost", PORT);
  10644. max_timeout_test(svr, cli, timeout, threshold);
  10645. }
  10646. #ifdef CPPHTTPLIB_SSL_ENABLED
  10647. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10648. time_t timeout = 2000;
  10649. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10651. SSLClient cli("localhost", PORT);
  10652. cli.enable_server_certificate_verification(false);
  10653. max_timeout_test(svr, cli, timeout, threshold);
  10654. }
  10655. #endif
  10656. class EventDispatcher {
  10657. public:
  10658. EventDispatcher() {}
  10659. bool wait_event(DataSink *sink) {
  10660. unique_lock<mutex> lk(m_);
  10661. int id = id_;
  10662. // Wait with timeout to prevent hanging if client disconnects
  10663. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10664. [&] { return cid_ == id; })) {
  10665. return false; // Timeout occurred
  10666. }
  10667. sink->write(message_.data(), message_.size());
  10668. return true;
  10669. }
  10670. void send_event(const string &message) {
  10671. lock_guard<mutex> lk(m_);
  10672. cid_ = id_++;
  10673. message_ = message;
  10674. cv_.notify_all();
  10675. }
  10676. private:
  10677. mutex m_;
  10678. condition_variable cv_;
  10679. atomic_int id_{0};
  10680. atomic_int cid_{-1};
  10681. string message_;
  10682. };
  10683. TEST(ClientInThreadTest, Issue2068) {
  10684. EventDispatcher ed;
  10685. Server svr;
  10686. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10687. res.set_chunked_content_provider("text/event-stream",
  10688. [&](size_t /*offset*/, DataSink &sink) {
  10689. return ed.wait_event(&sink);
  10690. });
  10691. });
  10692. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10693. svr.wait_until_ready();
  10694. thread event_thread([&] {
  10695. int id = 0;
  10696. while (svr.is_running()) {
  10697. this_thread::sleep_for(chrono::milliseconds(500));
  10698. std::stringstream ss;
  10699. ss << "data: " << id << "\n\n";
  10700. ed.send_event(ss.str());
  10701. id++;
  10702. }
  10703. });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. event_thread.join();
  10708. ASSERT_FALSE(svr.is_running());
  10709. });
  10710. {
  10711. auto client = detail::make_unique<Client>(HOST, PORT);
  10712. client->set_read_timeout(std::chrono::minutes(10));
  10713. std::atomic<bool> stop{false};
  10714. std::thread t([&] {
  10715. client->Get("/event1",
  10716. [&](const char *, size_t) -> bool { return !stop; });
  10717. });
  10718. std::this_thread::sleep_for(std::chrono::seconds(2));
  10719. stop = true;
  10720. client->stop();
  10721. t.join();
  10722. // Reset client after thread has finished
  10723. client.reset();
  10724. }
  10725. }
  10726. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10727. Server svr;
  10728. svr.Get("/", [](const Request &req, Response &res) {
  10729. EXPECT_EQ(2U, req.trailers.size());
  10730. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10731. // Denied
  10732. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10733. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10734. // Accepted
  10735. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10736. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10737. EXPECT_TRUE(req.has_trailer("X-World"));
  10738. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10739. res.set_content("ok", "text/plain");
  10740. });
  10741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. t.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.wait_until_ready();
  10748. const std::string req = "GET / HTTP/1.1\r\n"
  10749. "Transfer-Encoding: chunked\r\n"
  10750. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10751. "\r\n"
  10752. "0\r\n"
  10753. "Content-Length: 10\r\n"
  10754. "Host: internal.local\r\n"
  10755. "Content-Type: malicious/content\r\n"
  10756. "Cookie: any\r\n"
  10757. "Set-Cookie: any\r\n"
  10758. "X-Forwarded-For: attacker.com\r\n"
  10759. "X-Real-Ip: 1.1.1.1\r\n"
  10760. "X-Hello: hello\r\n"
  10761. "X-World: world\r\n"
  10762. "\r\n";
  10763. std::string res;
  10764. ASSERT_TRUE(send_request(1, req, &res));
  10765. }
  10766. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10767. Server svr;
  10768. std::string observed_remote_addr;
  10769. std::string observed_xff;
  10770. svr.Get("/ip", [&](const Request &req, Response &res) {
  10771. observed_remote_addr = req.remote_addr;
  10772. observed_xff = req.get_header_value("X-Forwarded-For");
  10773. res.set_content("ok", "text/plain");
  10774. });
  10775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10776. auto se = detail::scope_exit([&] {
  10777. svr.stop();
  10778. t.join();
  10779. ASSERT_FALSE(svr.is_running());
  10780. });
  10781. svr.wait_until_ready();
  10782. Client cli(HOST, PORT);
  10783. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10784. ASSERT_TRUE(res);
  10785. EXPECT_EQ(StatusCode::OK_200, res->status);
  10786. EXPECT_EQ(observed_xff, "203.0.113.66");
  10787. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10788. observed_remote_addr == "127.0.0.1");
  10789. }
  10790. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10791. Server svr;
  10792. svr.set_trusted_proxies({"203.0.113.66"});
  10793. std::string observed_remote_addr;
  10794. std::string observed_xff;
  10795. svr.Get("/ip", [&](const Request &req, Response &res) {
  10796. observed_remote_addr = req.remote_addr;
  10797. observed_xff = req.get_header_value("X-Forwarded-For");
  10798. res.set_content("ok", "text/plain");
  10799. });
  10800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. t.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. auto res = cli.Get("/ip");
  10809. ASSERT_TRUE(res);
  10810. EXPECT_EQ(StatusCode::OK_200, res->status);
  10811. EXPECT_EQ(observed_xff, "");
  10812. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10813. observed_remote_addr == "127.0.0.1");
  10814. }
  10815. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10816. Server svr;
  10817. svr.set_trusted_proxies({"203.0.113.66"});
  10818. std::string observed_remote_addr;
  10819. std::string observed_xff;
  10820. svr.Get("/ip", [&](const Request &req, Response &res) {
  10821. observed_remote_addr = req.remote_addr;
  10822. observed_xff = req.get_header_value("X-Forwarded-For");
  10823. res.set_content("ok", "text/plain");
  10824. });
  10825. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. t.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. auto res =
  10834. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10835. ASSERT_TRUE(res);
  10836. EXPECT_EQ(StatusCode::OK_200, res->status);
  10837. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10838. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10839. }
  10840. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10841. Server svr;
  10842. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10843. std::string observed_remote_addr;
  10844. std::string observed_xff;
  10845. svr.Get("/ip", [&](const Request &req, Response &res) {
  10846. observed_remote_addr = req.remote_addr;
  10847. observed_xff = req.get_header_value("X-Forwarded-For");
  10848. res.set_content("ok", "text/plain");
  10849. });
  10850. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. t.join();
  10854. ASSERT_FALSE(svr.is_running());
  10855. });
  10856. svr.wait_until_ready();
  10857. Client cli(HOST, PORT);
  10858. auto res = cli.Get(
  10859. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10860. ASSERT_TRUE(res);
  10861. EXPECT_EQ(StatusCode::OK_200, res->status);
  10862. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10863. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10864. }
  10865. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10866. Server svr;
  10867. svr.set_trusted_proxies({"192.0.2.45"});
  10868. std::string observed_remote_addr;
  10869. std::string observed_xff;
  10870. svr.Get("/ip", [&](const Request &req, Response &res) {
  10871. observed_remote_addr = req.remote_addr;
  10872. observed_xff = req.get_header_value("X-Forwarded-For");
  10873. res.set_content("ok", "text/plain");
  10874. });
  10875. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. t.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. Client cli(HOST, PORT);
  10883. auto res =
  10884. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10885. ASSERT_TRUE(res);
  10886. EXPECT_EQ(StatusCode::OK_200, res->status);
  10887. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10888. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10889. }
  10890. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10891. Server svr;
  10892. svr.set_trusted_proxies({"192.0.2.45"});
  10893. std::string observed_remote_addr;
  10894. std::string observed_xff;
  10895. svr.Get("/ip", [&](const Request &req, Response &res) {
  10896. observed_remote_addr = req.remote_addr;
  10897. observed_xff = req.get_header_value("X-Forwarded-For");
  10898. res.set_content("ok", "text/plain");
  10899. });
  10900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10901. auto se = detail::scope_exit([&] {
  10902. svr.stop();
  10903. t.join();
  10904. ASSERT_FALSE(svr.is_running());
  10905. });
  10906. svr.wait_until_ready();
  10907. Client cli(HOST, PORT);
  10908. auto res = cli.Get(
  10909. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10910. ASSERT_TRUE(res);
  10911. EXPECT_EQ(StatusCode::OK_200, res->status);
  10912. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10913. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10914. }
  10915. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10916. Server svr;
  10917. svr.set_trusted_proxies({"192.0.2.45"});
  10918. std::string observed_remote_addr;
  10919. std::string observed_xff;
  10920. svr.Get("/ip", [&](const Request &req, Response &res) {
  10921. observed_remote_addr = req.remote_addr;
  10922. observed_xff = req.get_header_value("X-Forwarded-For");
  10923. res.set_content("ok", "text/plain");
  10924. });
  10925. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. t.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. });
  10931. svr.wait_until_ready();
  10932. std::string raw_req =
  10933. "GET /ip HTTP/1.1\r\n"
  10934. "Host: localhost\r\n"
  10935. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10936. "Connection: close\r\n"
  10937. "\r\n";
  10938. std::string out;
  10939. ASSERT_TRUE(send_request(5, raw_req, &out));
  10940. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10941. // Header parser trims surrounding whitespace of the header value
  10942. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10943. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10944. }
  10945. #ifndef _WIN32
  10946. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10947. Server svr;
  10948. svr.Post("/post", [&](const Request &req, Response &res) {
  10949. res.set_content(req.body, "text/plain");
  10950. });
  10951. svr.Put("/put", [&](const Request &req, Response &res) {
  10952. res.set_content(req.body, "text/plain");
  10953. });
  10954. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10955. res.set_content(req.body, "text/plain");
  10956. });
  10957. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10958. res.set_content(req.body, "text/plain");
  10959. });
  10960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10961. auto se = detail::scope_exit([&] {
  10962. svr.stop();
  10963. t.join();
  10964. ASSERT_FALSE(svr.is_running());
  10965. });
  10966. svr.wait_until_ready();
  10967. std::string resp;
  10968. // POST without Content-Length
  10969. ASSERT_TRUE(send_request(5,
  10970. "POST /post HTTP/1.1\r\n"
  10971. "Host: localhost\r\n"
  10972. "Connection: close\r\n"
  10973. "\r\n",
  10974. &resp));
  10975. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10976. // PUT without Content-Length
  10977. resp.clear();
  10978. ASSERT_TRUE(send_request(5,
  10979. "PUT /put HTTP/1.1\r\n"
  10980. "Host: localhost\r\n"
  10981. "Connection: close\r\n"
  10982. "\r\n",
  10983. &resp));
  10984. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10985. // PATCH without Content-Length
  10986. resp.clear();
  10987. ASSERT_TRUE(send_request(5,
  10988. "PATCH /patch HTTP/1.1\r\n"
  10989. "Host: localhost\r\n"
  10990. "Connection: close\r\n"
  10991. "\r\n",
  10992. &resp));
  10993. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10994. // DELETE without Content-Length
  10995. resp.clear();
  10996. ASSERT_TRUE(send_request(5,
  10997. "DELETE /delete HTTP/1.1\r\n"
  10998. "Host: localhost\r\n"
  10999. "Connection: close\r\n"
  11000. "\r\n",
  11001. &resp));
  11002. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11003. }
  11004. #endif
  11005. //==============================================================================
  11006. // open_stream() Tests
  11007. //==============================================================================
  11008. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11009. std::string result;
  11010. char buf[8192];
  11011. ssize_t n;
  11012. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11013. result.append(buf, static_cast<size_t>(n));
  11014. }
  11015. return result;
  11016. }
  11017. // Mock stream for unit tests
  11018. class MockStream : public Stream {
  11019. public:
  11020. std::string data;
  11021. size_t pos = 0;
  11022. ssize_t error_after = -1; // -1 = no error
  11023. explicit MockStream(const std::string &d, ssize_t err = -1)
  11024. : data(d), error_after(err) {}
  11025. bool is_readable() const override { return true; }
  11026. bool wait_readable() const override { return true; }
  11027. bool wait_writable() const override { return true; }
  11028. ssize_t read(char *ptr, size_t size) override {
  11029. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11030. if (pos >= data.size()) return 0;
  11031. size_t limit =
  11032. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11033. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11034. std::memcpy(ptr, data.data() + pos, to_read);
  11035. pos += to_read;
  11036. return static_cast<ssize_t>(to_read);
  11037. }
  11038. ssize_t write(const char *, size_t) override { return -1; }
  11039. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11040. ip = "127.0.0.1";
  11041. port = 0;
  11042. }
  11043. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11044. ip = "127.0.0.1";
  11045. port = 0;
  11046. }
  11047. socket_t socket() const override { return INVALID_SOCKET; }
  11048. time_t duration() const override { return 0; }
  11049. };
  11050. TEST(StreamHandleTest, Basic) {
  11051. ClientImpl::StreamHandle handle;
  11052. EXPECT_FALSE(handle.is_valid());
  11053. handle.response = detail::make_unique<Response>();
  11054. handle.error = Error::Connection;
  11055. EXPECT_FALSE(handle.is_valid());
  11056. handle.error = Error::Success;
  11057. EXPECT_TRUE(handle.is_valid());
  11058. }
  11059. TEST(BodyReaderTest, Basic) {
  11060. MockStream stream("Hello, World!");
  11061. detail::BodyReader reader;
  11062. reader.stream = &stream;
  11063. reader.content_length = 13;
  11064. char buf[32];
  11065. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11066. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11067. EXPECT_TRUE(reader.eof);
  11068. }
  11069. TEST(BodyReaderTest, NoStream) {
  11070. detail::BodyReader reader;
  11071. char buf[32];
  11072. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11073. EXPECT_EQ(Error::Connection, reader.last_error);
  11074. }
  11075. TEST(BodyReaderTest, Error) {
  11076. MockStream stream("Hello, World!", 5);
  11077. detail::BodyReader reader;
  11078. reader.stream = &stream;
  11079. reader.content_length = 13;
  11080. char buf[32];
  11081. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11082. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11083. EXPECT_EQ(Error::Read, reader.last_error);
  11084. }
  11085. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11086. // Mock-based StreamHandle tests relying on private internals are removed.
  11087. class OpenStreamTest : public ::testing::Test {
  11088. protected:
  11089. void SetUp() override {
  11090. svr_.Get("/hello", [](const Request &, Response &res) {
  11091. res.set_content("Hello World!", "text/plain");
  11092. });
  11093. svr_.Get("/large", [](const Request &, Response &res) {
  11094. res.set_content(std::string(10000, 'X'), "text/plain");
  11095. });
  11096. svr_.Get("/chunked", [](const Request &, Response &res) {
  11097. res.set_chunked_content_provider("text/plain",
  11098. [](size_t offset, DataSink &sink) {
  11099. if (offset < 15) {
  11100. sink.write("chunk", 5);
  11101. return true;
  11102. }
  11103. sink.done();
  11104. return true;
  11105. });
  11106. });
  11107. svr_.Get("/compressible", [](const Request &, Response &res) {
  11108. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11109. DataSink &sink) {
  11110. if (offset < 100 * 1024) {
  11111. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11112. sink.write(chunk.data(), chunk.size());
  11113. return true;
  11114. }
  11115. sink.done();
  11116. return true;
  11117. });
  11118. });
  11119. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11120. [](const Request & /*req*/, Response &res) {
  11121. auto i = new int(0);
  11122. res.set_header("Trailer", "Content-Length, X-Allowed");
  11123. res.set_chunked_content_provider(
  11124. "text/plain",
  11125. [i](size_t /*offset*/, DataSink &sink) {
  11126. switch (*i) {
  11127. case 0: sink.os << "123"; break;
  11128. case 1: sink.os << "456"; break;
  11129. case 2: sink.os << "789"; break;
  11130. case 3: {
  11131. sink.done_with_trailer(
  11132. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11133. } break;
  11134. }
  11135. (*i)++;
  11136. return true;
  11137. },
  11138. [i](bool success) {
  11139. EXPECT_TRUE(success);
  11140. delete i;
  11141. });
  11142. });
  11143. // Echo headers endpoint for header-related tests
  11144. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11145. std::string body;
  11146. for (const auto &h : req.headers) {
  11147. body.append(h.first);
  11148. body.push_back(':');
  11149. body.append(h.second);
  11150. body.push_back('\n');
  11151. }
  11152. res.set_content(body, "text/plain");
  11153. });
  11154. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11155. std::string body;
  11156. for (const auto &h : req.headers) {
  11157. body.append(h.first);
  11158. body.push_back(':');
  11159. body.append(h.second);
  11160. body.push_back('\n');
  11161. }
  11162. res.set_content(body, "text/plain");
  11163. });
  11164. port_ = svr_.bind_to_any_port("127.0.0.1");
  11165. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11166. svr_.wait_until_ready();
  11167. }
  11168. void TearDown() override {
  11169. svr_.stop();
  11170. if (thread_.joinable()) thread_.join();
  11171. }
  11172. Server svr_;
  11173. std::thread thread_;
  11174. int port_ = 0;
  11175. };
  11176. TEST_F(OpenStreamTest, Basic) {
  11177. Client cli("127.0.0.1", port_);
  11178. auto handle = cli.open_stream("GET", "/hello");
  11179. EXPECT_TRUE(handle.is_valid());
  11180. EXPECT_EQ("Hello World!", read_all(handle));
  11181. }
  11182. TEST_F(OpenStreamTest, SmallBuffer) {
  11183. Client cli("127.0.0.1", port_);
  11184. auto handle = cli.open_stream("GET", "/hello");
  11185. std::string result;
  11186. char buf[4];
  11187. ssize_t n;
  11188. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11189. result.append(buf, static_cast<size_t>(n));
  11190. EXPECT_EQ("Hello World!", result);
  11191. }
  11192. TEST_F(OpenStreamTest, DefaultHeaders) {
  11193. Client cli("127.0.0.1", port_);
  11194. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11195. {
  11196. auto handle = cli.open_stream("GET", "/echo-headers");
  11197. ASSERT_TRUE(handle.is_valid());
  11198. auto body = read_all(handle);
  11199. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11200. std::string::npos);
  11201. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11202. std::string::npos);
  11203. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11204. }
  11205. // open_stream POST with body and no explicit content_type should NOT add
  11206. // text/plain Content-Type (behavior differs from non-streaming path), but
  11207. // should include Content-Length
  11208. {
  11209. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11210. ASSERT_TRUE(handle.is_valid());
  11211. auto body = read_all(handle);
  11212. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11213. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11214. }
  11215. // open_stream POST with explicit Content-Type should preserve it
  11216. {
  11217. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11218. {{"Content-Type", "application/custom"}},
  11219. "{}", "application/custom");
  11220. ASSERT_TRUE(handle.is_valid());
  11221. auto body = read_all(handle);
  11222. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11223. }
  11224. // User-specified User-Agent must not be overwritten for stream API
  11225. {
  11226. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11227. {{"User-Agent", "MyAgent/1.2"}});
  11228. ASSERT_TRUE(handle.is_valid());
  11229. auto body = read_all(handle);
  11230. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11231. }
  11232. }
  11233. TEST_F(OpenStreamTest, Large) {
  11234. Client cli("127.0.0.1", port_);
  11235. auto handle = cli.open_stream("GET", "/large");
  11236. EXPECT_EQ(10000u, read_all(handle).size());
  11237. }
  11238. TEST_F(OpenStreamTest, ConnectionError) {
  11239. Client cli("127.0.0.1", 9999);
  11240. auto handle = cli.open_stream("GET", "/hello");
  11241. EXPECT_FALSE(handle.is_valid());
  11242. }
  11243. TEST_F(OpenStreamTest, Chunked) {
  11244. Client cli("127.0.0.1", port_);
  11245. auto handle = cli.open_stream("GET", "/chunked");
  11246. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11247. "Transfer-Encoding") == "chunked");
  11248. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11249. }
  11250. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11251. Client cli("127.0.0.1", port_);
  11252. auto handle =
  11253. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11254. ASSERT_TRUE(handle.is_valid());
  11255. // Consume body to allow trailers to be received/parsed
  11256. auto body = read_all(handle);
  11257. // Explicitly parse trailers (ensure trailers are available for assertion)
  11258. handle.parse_trailers_if_needed();
  11259. EXPECT_EQ(std::string("123456789"), body);
  11260. // The response should include a Trailer header declaring both names
  11261. ASSERT_TRUE(handle.response);
  11262. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11263. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11264. handle.response->get_header_value("Trailer"));
  11265. // Prohibited trailer must not be present
  11266. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11267. // Allowed trailer should be present
  11268. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11269. EXPECT_EQ(std::string("yes"),
  11270. handle.response->get_trailer_value("X-Allowed"));
  11271. // Verify trailers are NOT present as regular headers
  11272. EXPECT_EQ(std::string(""),
  11273. handle.response->get_header_value("Content-Length"));
  11274. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11275. }
  11276. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11277. TEST_F(OpenStreamTest, Gzip) {
  11278. Client cli("127.0.0.1", port_);
  11279. auto handle = cli.open_stream("GET", "/compressible", {},
  11280. {{"Accept-Encoding", "gzip"}});
  11281. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11282. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11283. }
  11284. #endif
  11285. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11286. TEST_F(OpenStreamTest, Brotli) {
  11287. Client cli("127.0.0.1", port_);
  11288. auto handle =
  11289. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11290. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11291. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11292. }
  11293. #endif
  11294. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11295. TEST_F(OpenStreamTest, Zstd) {
  11296. Client cli("127.0.0.1", port_);
  11297. auto handle = cli.open_stream("GET", "/compressible", {},
  11298. {{"Accept-Encoding", "zstd"}});
  11299. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11300. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11301. }
  11302. #endif
  11303. #ifdef CPPHTTPLIB_SSL_ENABLED
  11304. class SSLOpenStreamTest : public ::testing::Test {
  11305. protected:
  11306. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11307. void SetUp() override {
  11308. svr_.Get("/hello", [](const Request &, Response &res) {
  11309. res.set_content("Hello SSL World!", "text/plain");
  11310. });
  11311. svr_.Get("/chunked", [](const Request &, Response &res) {
  11312. res.set_chunked_content_provider("text/plain",
  11313. [](size_t offset, DataSink &sink) {
  11314. if (offset < 15) {
  11315. sink.write("chunk", 5);
  11316. return true;
  11317. }
  11318. sink.done();
  11319. return true;
  11320. });
  11321. });
  11322. svr_.Post("/echo", [](const Request &req, Response &res) {
  11323. res.set_content(req.body, req.get_header_value("Content-Type"));
  11324. });
  11325. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11326. std::string body = req.body;
  11327. res.set_chunked_content_provider(
  11328. "text/plain", [body](size_t offset, DataSink &sink) {
  11329. if (offset < body.size()) {
  11330. sink.write(body.data() + offset, body.size() - offset);
  11331. }
  11332. sink.done();
  11333. return true;
  11334. });
  11335. });
  11336. port_ = svr_.bind_to_any_port("127.0.0.1");
  11337. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11338. svr_.wait_until_ready();
  11339. }
  11340. void TearDown() override {
  11341. svr_.stop();
  11342. if (thread_.joinable()) thread_.join();
  11343. }
  11344. SSLServer svr_;
  11345. std::thread thread_;
  11346. int port_ = 0;
  11347. };
  11348. TEST_F(SSLOpenStreamTest, Basic) {
  11349. SSLClient cli("127.0.0.1", port_);
  11350. cli.enable_server_certificate_verification(false);
  11351. auto handle = cli.open_stream("GET", "/hello");
  11352. ASSERT_TRUE(handle.is_valid());
  11353. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11354. }
  11355. TEST_F(SSLOpenStreamTest, Chunked) {
  11356. SSLClient cli("127.0.0.1", port_);
  11357. cli.enable_server_certificate_verification(false);
  11358. auto handle = cli.open_stream("GET", "/chunked");
  11359. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11360. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11361. "Transfer-Encoding") == "chunked");
  11362. auto body = read_all(handle);
  11363. EXPECT_EQ("chunkchunkchunk", body);
  11364. }
  11365. TEST_F(SSLOpenStreamTest, Post) {
  11366. SSLClient cli("127.0.0.1", port_);
  11367. cli.enable_server_certificate_verification(false);
  11368. auto handle =
  11369. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11370. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11371. EXPECT_EQ(200, handle.response->status);
  11372. auto body = read_all(handle);
  11373. EXPECT_EQ("Hello SSL POST", body);
  11374. }
  11375. TEST_F(SSLOpenStreamTest, PostChunked) {
  11376. SSLClient cli("127.0.0.1", port_);
  11377. cli.enable_server_certificate_verification(false);
  11378. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11379. "Chunked SSL Data", "text/plain");
  11380. ASSERT_TRUE(handle.is_valid());
  11381. EXPECT_EQ(200, handle.response->status);
  11382. auto body = read_all(handle);
  11383. EXPECT_EQ("Chunked SSL Data", body);
  11384. }
  11385. #endif // CPPHTTPLIB_SSL_ENABLED
  11386. //==============================================================================
  11387. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11388. // results for various scenarios.
  11389. //==============================================================================
  11390. TEST(ParityTest, GetVsOpenStream) {
  11391. Server svr;
  11392. const std::string path = "/parity";
  11393. const std::string content = "Parity test content: hello world";
  11394. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11395. res.set_content(content, "text/plain");
  11396. });
  11397. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11398. auto se = detail::scope_exit([&] {
  11399. svr.stop();
  11400. t.join();
  11401. ASSERT_FALSE(svr.is_running());
  11402. });
  11403. svr.wait_until_ready();
  11404. Client cli(HOST, PORT);
  11405. // Non-stream path
  11406. auto r1 = cli.Get(path);
  11407. ASSERT_TRUE(r1);
  11408. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11409. // Stream path
  11410. auto h = cli.open_stream("GET", path);
  11411. ASSERT_TRUE(h.is_valid());
  11412. EXPECT_EQ(r1->body, read_all(h));
  11413. }
  11414. // Helper to compress data with provided compressor type T
  11415. template <typename Compressor>
  11416. static std::string compress_payload_for_parity(const std::string &in) {
  11417. std::string out;
  11418. Compressor compressor;
  11419. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11420. [&](const char *data, size_t n) {
  11421. out.append(data, n);
  11422. return true;
  11423. });
  11424. EXPECT_TRUE(ok);
  11425. return out;
  11426. }
  11427. // Helper function for compression parity tests
  11428. template <typename Compressor>
  11429. static void test_compression_parity(const std::string &original,
  11430. const std::string &path,
  11431. const std::string &encoding) {
  11432. const std::string compressed =
  11433. compress_payload_for_parity<Compressor>(original);
  11434. Server svr;
  11435. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11436. res.set_content(compressed, "application/octet-stream");
  11437. res.set_header("Content-Encoding", encoding);
  11438. });
  11439. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11440. auto se = detail::scope_exit([&] {
  11441. svr.stop();
  11442. t.join();
  11443. ASSERT_FALSE(svr.is_running());
  11444. });
  11445. svr.wait_until_ready();
  11446. Client cli(HOST, PORT);
  11447. // Non-streaming
  11448. {
  11449. auto res = cli.Get(path);
  11450. ASSERT_TRUE(res);
  11451. EXPECT_EQ(StatusCode::OK_200, res->status);
  11452. EXPECT_EQ(original, res->body);
  11453. }
  11454. // Streaming
  11455. {
  11456. auto h = cli.open_stream("GET", path);
  11457. ASSERT_TRUE(h.is_valid());
  11458. EXPECT_EQ(original, read_all(h));
  11459. }
  11460. }
  11461. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11462. TEST(ParityTest, Gzip) {
  11463. test_compression_parity<detail::gzip_compressor>(
  11464. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11465. }
  11466. #endif
  11467. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11468. TEST(ParityTest, Brotli) {
  11469. test_compression_parity<detail::brotli_compressor>(
  11470. "Hello, brotli parity test payload", "/parity-br", "br");
  11471. }
  11472. #endif
  11473. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11474. TEST(ParityTest, Zstd) {
  11475. test_compression_parity<detail::zstd_compressor>(
  11476. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11477. }
  11478. #endif
  11479. //==============================================================================
  11480. // New Stream API Tests
  11481. //==============================================================================
  11482. inline std::string read_body(httplib::stream::Result &result) {
  11483. std::string body;
  11484. while (result.next()) {
  11485. body.append(result.data(), result.size());
  11486. }
  11487. return body;
  11488. }
  11489. TEST(ClientConnectionTest, Basic) {
  11490. httplib::ClientConnection conn;
  11491. EXPECT_FALSE(conn.is_open());
  11492. conn.sock = 1;
  11493. EXPECT_TRUE(conn.is_open());
  11494. httplib::ClientConnection conn2(std::move(conn));
  11495. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11496. conn2.sock = INVALID_SOCKET;
  11497. }
  11498. // Unified test server for all stream::* tests
  11499. class StreamApiTest : public ::testing::Test {
  11500. protected:
  11501. void SetUp() override {
  11502. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11503. res.set_content("Hello World!", "text/plain");
  11504. });
  11505. svr_.Get("/echo-params",
  11506. [](const httplib::Request &req, httplib::Response &res) {
  11507. std::string r;
  11508. for (const auto &p : req.params) {
  11509. if (!r.empty()) r += "&";
  11510. r += p.first + "=" + p.second;
  11511. }
  11512. res.set_content(r, "text/plain");
  11513. });
  11514. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11515. res.set_content(req.body, req.get_header_value("Content-Type"));
  11516. });
  11517. svr_.Post("/echo-headers",
  11518. [](const httplib::Request &req, httplib::Response &res) {
  11519. std::string r;
  11520. for (const auto &h : req.headers)
  11521. r += h.first + ": " + h.second + "\n";
  11522. res.set_content(r, "text/plain");
  11523. });
  11524. svr_.Post("/echo-params",
  11525. [](const httplib::Request &req, httplib::Response &res) {
  11526. std::string r = "params:";
  11527. for (const auto &p : req.params)
  11528. r += p.first + "=" + p.second + ";";
  11529. res.set_content(r + " body:" + req.body, "text/plain");
  11530. });
  11531. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11532. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11533. });
  11534. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11535. res.set_content("PUT:" + req.body, "text/plain");
  11536. });
  11537. svr_.Patch("/echo",
  11538. [](const httplib::Request &req, httplib::Response &res) {
  11539. res.set_content("PATCH:" + req.body, "text/plain");
  11540. });
  11541. svr_.Delete(
  11542. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11543. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11544. "text/plain");
  11545. });
  11546. svr_.Get("/head-test",
  11547. [](const httplib::Request &, httplib::Response &res) {
  11548. res.set_content("body for HEAD", "text/plain");
  11549. });
  11550. svr_.Options("/options",
  11551. [](const httplib::Request &, httplib::Response &res) {
  11552. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11553. });
  11554. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11555. svr_.wait_until_ready();
  11556. }
  11557. void TearDown() override {
  11558. svr_.stop();
  11559. if (thread_.joinable()) thread_.join();
  11560. }
  11561. httplib::Server svr_;
  11562. std::thread thread_;
  11563. };
  11564. // stream::Get tests
  11565. TEST_F(StreamApiTest, GetBasic) {
  11566. httplib::Client cli(HOST, PORT);
  11567. auto result = httplib::stream::Get(cli, "/hello");
  11568. ASSERT_TRUE(result.is_valid());
  11569. EXPECT_EQ(200, result.status());
  11570. EXPECT_EQ("Hello World!", read_body(result));
  11571. }
  11572. TEST_F(StreamApiTest, GetWithParams) {
  11573. httplib::Client cli(HOST, PORT);
  11574. httplib::Params params{{"foo", "bar"}};
  11575. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11576. ASSERT_TRUE(result.is_valid());
  11577. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11578. }
  11579. TEST_F(StreamApiTest, GetConnectionError) {
  11580. httplib::Client cli(HOST, 9999);
  11581. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11582. }
  11583. TEST_F(StreamApiTest, Get404) {
  11584. httplib::Client cli(HOST, PORT);
  11585. auto result = httplib::stream::Get(cli, "/nonexistent");
  11586. EXPECT_TRUE(result.is_valid());
  11587. EXPECT_EQ(404, result.status());
  11588. }
  11589. // stream::Post tests
  11590. TEST_F(StreamApiTest, PostBasic) {
  11591. httplib::Client cli(HOST, PORT);
  11592. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11593. "application/json");
  11594. ASSERT_TRUE(result.is_valid());
  11595. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11596. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11597. }
  11598. TEST_F(StreamApiTest, PostWithHeaders) {
  11599. httplib::Client cli(HOST, PORT);
  11600. httplib::Headers headers{{"X-Custom", "value"}};
  11601. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11602. "text/plain");
  11603. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11604. }
  11605. TEST_F(StreamApiTest, PostWithParams) {
  11606. httplib::Client cli(HOST, PORT);
  11607. httplib::Params params{{"k", "v"}};
  11608. auto result =
  11609. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11610. auto body = read_body(result);
  11611. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11612. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11613. }
  11614. TEST_F(StreamApiTest, PostLarge) {
  11615. httplib::Client cli(HOST, PORT);
  11616. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11617. size_t total = 0;
  11618. while (result.next()) {
  11619. total += result.size();
  11620. }
  11621. EXPECT_EQ(100u * 1024u, total);
  11622. }
  11623. // stream::Put/Patch tests
  11624. TEST_F(StreamApiTest, PutAndPatch) {
  11625. httplib::Client cli(HOST, PORT);
  11626. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11627. EXPECT_EQ("PUT:test", read_body(put));
  11628. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11629. EXPECT_EQ("PATCH:test", read_body(patch));
  11630. }
  11631. // stream::Delete tests
  11632. TEST_F(StreamApiTest, Delete) {
  11633. httplib::Client cli(HOST, PORT);
  11634. auto del1 = httplib::stream::Delete(cli, "/resource");
  11635. EXPECT_EQ("Deleted", read_body(del1));
  11636. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11637. EXPECT_EQ("Deleted:data", read_body(del2));
  11638. }
  11639. // stream::Head/Options tests
  11640. TEST_F(StreamApiTest, HeadAndOptions) {
  11641. httplib::Client cli(HOST, PORT);
  11642. auto head = httplib::stream::Head(cli, "/head-test");
  11643. EXPECT_TRUE(head.is_valid());
  11644. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11645. auto opts = httplib::stream::Options(cli, "/options");
  11646. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11647. }
  11648. // SSL stream::* tests
  11649. #ifdef CPPHTTPLIB_SSL_ENABLED
  11650. class SSLStreamApiTest : public ::testing::Test {
  11651. protected:
  11652. void SetUp() override {
  11653. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11654. res.set_content("Hello SSL!", "text/plain");
  11655. });
  11656. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11657. res.set_content(req.body, "text/plain");
  11658. });
  11659. port_ = svr_.bind_to_any_port("127.0.0.1");
  11660. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11661. svr_.wait_until_ready();
  11662. }
  11663. void TearDown() override {
  11664. svr_.stop();
  11665. if (thread_.joinable()) thread_.join();
  11666. }
  11667. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11668. std::thread thread_;
  11669. int port_ = 0;
  11670. };
  11671. TEST_F(SSLStreamApiTest, GetAndPost) {
  11672. httplib::SSLClient cli("127.0.0.1", port_);
  11673. cli.enable_server_certificate_verification(false);
  11674. auto get = httplib::stream::Get(cli, "/hello");
  11675. EXPECT_EQ("Hello SSL!", read_body(get));
  11676. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11677. EXPECT_EQ("test", read_body(post));
  11678. }
  11679. #endif
  11680. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11681. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11682. // BodyReader
  11683. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11684. // Test that read timeout during streaming is detected
  11685. // Use a large content-length response where server delays mid-stream
  11686. Server svr;
  11687. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11688. // Send a large response with delay in the middle
  11689. res.set_content_provider(
  11690. 1000, // content_length
  11691. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11692. if (offset < 100) {
  11693. // Send first 100 bytes immediately
  11694. std::string data(100, 'A');
  11695. sink.write(data.c_str(), data.size());
  11696. return true;
  11697. }
  11698. // Then delay longer than client timeout
  11699. std::this_thread::sleep_for(std::chrono::seconds(3));
  11700. std::string data(900, 'B');
  11701. sink.write(data.c_str(), data.size());
  11702. return true;
  11703. });
  11704. });
  11705. auto port = 8091;
  11706. std::thread t([&]() { svr.listen("localhost", port); });
  11707. svr.wait_until_ready();
  11708. Client cli("localhost", port);
  11709. cli.set_read_timeout(1, 0); // 1 second timeout
  11710. auto handle = cli.open_stream("GET", "/slow-stream");
  11711. ASSERT_TRUE(handle.is_valid());
  11712. char buf[256];
  11713. ssize_t total = 0;
  11714. ssize_t n;
  11715. bool got_error = false;
  11716. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11717. total += n;
  11718. }
  11719. if (n < 0) {
  11720. got_error = true;
  11721. // Should be timeout or read error
  11722. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11723. handle.get_read_error() == Error::Read)
  11724. << "Actual error: " << to_string(handle.get_read_error());
  11725. }
  11726. // Either we got an error, or we got less data than expected
  11727. EXPECT_TRUE(got_error || total < 1000)
  11728. << "Expected timeout but got all " << total << " bytes";
  11729. svr.stop();
  11730. t.join();
  11731. }
  11732. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11733. // Test connection closed detection via BodyReader
  11734. Server svr;
  11735. std::atomic<bool> close_now{false};
  11736. svr.Get("/will-close", [&](const Request &, Response &res) {
  11737. res.set_content_provider(
  11738. 10000, // Large content_length that we won't fully send
  11739. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11740. if (offset < 100) {
  11741. std::string data(100, 'X');
  11742. sink.write(data.c_str(), data.size());
  11743. return true;
  11744. }
  11745. // Wait for signal then abort
  11746. while (!close_now) {
  11747. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11748. }
  11749. return false; // Abort - server will close connection
  11750. });
  11751. });
  11752. auto port = 8092;
  11753. std::thread t([&]() { svr.listen("localhost", port); });
  11754. svr.wait_until_ready();
  11755. Client cli("localhost", port);
  11756. auto handle = cli.open_stream("GET", "/will-close");
  11757. ASSERT_TRUE(handle.is_valid());
  11758. char buf[256];
  11759. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11760. EXPECT_GT(n, 0) << "First read should succeed";
  11761. // Signal server to close
  11762. close_now = true;
  11763. // Keep reading until error or EOF
  11764. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11765. // Keep reading
  11766. }
  11767. // Should get an error since content_length wasn't satisfied
  11768. if (n < 0) {
  11769. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11770. handle.get_read_error() == Error::Read)
  11771. << "Actual error: " << to_string(handle.get_read_error());
  11772. }
  11773. svr.stop();
  11774. t.join();
  11775. }
  11776. #ifdef CPPHTTPLIB_SSL_ENABLED
  11777. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11778. // Test that read timeout during SSL streaming is detected
  11779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11780. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11781. res.set_content_provider(
  11782. 1000, "text/plain",
  11783. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11784. if (offset < 100) {
  11785. std::string data(100, 'A');
  11786. sink.write(data.c_str(), data.size());
  11787. return true;
  11788. }
  11789. std::this_thread::sleep_for(std::chrono::seconds(3));
  11790. std::string data(900, 'B');
  11791. sink.write(data.c_str(), data.size());
  11792. return true;
  11793. });
  11794. });
  11795. auto port = 8093;
  11796. std::thread t([&]() { svr.listen("localhost", port); });
  11797. svr.wait_until_ready();
  11798. SSLClient cli("localhost", port);
  11799. cli.enable_server_certificate_verification(false);
  11800. cli.set_read_timeout(1, 0); // 1 second timeout
  11801. auto handle = cli.open_stream("GET", "/slow-stream");
  11802. ASSERT_TRUE(handle.is_valid());
  11803. char buf[256];
  11804. ssize_t total = 0;
  11805. ssize_t n;
  11806. bool got_error = false;
  11807. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11808. total += n;
  11809. }
  11810. if (n < 0) {
  11811. got_error = true;
  11812. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11813. handle.get_read_error() == Error::Read)
  11814. << "Actual error: " << to_string(handle.get_read_error());
  11815. }
  11816. EXPECT_TRUE(got_error || total < 1000)
  11817. << "Expected timeout but got all " << total << " bytes";
  11818. svr.stop();
  11819. t.join();
  11820. }
  11821. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11822. // Test SSL connection closed detection
  11823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11824. std::atomic<bool> close_now{false};
  11825. svr.Get("/will-close", [&](const Request &, Response &res) {
  11826. res.set_content_provider(
  11827. 10000, "text/plain",
  11828. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11829. if (offset < 100) {
  11830. std::string data(100, 'X');
  11831. sink.write(data.c_str(), data.size());
  11832. return true;
  11833. }
  11834. while (!close_now) {
  11835. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11836. }
  11837. return false;
  11838. });
  11839. });
  11840. auto port = 8094;
  11841. std::thread t([&]() { svr.listen("localhost", port); });
  11842. svr.wait_until_ready();
  11843. SSLClient cli("localhost", port);
  11844. cli.enable_server_certificate_verification(false);
  11845. auto handle = cli.open_stream("GET", "/will-close");
  11846. ASSERT_TRUE(handle.is_valid());
  11847. char buf[256];
  11848. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11849. EXPECT_GT(n, 0);
  11850. // Signal server to close
  11851. close_now = true;
  11852. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11853. // Keep reading
  11854. }
  11855. if (n < 0) {
  11856. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11857. handle.get_read_error() == Error::Read)
  11858. << "Actual error: " << to_string(handle.get_read_error());
  11859. }
  11860. svr.stop();
  11861. t.join();
  11862. }
  11863. #endif
  11864. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11865. using namespace httplib;
  11866. // Create a test file
  11867. const char *fname = "etag_testfile.txt";
  11868. const char *content = "etag-content";
  11869. {
  11870. std::ofstream ofs(fname);
  11871. ofs << content;
  11872. ASSERT_TRUE(ofs.good());
  11873. }
  11874. Server svr;
  11875. svr.set_mount_point("/static", ".");
  11876. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11877. svr.wait_until_ready();
  11878. Client cli(HOST, PORT);
  11879. // First request: should get 200 with ETag header
  11880. auto res1 = cli.Get("/static/etag_testfile.txt");
  11881. ASSERT_TRUE(res1);
  11882. ASSERT_EQ(200, res1->status);
  11883. ASSERT_TRUE(res1->has_header("ETag"));
  11884. std::string etag = res1->get_header_value("ETag");
  11885. EXPECT_FALSE(etag.empty());
  11886. // Verify ETag format: W/"hex-hex"
  11887. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11888. EXPECT_EQ('W', etag[0]);
  11889. EXPECT_EQ('/', etag[1]);
  11890. EXPECT_EQ('"', etag[2]);
  11891. EXPECT_EQ('"', etag.back());
  11892. // Exact match: expect 304 Not Modified
  11893. Headers h2 = {{"If-None-Match", etag}};
  11894. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11895. ASSERT_TRUE(res2);
  11896. EXPECT_EQ(304, res2->status);
  11897. // Wildcard match: expect 304 Not Modified
  11898. Headers h3 = {{"If-None-Match", "*"}};
  11899. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11900. ASSERT_TRUE(res3);
  11901. EXPECT_EQ(304, res3->status);
  11902. // Non-matching ETag: expect 200
  11903. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11904. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11905. ASSERT_TRUE(res4);
  11906. EXPECT_EQ(200, res4->status);
  11907. // Multiple ETags with one matching: expect 304
  11908. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11909. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11910. ASSERT_TRUE(res5);
  11911. EXPECT_EQ(304, res5->status);
  11912. svr.stop();
  11913. t.join();
  11914. std::remove(fname);
  11915. }
  11916. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11917. using namespace httplib;
  11918. Server svr;
  11919. svr.set_mount_point("/static", ".");
  11920. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11921. svr.wait_until_ready();
  11922. Client cli(HOST, PORT);
  11923. // Send If-None-Match: * to a non-existent file
  11924. Headers h = {{"If-None-Match", "*"}};
  11925. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11926. ASSERT_TRUE(res);
  11927. EXPECT_EQ(404, res->status);
  11928. svr.stop();
  11929. t.join();
  11930. }
  11931. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  11932. using namespace httplib;
  11933. // Create a test file
  11934. const char *fname = "etag_boundary_testfile.txt";
  11935. const char *content = "boundary-test";
  11936. {
  11937. std::ofstream ofs(fname);
  11938. ofs << content;
  11939. ASSERT_TRUE(ofs.good());
  11940. }
  11941. Server svr;
  11942. svr.set_mount_point("/static", ".");
  11943. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11944. svr.wait_until_ready();
  11945. Client cli(HOST, PORT);
  11946. // Get the actual ETag
  11947. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  11948. ASSERT_TRUE(res1);
  11949. ASSERT_EQ(200, res1->status);
  11950. ASSERT_TRUE(res1->has_header("ETag"));
  11951. std::string etag = res1->get_header_value("ETag");
  11952. // Test 1: Very long ETag value (longer than actual ETag)
  11953. // Should NOT match and return 200 (not trigger out-of-bounds read)
  11954. Headers h1 = {{"If-None-Match", "W/"
  11955. "\"very-long-etag-value-that-is-much-longer-"
  11956. "than-the-actual-etag-value\""}};
  11957. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  11958. ASSERT_TRUE(res2);
  11959. EXPECT_EQ(200, res2->status); // Should not match
  11960. // Test 2: Long string followed by wildcard
  11961. // Should match on "*" and return 304 (without out-of-bounds read on the long
  11962. // string)
  11963. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  11964. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  11965. ASSERT_TRUE(res3);
  11966. EXPECT_EQ(304, res3->status); // Should match on "*"
  11967. // Test 3: Wildcard followed by long string
  11968. // Should match on "*" immediately and return 304
  11969. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  11970. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  11971. ASSERT_TRUE(res4);
  11972. EXPECT_EQ(304, res4->status); // Should match on "*"
  11973. // Test 4: Multiple long non-matching values
  11974. // Should NOT match and return 200 (test that all comparisons are safe)
  11975. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  11976. "W/\"second-long-non-matching-value\", "
  11977. "W/\"third-long-non-matching-value\""}};
  11978. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  11979. ASSERT_TRUE(res5);
  11980. EXPECT_EQ(200, res5->status); // Should not match
  11981. // Test 5: Single character that is not "*" (edge case)
  11982. Headers h5 = {{"If-None-Match", "X"}};
  11983. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  11984. ASSERT_TRUE(res6);
  11985. EXPECT_EQ(200, res6->status); // Should not match
  11986. svr.stop();
  11987. t.join();
  11988. std::remove(fname);
  11989. }
  11990. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11991. using namespace httplib;
  11992. // Create a test file
  11993. const char *fname = "ims_testfile.txt";
  11994. const char *content = "if-modified-since-test";
  11995. {
  11996. std::ofstream ofs(fname);
  11997. ofs << content;
  11998. ASSERT_TRUE(ofs.good());
  11999. }
  12000. Server svr;
  12001. svr.set_mount_point("/static", ".");
  12002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12003. svr.wait_until_ready();
  12004. Client cli(HOST, PORT);
  12005. // First request: should get 200 with Last-Modified header
  12006. auto res1 = cli.Get("/static/ims_testfile.txt");
  12007. ASSERT_TRUE(res1);
  12008. ASSERT_EQ(200, res1->status);
  12009. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12010. std::string last_modified = res1->get_header_value("Last-Modified");
  12011. EXPECT_FALSE(last_modified.empty());
  12012. // If-Modified-Since with same time: expect 304
  12013. Headers h2 = {{"If-Modified-Since", last_modified}};
  12014. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12015. ASSERT_TRUE(res2);
  12016. EXPECT_EQ(304, res2->status);
  12017. // If-Modified-Since with future time: expect 304
  12018. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12019. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12020. ASSERT_TRUE(res3);
  12021. EXPECT_EQ(304, res3->status);
  12022. // If-Modified-Since with past time: expect 200
  12023. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12024. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12025. ASSERT_TRUE(res4);
  12026. EXPECT_EQ(200, res4->status);
  12027. // If-None-Match takes precedence over If-Modified-Since
  12028. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12029. ASSERT_TRUE(res1->has_header("ETag"));
  12030. std::string etag = res1->get_header_value("ETag");
  12031. Headers h5 = {{"If-None-Match", etag},
  12032. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12033. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12034. ASSERT_TRUE(res5);
  12035. EXPECT_EQ(304, res5->status);
  12036. svr.stop();
  12037. t.join();
  12038. std::remove(fname);
  12039. }
  12040. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12041. using namespace httplib;
  12042. Server svr;
  12043. // Endpoint that returns compressible content
  12044. svr.Get("/compressible", [](const Request &, Response &res) {
  12045. // Return a large enough body to trigger compression
  12046. std::string body(1000, 'a');
  12047. res.set_content(body, "text/plain");
  12048. });
  12049. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12050. svr.wait_until_ready();
  12051. Client cli(HOST, PORT);
  12052. // Request with gzip support: should get Vary header when compressed
  12053. cli.set_compress(true);
  12054. auto res1 = cli.Get("/compressible");
  12055. ASSERT_TRUE(res1);
  12056. EXPECT_EQ(200, res1->status);
  12057. // If Content-Encoding is set, Vary should also be set
  12058. if (res1->has_header("Content-Encoding")) {
  12059. EXPECT_TRUE(res1->has_header("Vary"));
  12060. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12061. }
  12062. // Request without Accept-Encoding header: should not have compression
  12063. Headers h_no_compress;
  12064. auto res2 = cli.Get("/compressible", h_no_compress);
  12065. ASSERT_TRUE(res2);
  12066. EXPECT_EQ(200, res2->status);
  12067. // Verify Vary header is present when compression is applied
  12068. // (the exact behavior depends on server configuration)
  12069. svr.stop();
  12070. t.join();
  12071. }
  12072. TEST(ETagTest, IfRangeWithETag) {
  12073. using namespace httplib;
  12074. // Create a test file with known content
  12075. const char *fname = "if_range_testfile.txt";
  12076. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12077. {
  12078. std::ofstream ofs(fname);
  12079. ofs << content;
  12080. ASSERT_TRUE(ofs.good());
  12081. }
  12082. Server svr;
  12083. svr.set_mount_point("/static", ".");
  12084. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12085. svr.wait_until_ready();
  12086. Client cli(HOST, PORT);
  12087. // First request: get ETag
  12088. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12089. ASSERT_TRUE(res1);
  12090. ASSERT_EQ(200, res1->status);
  12091. ASSERT_TRUE(res1->has_header("ETag"));
  12092. std::string etag = res1->get_header_value("ETag");
  12093. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12094. // Since our server generates weak ETags (W/"..."), If-Range with our
  12095. // ETag should NOT result in partial content - it should return full content.
  12096. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12097. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12098. ASSERT_TRUE(res2);
  12099. // Weak ETag in If-Range -> full content (200), not partial (206)
  12100. EXPECT_EQ(200, res2->status);
  12101. EXPECT_EQ(content, res2->body);
  12102. EXPECT_FALSE(res2->has_header("Content-Range"));
  12103. // Range request with non-matching If-Range (ETag): should get 200 (full
  12104. // content)
  12105. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12106. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12107. ASSERT_TRUE(res3);
  12108. EXPECT_EQ(200, res3->status);
  12109. EXPECT_EQ(content, res3->body);
  12110. EXPECT_FALSE(res3->has_header("Content-Range"));
  12111. // Range request with strong ETag (hypothetical - our server doesn't generate
  12112. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12113. // should return full content)
  12114. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12115. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12116. ASSERT_TRUE(res4);
  12117. EXPECT_EQ(200, res4->status);
  12118. EXPECT_EQ(content, res4->body);
  12119. EXPECT_FALSE(res4->has_header("Content-Range"));
  12120. svr.stop();
  12121. t.join();
  12122. std::remove(fname);
  12123. }
  12124. TEST(ETagTest, IfRangeWithDate) {
  12125. using namespace httplib;
  12126. // Create a test file
  12127. const char *fname = "if_range_date_testfile.txt";
  12128. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12129. {
  12130. std::ofstream ofs(fname);
  12131. ofs << content;
  12132. ASSERT_TRUE(ofs.good());
  12133. }
  12134. Server svr;
  12135. svr.set_mount_point("/static", ".");
  12136. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12137. svr.wait_until_ready();
  12138. Client cli(HOST, PORT);
  12139. // First request: get Last-Modified
  12140. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12141. ASSERT_TRUE(res1);
  12142. ASSERT_EQ(200, res1->status);
  12143. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12144. std::string last_modified = res1->get_header_value("Last-Modified");
  12145. // Range request with matching If-Range (date): should get 206
  12146. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12147. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12148. ASSERT_TRUE(res2);
  12149. EXPECT_EQ(206, res2->status);
  12150. EXPECT_EQ("FGHIJ", res2->body);
  12151. // Range request with old If-Range date: should get 200 (full content)
  12152. Headers h3 = {{"Range", "bytes=5-9"},
  12153. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12154. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12155. ASSERT_TRUE(res3);
  12156. EXPECT_EQ(200, res3->status);
  12157. EXPECT_EQ(content, res3->body);
  12158. // Range request with future If-Range date: should get 206
  12159. Headers h4 = {{"Range", "bytes=0-4"},
  12160. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12161. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12162. ASSERT_TRUE(res4);
  12163. EXPECT_EQ(206, res4->status);
  12164. EXPECT_EQ("ABCDE", res4->body);
  12165. svr.stop();
  12166. t.join();
  12167. std::remove(fname);
  12168. }
  12169. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12170. using namespace httplib;
  12171. const char *fname = "etag_malformed.txt";
  12172. const char *content = "malformed-etag";
  12173. {
  12174. std::ofstream ofs(fname);
  12175. ofs << content;
  12176. ASSERT_TRUE(ofs.good());
  12177. }
  12178. Server svr;
  12179. svr.set_mount_point("/static", ".");
  12180. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12181. svr.wait_until_ready();
  12182. Client cli(HOST, PORT);
  12183. // baseline: should get 200 and an ETag
  12184. auto res1 = cli.Get("/static/etag_malformed.txt");
  12185. ASSERT_TRUE(res1);
  12186. ASSERT_EQ(200, res1->status);
  12187. ASSERT_TRUE(res1->has_header("ETag"));
  12188. // Malformed ETag value (missing quotes) should be treated as non-matching
  12189. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12190. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12191. ASSERT_TRUE(res_bad);
  12192. EXPECT_EQ(200, res_bad->status);
  12193. // Whitespace-only header value should be considered invalid / non-matching
  12194. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12195. "Host: localhost\r\n"
  12196. "If-None-Match: \r\n"
  12197. "Connection: close\r\n"
  12198. "\r\n";
  12199. std::string out;
  12200. ASSERT_TRUE(send_request(5, raw_req, &out));
  12201. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12202. svr.stop();
  12203. t.join();
  12204. std::remove(fname);
  12205. }
  12206. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12207. using namespace httplib;
  12208. const char *fname = "ims_invalid_format.txt";
  12209. const char *content = "ims-bad-format";
  12210. {
  12211. std::ofstream ofs(fname);
  12212. ofs << content;
  12213. ASSERT_TRUE(ofs.good());
  12214. }
  12215. Server svr;
  12216. svr.set_mount_point("/static", ".");
  12217. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12218. svr.wait_until_ready();
  12219. Client cli(HOST, PORT);
  12220. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12221. ASSERT_TRUE(res1);
  12222. ASSERT_EQ(200, res1->status);
  12223. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12224. // If-Modified-Since with invalid format should not result in 304
  12225. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12226. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12227. ASSERT_TRUE(res_bad);
  12228. EXPECT_EQ(200, res_bad->status);
  12229. // If-Range with invalid date format should be treated as mismatch -> full
  12230. // content (200)
  12231. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12232. {"If-Range", "invalid-date"}};
  12233. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12234. ASSERT_TRUE(res_ifrange);
  12235. EXPECT_EQ(200, res_ifrange->status);
  12236. svr.stop();
  12237. t.join();
  12238. std::remove(fname);
  12239. }
  12240. TEST(ETagTest, IfRangeWithMalformedETag) {
  12241. using namespace httplib;
  12242. const char *fname = "ifrange_malformed.txt";
  12243. const std::string content = "0123456789";
  12244. {
  12245. std::ofstream ofs(fname);
  12246. ofs << content;
  12247. ASSERT_TRUE(ofs.good());
  12248. }
  12249. Server svr;
  12250. svr.set_mount_point("/static", ".");
  12251. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12252. svr.wait_until_ready();
  12253. Client cli(HOST, PORT);
  12254. // First request: get ETag
  12255. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12256. ASSERT_TRUE(res1);
  12257. ASSERT_EQ(200, res1->status);
  12258. ASSERT_TRUE(res1->has_header("ETag"));
  12259. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12260. // full content (200)
  12261. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12262. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12263. ASSERT_TRUE(res2);
  12264. EXPECT_EQ(200, res2->status);
  12265. EXPECT_EQ(content, res2->body);
  12266. svr.stop();
  12267. t.join();
  12268. std::remove(fname);
  12269. }
  12270. TEST(ETagTest, ExtremeLargeDateValues) {
  12271. using namespace httplib;
  12272. const char *fname = "ims_extreme_date.txt";
  12273. const char *content = "ims-extreme-date";
  12274. {
  12275. std::ofstream ofs(fname);
  12276. ofs << content;
  12277. ASSERT_TRUE(ofs.good());
  12278. }
  12279. Server svr;
  12280. svr.set_mount_point("/static", ".");
  12281. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12282. svr.wait_until_ready();
  12283. Client cli(HOST, PORT);
  12284. auto res1 = cli.Get(std::string("/static/") + fname);
  12285. ASSERT_TRUE(res1);
  12286. ASSERT_EQ(200, res1->status);
  12287. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12288. // Extremely large year that may overflow date parsing routines.
  12289. Headers h_large_date = {
  12290. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12291. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12292. ASSERT_TRUE(res_bad);
  12293. // Expect server to treat this as invalid/mismatch and return full content
  12294. EXPECT_EQ(200, res_bad->status);
  12295. // If-Range with extremely large date should be treated as mismatch -> full
  12296. // content (200)
  12297. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12298. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12299. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12300. ASSERT_TRUE(res_ifrange);
  12301. EXPECT_EQ(200, res_ifrange->status);
  12302. svr.stop();
  12303. t.join();
  12304. std::remove(fname);
  12305. }
  12306. TEST(ETagTest, NegativeFileModificationTime) {
  12307. using namespace httplib;
  12308. const char *fname = "ims_negative_mtime.txt";
  12309. const std::string content = "negative-mtime";
  12310. {
  12311. std::ofstream ofs(fname);
  12312. ofs << content;
  12313. ASSERT_TRUE(ofs.good());
  12314. }
  12315. // Try to set file mtime to a negative value. This may fail on some
  12316. // platforms/filesystems; if it fails, the test will still verify server
  12317. // behaves safely by performing a regular conditional request.
  12318. #if defined(__APPLE__) || defined(__linux__)
  12319. bool set_negative = false;
  12320. do {
  12321. struct timeval times[2];
  12322. // access time: now
  12323. times[0].tv_sec = time(nullptr);
  12324. times[0].tv_usec = 0;
  12325. // modification time: negative (e.g., -1)
  12326. times[1].tv_sec = -1;
  12327. times[1].tv_usec = 0;
  12328. if (utimes(fname, times) == 0) { set_negative = true; }
  12329. } while (0);
  12330. #else
  12331. bool set_negative = false;
  12332. #endif
  12333. Server svr;
  12334. svr.set_mount_point("/static", ".");
  12335. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12336. svr.wait_until_ready();
  12337. Client cli(HOST, PORT);
  12338. auto res1 = cli.Get(std::string("/static/") + fname);
  12339. ASSERT_TRUE(res1);
  12340. ASSERT_EQ(200, res1->status);
  12341. bool has_last_modified = res1->has_header("Last-Modified");
  12342. std::string last_modified;
  12343. if (has_last_modified) {
  12344. last_modified = res1->get_header_value("Last-Modified");
  12345. }
  12346. if (set_negative) {
  12347. // If we successfully set a negative mtime, ensure server returns a
  12348. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12349. // with an old date and ensure server handles it without crash.
  12350. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12351. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12352. ASSERT_TRUE(res2);
  12353. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12354. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12355. } else {
  12356. // Could not set negative mtime on this platform; fall back to verifying
  12357. // that normal invalid/malformed dates are treated safely (non-304).
  12358. Headers h_bad_date = {
  12359. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12360. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12361. ASSERT_TRUE(res_bad);
  12362. EXPECT_EQ(200, res_bad->status);
  12363. }
  12364. svr.stop();
  12365. t.join();
  12366. std::remove(fname);
  12367. }
  12368. //==============================================================================
  12369. // SSE Parsing Tests
  12370. //==============================================================================
  12371. class SSEParsingTest : public ::testing::Test {
  12372. protected:
  12373. // Test helper that mimics SSE parsing behavior
  12374. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12375. int &retry_ms) {
  12376. // Blank line signals end of event
  12377. if (line.empty() || line == "\r") { return true; }
  12378. // Lines starting with ':' are comments (ignored)
  12379. if (!line.empty() && line[0] == ':') { return false; }
  12380. // Find the colon separator
  12381. auto colon_pos = line.find(':');
  12382. if (colon_pos == std::string::npos) {
  12383. // Line with no colon is treated as field name with empty value
  12384. return false;
  12385. }
  12386. std::string field = line.substr(0, colon_pos);
  12387. std::string value;
  12388. // Value starts after colon, skip optional single space
  12389. if (colon_pos + 1 < line.size()) {
  12390. size_t value_start = colon_pos + 1;
  12391. if (line[value_start] == ' ') { value_start++; }
  12392. value = line.substr(value_start);
  12393. // Remove trailing \r if present
  12394. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12395. }
  12396. // Handle known fields
  12397. if (field == "event") {
  12398. msg.event = value;
  12399. } else if (field == "data") {
  12400. // Multiple data lines are concatenated with newlines
  12401. if (!msg.data.empty()) { msg.data += "\n"; }
  12402. msg.data += value;
  12403. } else if (field == "id") {
  12404. // Empty id is valid (clears the last event ID)
  12405. msg.id = value;
  12406. } else if (field == "retry") {
  12407. // Parse retry interval in milliseconds
  12408. {
  12409. int v = 0;
  12410. auto res =
  12411. detail::from_chars(value.data(), value.data() + value.size(), v);
  12412. if (res.ec == std::errc{}) { retry_ms = v; }
  12413. }
  12414. }
  12415. // Unknown fields are ignored per SSE spec
  12416. return false;
  12417. }
  12418. };
  12419. // Test: Single-line data
  12420. TEST_F(SSEParsingTest, SingleLineData) {
  12421. sse::SSEMessage msg;
  12422. int retry_ms = 3000;
  12423. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12424. EXPECT_EQ(msg.data, "hello");
  12425. EXPECT_EQ(msg.event, "message");
  12426. // Blank line ends event
  12427. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12428. }
  12429. // Test: Multi-line data
  12430. TEST_F(SSEParsingTest, MultiLineData) {
  12431. sse::SSEMessage msg;
  12432. int retry_ms = 3000;
  12433. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12434. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12435. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12436. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12437. }
  12438. // Test: Custom event types
  12439. TEST_F(SSEParsingTest, CustomEventType) {
  12440. sse::SSEMessage msg;
  12441. int retry_ms = 3000;
  12442. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12443. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12444. EXPECT_EQ(msg.event, "update");
  12445. EXPECT_EQ(msg.data, "payload");
  12446. }
  12447. // Test: Event ID handling
  12448. TEST_F(SSEParsingTest, EventIdHandling) {
  12449. sse::SSEMessage msg;
  12450. int retry_ms = 3000;
  12451. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12452. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12453. EXPECT_EQ(msg.id, "12345");
  12454. }
  12455. // Test: Empty event ID (clears last event ID)
  12456. TEST_F(SSEParsingTest, EmptyEventId) {
  12457. sse::SSEMessage msg;
  12458. msg.id = "previous";
  12459. int retry_ms = 3000;
  12460. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12461. EXPECT_EQ(msg.id, "");
  12462. }
  12463. // Test: Retry field parsing
  12464. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12465. sse::SSEMessage msg;
  12466. int retry_ms = 3000;
  12467. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12468. EXPECT_EQ(retry_ms, 5000);
  12469. }
  12470. // Test: Invalid retry value
  12471. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12472. sse::SSEMessage msg;
  12473. int retry_ms = 3000;
  12474. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12475. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12476. }
  12477. // Test: Comments (lines starting with :)
  12478. TEST_F(SSEParsingTest, CommentsIgnored) {
  12479. sse::SSEMessage msg;
  12480. int retry_ms = 3000;
  12481. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12482. EXPECT_EQ(msg.data, "");
  12483. EXPECT_EQ(msg.event, "message");
  12484. }
  12485. // Test: Colon in value
  12486. TEST_F(SSEParsingTest, ColonInValue) {
  12487. sse::SSEMessage msg;
  12488. int retry_ms = 3000;
  12489. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12490. EXPECT_EQ(msg.data, "hello:world:test");
  12491. }
  12492. // Test: Line with no colon (field name only)
  12493. TEST_F(SSEParsingTest, FieldNameOnly) {
  12494. sse::SSEMessage msg;
  12495. int retry_ms = 3000;
  12496. // According to SSE spec, this is treated as field name with empty value
  12497. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12498. // Since we don't recognize "data" without colon, data should be empty
  12499. EXPECT_EQ(msg.data, "");
  12500. }
  12501. // Test: Trailing \r handling
  12502. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12503. sse::SSEMessage msg;
  12504. int retry_ms = 3000;
  12505. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12506. EXPECT_EQ(msg.data, "hello");
  12507. }
  12508. // Test: Unknown fields ignored
  12509. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12510. sse::SSEMessage msg;
  12511. int retry_ms = 3000;
  12512. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12513. EXPECT_EQ(msg.data, "");
  12514. EXPECT_EQ(msg.event, "message");
  12515. }
  12516. // Test: Space after colon is optional
  12517. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12518. sse::SSEMessage msg1, msg2;
  12519. int retry_ms = 3000;
  12520. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12521. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12522. EXPECT_EQ(msg1.data, "hello");
  12523. EXPECT_EQ(msg2.data, "hello");
  12524. }
  12525. // Test: SSEMessage clear
  12526. TEST_F(SSEParsingTest, MessageClear) {
  12527. sse::SSEMessage msg;
  12528. msg.event = "custom";
  12529. msg.data = "some data";
  12530. msg.id = "123";
  12531. msg.clear();
  12532. EXPECT_EQ(msg.event, "message");
  12533. EXPECT_EQ(msg.data, "");
  12534. EXPECT_EQ(msg.id, "");
  12535. }
  12536. // Test: Complete event parsing
  12537. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12538. sse::SSEMessage msg;
  12539. int retry_ms = 3000;
  12540. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12541. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12542. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12543. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12544. // Blank line ends event
  12545. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12546. EXPECT_EQ(msg.event, "notification");
  12547. EXPECT_EQ(msg.id, "evt-42");
  12548. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12549. EXPECT_EQ(retry_ms, 1000);
  12550. }
  12551. //==============================================================================
  12552. // Integration Tests with Server
  12553. //==============================================================================
  12554. class SSEIntegrationTest : public ::testing::Test {
  12555. protected:
  12556. void SetUp() override {
  12557. stop_server_.store(false);
  12558. events_.clear();
  12559. server_ = httplib::detail::make_unique<Server>();
  12560. setup_server();
  12561. start_server();
  12562. }
  12563. void TearDown() override {
  12564. stop_server_.store(true);
  12565. event_cv_.notify_all();
  12566. server_->stop();
  12567. if (server_thread_.joinable()) { server_thread_.join(); }
  12568. }
  12569. void setup_server() {
  12570. // Simple SSE endpoint
  12571. server_->Get("/events", [this](const Request &req, Response &res) {
  12572. auto last_id = req.get_header_value("Last-Event-ID");
  12573. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12574. res.set_chunked_content_provider(
  12575. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12576. std::unique_lock<std::mutex> lock(event_mutex_);
  12577. if (event_cv_.wait_for(
  12578. lock, std::chrono::milliseconds(200), [this] {
  12579. return !events_.empty() || stop_server_.load();
  12580. })) {
  12581. if (stop_server_.load()) { return false; }
  12582. if (!events_.empty()) {
  12583. std::string event = events_.front();
  12584. events_.erase(events_.begin());
  12585. sink.write(event.data(), event.size());
  12586. return true;
  12587. }
  12588. }
  12589. return !stop_server_.load();
  12590. });
  12591. });
  12592. // Endpoint that returns error
  12593. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12594. res.status = 500;
  12595. res.set_content("Internal Server Error", "text/plain");
  12596. });
  12597. // Endpoint for custom event types
  12598. server_->Get("/custom-events", [](const Request &, Response &res) {
  12599. res.set_chunked_content_provider(
  12600. "text/event-stream", [](size_t offset, DataSink &sink) {
  12601. if (offset == 0) {
  12602. std::string event = "event: update\ndata: updated\n\n"
  12603. "event: delete\ndata: deleted\n\n";
  12604. sink.write(event.data(), event.size());
  12605. }
  12606. return false; // End stream after sending
  12607. });
  12608. });
  12609. }
  12610. void start_server() {
  12611. port_ = server_->bind_to_any_port(HOST);
  12612. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12613. // Wait for server to start
  12614. while (!server_->is_running()) {
  12615. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12616. }
  12617. }
  12618. int get_port() const { return port_; }
  12619. void send_event(const std::string &event) {
  12620. std::lock_guard<std::mutex> lock(event_mutex_);
  12621. events_.push_back(event);
  12622. event_cv_.notify_all();
  12623. }
  12624. std::unique_ptr<Server> server_;
  12625. std::thread server_thread_;
  12626. std::mutex event_mutex_;
  12627. std::condition_variable event_cv_;
  12628. std::vector<std::string> events_;
  12629. std::atomic<bool> stop_server_{false};
  12630. std::string last_received_event_id_;
  12631. int port_ = 0;
  12632. };
  12633. // Test: Successful connection and on_open callback
  12634. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12635. // Add a simple endpoint that sends one event and closes
  12636. server_->Get("/simple-event", [](const Request &, Response &res) {
  12637. res.set_chunked_content_provider(
  12638. "text/event-stream", [](size_t offset, DataSink &sink) {
  12639. if (offset == 0) {
  12640. std::string event = "data: hello\n\n";
  12641. sink.write(event.data(), event.size());
  12642. }
  12643. return false; // Close stream after sending
  12644. });
  12645. });
  12646. Client client("localhost", get_port());
  12647. sse::SSEClient sse(client, "/simple-event");
  12648. std::atomic<bool> open_called{false};
  12649. std::atomic<bool> message_received{false};
  12650. sse.on_open([&open_called]() { open_called.store(true); });
  12651. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12652. if (msg.data == "hello") { message_received.store(true); }
  12653. });
  12654. sse.set_reconnect_interval(100);
  12655. sse.set_max_reconnect_attempts(1);
  12656. // Start async
  12657. sse.start_async();
  12658. // Wait for message to be processed
  12659. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12660. sse.stop();
  12661. EXPECT_TRUE(open_called.load());
  12662. EXPECT_TRUE(message_received.load());
  12663. }
  12664. // Test: on_message callback
  12665. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12666. // Endpoint that sends multiple events then closes
  12667. server_->Get("/multi-event", [](const Request &, Response &res) {
  12668. res.set_chunked_content_provider(
  12669. "text/event-stream", [](size_t offset, DataSink &sink) {
  12670. if (offset == 0) {
  12671. std::string events = "data: message1\n\ndata: message2\n\n";
  12672. sink.write(events.data(), events.size());
  12673. }
  12674. return false;
  12675. });
  12676. });
  12677. Client client("localhost", get_port());
  12678. sse::SSEClient sse(client, "/multi-event");
  12679. std::vector<std::string> received_messages;
  12680. std::mutex messages_mutex;
  12681. sse.on_message([&](const sse::SSEMessage &msg) {
  12682. std::lock_guard<std::mutex> lock(messages_mutex);
  12683. received_messages.push_back(msg.data);
  12684. });
  12685. sse.set_reconnect_interval(100);
  12686. sse.set_max_reconnect_attempts(1);
  12687. sse.start_async();
  12688. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12689. sse.stop();
  12690. std::lock_guard<std::mutex> lock(messages_mutex);
  12691. EXPECT_GE(received_messages.size(), 2u);
  12692. if (received_messages.size() >= 2) {
  12693. EXPECT_EQ(received_messages[0], "message1");
  12694. EXPECT_EQ(received_messages[1], "message2");
  12695. }
  12696. }
  12697. // Test: on_event for specific types
  12698. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12699. Client client("localhost", get_port());
  12700. sse::SSEClient sse(client, "/custom-events");
  12701. std::atomic<bool> update_received{false};
  12702. std::atomic<bool> delete_received{false};
  12703. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12704. if (msg.data == "updated") { update_received.store(true); }
  12705. });
  12706. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12707. if (msg.data == "deleted") { delete_received.store(true); }
  12708. });
  12709. sse.set_max_reconnect_attempts(1);
  12710. sse.start_async();
  12711. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12712. sse.stop();
  12713. EXPECT_TRUE(update_received.load());
  12714. EXPECT_TRUE(delete_received.load());
  12715. }
  12716. // Test: on_error callback on connection failure
  12717. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12718. // Connect to a non-existent port
  12719. Client client("localhost", 59999);
  12720. sse::SSEClient sse(client, "/events");
  12721. std::atomic<bool> error_called{false};
  12722. Error received_error = Error::Success;
  12723. sse.on_error([&](Error err) {
  12724. error_called.store(true);
  12725. received_error = err;
  12726. });
  12727. sse.set_reconnect_interval(50);
  12728. sse.set_max_reconnect_attempts(1);
  12729. sse.start_async();
  12730. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12731. sse.stop();
  12732. EXPECT_TRUE(error_called.load());
  12733. EXPECT_NE(received_error, Error::Success);
  12734. }
  12735. // Test: Last-Event-ID header sent on reconnect
  12736. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12737. // Endpoint that sends event with ID
  12738. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12739. res.set_chunked_content_provider(
  12740. "text/event-stream", [](size_t offset, DataSink &sink) {
  12741. if (offset == 0) {
  12742. std::string event = "id: evt-123\ndata: test\n\n";
  12743. sink.write(event.data(), event.size());
  12744. }
  12745. return false;
  12746. });
  12747. });
  12748. Client client("localhost", get_port());
  12749. sse::SSEClient sse(client, "/event-with-id");
  12750. std::atomic<bool> id_received{false};
  12751. sse.on_message([&](const sse::SSEMessage &msg) {
  12752. if (!msg.id.empty()) { id_received.store(true); }
  12753. });
  12754. sse.set_reconnect_interval(100);
  12755. sse.set_max_reconnect_attempts(1);
  12756. sse.start_async();
  12757. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12758. sse.stop();
  12759. EXPECT_TRUE(id_received.load());
  12760. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12761. }
  12762. // Test: Manual stop
  12763. TEST_F(SSEIntegrationTest, ManualStop) {
  12764. // Endpoint that sends one event and stays open briefly
  12765. std::atomic<bool> handler_running{true};
  12766. server_->Get("/stay-open", [&handler_running](const Request &,
  12767. Response &res) {
  12768. res.set_chunked_content_provider(
  12769. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12770. if (offset == 0) {
  12771. std::string event = "data: connected\n\n";
  12772. sink.write(event.data(), event.size());
  12773. }
  12774. // Keep connection open while handler_running is true
  12775. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12776. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12777. }
  12778. return false;
  12779. });
  12780. });
  12781. Client client("localhost", get_port());
  12782. sse::SSEClient sse(client, "/stay-open");
  12783. std::atomic<bool> connected{false};
  12784. sse.on_open([&connected]() { connected.store(true); });
  12785. sse.set_reconnect_interval(100);
  12786. sse.set_max_reconnect_attempts(1);
  12787. sse.start_async();
  12788. // Wait for connection to establish
  12789. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12790. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12791. }
  12792. EXPECT_TRUE(connected.load());
  12793. EXPECT_TRUE(sse.is_connected());
  12794. // Signal handler to stop
  12795. handler_running.store(false);
  12796. // Stop SSE client
  12797. sse.stop();
  12798. EXPECT_FALSE(sse.is_connected());
  12799. }
  12800. // Test: SSEClient with custom headers
  12801. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12802. // Setup a server endpoint that checks for custom header
  12803. std::atomic<bool> header_received{false};
  12804. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12805. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12806. header_received.store(true);
  12807. }
  12808. res.set_chunked_content_provider("text/event-stream",
  12809. [](size_t, DataSink &) { return false; });
  12810. });
  12811. Client client("localhost", get_port());
  12812. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12813. sse::SSEClient sse(client, "/header-check", headers);
  12814. sse.set_max_reconnect_attempts(1);
  12815. sse.start_async();
  12816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12817. sse.stop();
  12818. EXPECT_TRUE(header_received.load());
  12819. }
  12820. // Test: Reconnect interval configuration
  12821. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12822. Client client("localhost", get_port());
  12823. sse::SSEClient sse(client, "/events");
  12824. auto &result = sse.set_reconnect_interval(500);
  12825. // Builder pattern should return reference to self
  12826. EXPECT_EQ(&result, &sse);
  12827. }
  12828. // Test: Max reconnect attempts
  12829. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12830. // Connect to non-existent port to force reconnects
  12831. Client client("localhost", 59998);
  12832. sse::SSEClient sse(client, "/events");
  12833. std::atomic<int> error_count{0};
  12834. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12835. sse.set_reconnect_interval(50);
  12836. sse.set_max_reconnect_attempts(2);
  12837. auto start = std::chrono::steady_clock::now();
  12838. sse.start(); // Blocking call
  12839. auto end = std::chrono::steady_clock::now();
  12840. // Should have stopped after 2 failed attempts
  12841. EXPECT_GE(error_count.load(), 2);
  12842. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12843. auto duration =
  12844. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12845. #ifdef _WIN32
  12846. // Windows is much slower for socket connection failures
  12847. EXPECT_LT(duration.count(), 7000);
  12848. #else
  12849. EXPECT_LT(duration.count(), 1000);
  12850. #endif
  12851. }
  12852. // Test: Multi-line data in integration
  12853. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12854. // Endpoint with multi-line data
  12855. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12856. res.set_chunked_content_provider(
  12857. "text/event-stream", [](size_t offset, DataSink &sink) {
  12858. if (offset == 0) {
  12859. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12860. sink.write(event.data(), event.size());
  12861. }
  12862. return false;
  12863. });
  12864. });
  12865. Client client("localhost", get_port());
  12866. sse::SSEClient sse(client, "/multiline-data");
  12867. std::string received_data;
  12868. std::mutex data_mutex;
  12869. sse.on_message([&](const sse::SSEMessage &msg) {
  12870. std::lock_guard<std::mutex> lock(data_mutex);
  12871. received_data = msg.data;
  12872. });
  12873. sse.set_reconnect_interval(100);
  12874. sse.set_max_reconnect_attempts(1);
  12875. sse.start_async();
  12876. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12877. sse.stop();
  12878. std::lock_guard<std::mutex> lock(data_mutex);
  12879. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12880. }
  12881. // Test: Auto-reconnect after server disconnection
  12882. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12883. std::atomic<int> connection_count{0};
  12884. std::atomic<int> message_count{0};
  12885. // Endpoint that sends one event and closes, forcing reconnect
  12886. server_->Get("/reconnect-test",
  12887. [&connection_count](const Request &, Response &res) {
  12888. connection_count.fetch_add(1);
  12889. res.set_chunked_content_provider(
  12890. "text/event-stream", [](size_t offset, DataSink &sink) {
  12891. if (offset == 0) {
  12892. std::string event = "data: hello\n\n";
  12893. sink.write(event.data(), event.size());
  12894. }
  12895. return false; // Close connection after sending
  12896. });
  12897. });
  12898. Client client("localhost", get_port());
  12899. sse::SSEClient sse(client, "/reconnect-test");
  12900. sse.on_message([&message_count](const sse::SSEMessage &) {
  12901. message_count.fetch_add(1);
  12902. });
  12903. sse.set_reconnect_interval(100);
  12904. sse.set_max_reconnect_attempts(3);
  12905. sse.start_async();
  12906. // Wait long enough for multiple reconnects
  12907. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12908. sse.stop();
  12909. // Should have connected multiple times (initial + reconnects)
  12910. EXPECT_GE(connection_count.load(), 2);
  12911. // Should have received messages from multiple connections
  12912. EXPECT_GE(message_count.load(), 2);
  12913. }
  12914. // Test: Last-Event-ID sent on reconnect
  12915. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12916. std::atomic<int> connection_count{0};
  12917. std::vector<std::string> received_last_event_ids;
  12918. std::mutex id_mutex;
  12919. // Endpoint that checks Last-Event-ID header and sends event with ID
  12920. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12921. int conn = connection_count.fetch_add(1);
  12922. // Capture the Last-Event-ID header from each connection
  12923. {
  12924. std::lock_guard<std::mutex> lock(id_mutex);
  12925. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12926. }
  12927. res.set_chunked_content_provider(
  12928. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12929. if (offset == 0) {
  12930. std::string event =
  12931. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12932. sink.write(event.data(), event.size());
  12933. }
  12934. return false;
  12935. });
  12936. });
  12937. Client client("localhost", get_port());
  12938. sse::SSEClient sse(client, "/reconnect-with-id");
  12939. sse.set_reconnect_interval(100);
  12940. sse.set_max_reconnect_attempts(3);
  12941. sse.start_async();
  12942. // Wait for at least 2 connections
  12943. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12944. sse.stop();
  12945. // Verify behavior
  12946. std::lock_guard<std::mutex> lock(id_mutex);
  12947. EXPECT_GE(received_last_event_ids.size(), 2u);
  12948. // First connection should have no Last-Event-ID
  12949. if (!received_last_event_ids.empty()) {
  12950. EXPECT_EQ(received_last_event_ids[0], "");
  12951. }
  12952. // Second connection should have Last-Event-ID from first connection
  12953. if (received_last_event_ids.size() >= 2) {
  12954. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12955. }
  12956. }
  12957. TEST(Issue2318Test, EmptyHostString) {
  12958. {
  12959. httplib::Client cli_empty("", PORT);
  12960. auto res = cli_empty.Get("/");
  12961. ASSERT_FALSE(res);
  12962. EXPECT_EQ(httplib::Error::Connection, res.error());
  12963. }
  12964. {
  12965. httplib::Client cli(" ", PORT);
  12966. auto res = cli.Get("/");
  12967. ASSERT_FALSE(res);
  12968. EXPECT_EQ(httplib::Error::Connection, res.error());
  12969. }
  12970. }
  12971. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12972. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12973. Server svr;
  12974. // Set a small payload limit (1KB)
  12975. svr.set_payload_max_length(1024);
  12976. svr.Post("/test", [&](const Request &req, Response &res) {
  12977. res.set_content("Body size: " + std::to_string(req.body.size()),
  12978. "text/plain");
  12979. });
  12980. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12981. auto se = detail::scope_exit([&] {
  12982. svr.stop();
  12983. listen_thread.join();
  12984. });
  12985. svr.wait_until_ready();
  12986. // Create data that compresses well but exceeds limit when decompressed
  12987. // 8KB of repeated null bytes compresses to a very small size
  12988. std::string original_data(8 * 1024, '\0');
  12989. // Compress the data using gzip
  12990. std::string compressed_data;
  12991. detail::gzip_compressor compressor;
  12992. compressor.compress(original_data.data(), original_data.size(), true,
  12993. [&](const char *data, size_t size) {
  12994. compressed_data.append(data, size);
  12995. return true;
  12996. });
  12997. // Verify compression worked (compressed should be much smaller)
  12998. ASSERT_LT(compressed_data.size(), original_data.size());
  12999. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13000. // Send compressed data with Content-Encoding: gzip
  13001. Client cli(HOST, PORT);
  13002. Headers headers = {{"Content-Encoding", "gzip"}};
  13003. auto res =
  13004. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13005. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13006. ASSERT_TRUE(res);
  13007. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13008. }
  13009. #endif
  13010. // ============================================================================
  13011. // OpenSSL-Specific Tests
  13012. // ============================================================================
  13013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13014. X509 *readCertificate(const std::string &strFileName) {
  13015. std::ifstream inStream(strFileName);
  13016. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13017. std::istreambuf_iterator<char>());
  13018. if (strCertPEM.empty()) return (nullptr);
  13019. BIO *pbCert = BIO_new(BIO_s_mem());
  13020. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13021. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13022. BIO_free(pbCert);
  13023. return (pCert);
  13024. }
  13025. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13026. std::ifstream inStream(strFileName);
  13027. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13028. std::istreambuf_iterator<char>());
  13029. if (strPrivateKeyPEM.empty()) return (nullptr);
  13030. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13031. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13032. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13033. BIO_free(pbPrivKey);
  13034. return (pPrivateKey);
  13035. }
  13036. TEST(BindServerTest, UpdateCerts) {
  13037. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13038. int port = svr.bind_to_any_port("0.0.0.0");
  13039. ASSERT_TRUE(svr.is_valid());
  13040. ASSERT_TRUE(port > 0);
  13041. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13042. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13043. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13044. ASSERT_TRUE(cert != nullptr);
  13045. ASSERT_TRUE(ca_cert != nullptr);
  13046. ASSERT_TRUE(key != nullptr);
  13047. X509_STORE *cert_store = X509_STORE_new();
  13048. X509_STORE_add_cert(cert_store, ca_cert);
  13049. // svr.update_certs(cert, key, cert_store); // deprecated
  13050. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13051. CLIENT_CA_CERT_FILE);
  13052. ASSERT_TRUE(svr.is_valid());
  13053. svr.stop();
  13054. X509_STORE_free(cert_store);
  13055. X509_free(cert);
  13056. X509_free(ca_cert);
  13057. EVP_PKEY_free(key);
  13058. }
  13059. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13060. // client CA list correctly for TLS handshake
  13061. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13062. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13063. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13064. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13065. ASSERT_TRUE(cert != nullptr);
  13066. ASSERT_TRUE(ca_cert != nullptr);
  13067. ASSERT_TRUE(key != nullptr);
  13068. X509_STORE *cert_store = X509_STORE_new();
  13069. X509_STORE_add_cert(cert_store, ca_cert);
  13070. // Use X509-based constructor (deprecated but should still work correctly)
  13071. #pragma GCC diagnostic push
  13072. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13073. SSLServer svr(cert, key, cert_store);
  13074. #pragma GCC diagnostic pop
  13075. ASSERT_TRUE(svr.is_valid());
  13076. // Verify that client CA list is set in SSL_CTX
  13077. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13078. ASSERT_TRUE(ssl_ctx != nullptr);
  13079. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13080. ASSERT_TRUE(ca_list != nullptr);
  13081. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13082. X509_free(cert);
  13083. X509_free(ca_cert);
  13084. EVP_PKEY_free(key);
  13085. }
  13086. // Test that update_certs() updates client CA list correctly
  13087. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13088. // Start with file-based constructor
  13089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13090. ASSERT_TRUE(svr.is_valid());
  13091. // Initially no client CA list should be set
  13092. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13093. ASSERT_TRUE(ssl_ctx != nullptr);
  13094. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13095. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13096. EXPECT_EQ(0, count_before);
  13097. // Now update with client CA (PEM string)
  13098. std::string cert_pem, key_pem, ca_pem;
  13099. read_file(SERVER_CERT_FILE, cert_pem);
  13100. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13101. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13102. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13103. ASSERT_TRUE(svr.is_valid());
  13104. // Now client CA list should be set
  13105. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13106. ASSERT_TRUE(ca_list_after != nullptr);
  13107. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13108. }
  13109. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13110. // Test that the file-path SSLServer constructor properly sets the client CA
  13111. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13113. ASSERT_TRUE(svr.is_valid());
  13114. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13115. ASSERT_TRUE(ssl_ctx != nullptr);
  13116. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13117. ASSERT_TRUE(ca_list != nullptr);
  13118. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13119. }
  13120. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13121. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13122. // prepare large data
  13123. std::random_device seed_gen;
  13124. std::mt19937 random(seed_gen());
  13125. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13126. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13127. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13128. // server
  13129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13130. ASSERT_TRUE(svr.is_valid());
  13131. svr.Post("/binary", [&](const Request &req, Response &res) {
  13132. EXPECT_EQ(large_size_byte, req.body.size());
  13133. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13134. res.set_content(req.body, "application/octet-stream");
  13135. });
  13136. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13137. auto se = detail::scope_exit([&] {
  13138. svr.stop();
  13139. listen_thread.join();
  13140. ASSERT_FALSE(svr.is_running());
  13141. });
  13142. svr.wait_until_ready();
  13143. // client POST
  13144. SSLClient cli("localhost", PORT);
  13145. cli.enable_server_certificate_verification(false);
  13146. cli.set_read_timeout(std::chrono::seconds(100));
  13147. cli.set_write_timeout(std::chrono::seconds(100));
  13148. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13149. large_size_byte, "application/octet-stream");
  13150. // compare
  13151. EXPECT_EQ(StatusCode::OK_200, res->status);
  13152. EXPECT_EQ(large_size_byte, res->body.size());
  13153. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13154. }
  13155. #endif
  13156. // ============================================================================
  13157. // MbedTLS-Specific Tests
  13158. // ============================================================================
  13159. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13160. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13161. using namespace httplib::tls;
  13162. // Track if callback was invoked
  13163. bool callback_invoked = false;
  13164. // The callback receives void* ctx which is actually MbedTlsContext*
  13165. // We can access the mbedtls_ssl_config via the context
  13166. auto setup_callback = [&callback_invoked](void *ctx) {
  13167. callback_invoked = true;
  13168. // Cast to MbedTlsContext* to access the ssl config
  13169. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13170. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13171. // Use static variables to hold certificate data (simplified for test)
  13172. static mbedtls_x509_crt own_cert;
  13173. static mbedtls_pk_context own_key;
  13174. static mbedtls_x509_crt ca_chain;
  13175. static bool initialized = false;
  13176. if (!initialized) {
  13177. mbedtls_x509_crt_init(&own_cert);
  13178. mbedtls_pk_init(&own_key);
  13179. mbedtls_x509_crt_init(&ca_chain);
  13180. // Load server certificate
  13181. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13182. return false;
  13183. }
  13184. // Load server private key
  13185. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13186. #if MBEDTLS_VERSION_MAJOR >= 3
  13187. ,
  13188. mbedtls_ctr_drbg_random, nullptr
  13189. #endif
  13190. ) != 0) {
  13191. return false;
  13192. }
  13193. // Load CA chain for client verification
  13194. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13195. return false;
  13196. }
  13197. initialized = true;
  13198. }
  13199. // Configure the SSL config
  13200. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13201. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13202. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13203. // Set minimum TLS version using mbedTLS native API
  13204. #if MBEDTLS_VERSION_MAJOR >= 3
  13205. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13206. #else
  13207. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13208. MBEDTLS_SSL_MINOR_VERSION_3);
  13209. #endif
  13210. return true;
  13211. };
  13212. SSLServer svr(setup_callback);
  13213. ASSERT_TRUE(svr.is_valid());
  13214. ASSERT_TRUE(callback_invoked);
  13215. svr.Get("/test", [&](const Request &req, Response &res) {
  13216. res.set_content("test", "text/plain");
  13217. auto cert = req.peer_cert();
  13218. ASSERT_TRUE(static_cast<bool>(cert));
  13219. auto common_name = cert.subject_cn();
  13220. EXPECT_EQ("Common Name", common_name);
  13221. });
  13222. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. t.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13230. cli.enable_server_certificate_verification(false);
  13231. cli.set_connection_timeout(30);
  13232. auto res = cli.Get("/test");
  13233. ASSERT_TRUE(res);
  13234. ASSERT_EQ(StatusCode::OK_200, res->status);
  13235. }
  13236. #endif
  13237. // WebSocket Tests
  13238. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13239. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13240. // defining the meaning of these bits has been negotiated.
  13241. auto make_frame = [](uint8_t first_byte) {
  13242. std::string frame;
  13243. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13244. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13245. frame += "Hello";
  13246. return frame;
  13247. };
  13248. // RSV1 set (0x40)
  13249. {
  13250. detail::BufferStream strm;
  13251. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13252. ws::Opcode opcode;
  13253. std::string payload;
  13254. bool fin;
  13255. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13256. false, 1024));
  13257. }
  13258. // RSV2 set (0x20)
  13259. {
  13260. detail::BufferStream strm;
  13261. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13262. ws::Opcode opcode;
  13263. std::string payload;
  13264. bool fin;
  13265. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13266. false, 1024));
  13267. }
  13268. // RSV3 set (0x10)
  13269. {
  13270. detail::BufferStream strm;
  13271. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13272. ws::Opcode opcode;
  13273. std::string payload;
  13274. bool fin;
  13275. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13276. false, 1024));
  13277. }
  13278. // No RSV bits set - should succeed
  13279. {
  13280. detail::BufferStream strm;
  13281. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13282. ws::Opcode opcode;
  13283. std::string payload;
  13284. bool fin;
  13285. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13286. false, 1024));
  13287. EXPECT_EQ(ws::Opcode::Text, opcode);
  13288. EXPECT_EQ("Hello", payload);
  13289. EXPECT_TRUE(fin);
  13290. }
  13291. }
  13292. TEST(WebSocketTest, ControlFrameValidation) {
  13293. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13294. // payload length <= 125.
  13295. // Ping with FIN=0 - must be rejected
  13296. {
  13297. detail::BufferStream strm;
  13298. std::string frame;
  13299. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13300. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13301. strm.write(frame.data(), frame.size());
  13302. ws::Opcode opcode;
  13303. std::string payload;
  13304. bool fin;
  13305. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13306. false, 1024));
  13307. }
  13308. // Close with FIN=0 - must be rejected
  13309. {
  13310. detail::BufferStream strm;
  13311. std::string frame;
  13312. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13313. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13314. strm.write(frame.data(), frame.size());
  13315. ws::Opcode opcode;
  13316. std::string payload;
  13317. bool fin;
  13318. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13319. false, 1024));
  13320. }
  13321. // Ping with payload_len=126 (extended length) - must be rejected
  13322. {
  13323. detail::BufferStream strm;
  13324. std::string frame;
  13325. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13326. frame += static_cast<char>(126); // payload_len=126 (>125)
  13327. frame += static_cast<char>(0x00); // extended length high byte
  13328. frame += static_cast<char>(126); // extended length low byte
  13329. frame += std::string(126, 'x');
  13330. strm.write(frame.data(), frame.size());
  13331. ws::Opcode opcode;
  13332. std::string payload;
  13333. bool fin;
  13334. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13335. false, 1024));
  13336. }
  13337. // Ping with FIN=1 and payload_len=125 - should succeed
  13338. {
  13339. detail::BufferStream strm;
  13340. std::string frame;
  13341. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13342. frame += static_cast<char>(125); // payload_len=125
  13343. frame += std::string(125, 'x');
  13344. strm.write(frame.data(), frame.size());
  13345. ws::Opcode opcode;
  13346. std::string payload;
  13347. bool fin;
  13348. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13349. false, 1024));
  13350. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13351. EXPECT_EQ(125u, payload.size());
  13352. EXPECT_TRUE(fin);
  13353. }
  13354. }
  13355. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13356. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13357. // length MUST be 0.
  13358. // MSB set - must be rejected
  13359. {
  13360. detail::BufferStream strm;
  13361. std::string frame;
  13362. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13363. frame += static_cast<char>(127); // 64-bit extended length
  13364. frame += static_cast<char>(0x80); // MSB set (invalid)
  13365. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13366. strm.write(frame.data(), frame.size());
  13367. ws::Opcode opcode;
  13368. std::string payload;
  13369. bool fin;
  13370. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13371. false, 1024));
  13372. }
  13373. // MSB clear - should pass length parsing (will be rejected by max_len,
  13374. // but that's a different check; use a small length to verify)
  13375. {
  13376. detail::BufferStream strm;
  13377. std::string frame;
  13378. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13379. frame += static_cast<char>(127); // 64-bit extended length
  13380. frame += std::string(7, '\0'); // high bytes = 0
  13381. frame += static_cast<char>(0x03); // length = 3
  13382. frame += "abc";
  13383. strm.write(frame.data(), frame.size());
  13384. ws::Opcode opcode;
  13385. std::string payload;
  13386. bool fin;
  13387. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13388. false, 1024));
  13389. EXPECT_EQ(ws::Opcode::Text, opcode);
  13390. EXPECT_EQ("abc", payload);
  13391. }
  13392. }
  13393. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13394. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13395. // Valid UTF-8
  13396. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13397. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13398. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13399. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13400. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13401. // Invalid UTF-8
  13402. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13403. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13404. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13405. EXPECT_FALSE(
  13406. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13407. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13408. }
  13409. TEST(WebSocketTest, ConnectAndDisconnect) {
  13410. Server svr;
  13411. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13412. std::string msg;
  13413. while (ws.read(msg)) {}
  13414. });
  13415. auto port = svr.bind_to_any_port(HOST);
  13416. std::thread t([&]() { svr.listen_after_bind(); });
  13417. svr.wait_until_ready();
  13418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13419. ASSERT_TRUE(client.connect());
  13420. EXPECT_TRUE(client.is_open());
  13421. client.close();
  13422. EXPECT_FALSE(client.is_open());
  13423. svr.stop();
  13424. t.join();
  13425. }
  13426. TEST(WebSocketTest, ValidURL) {
  13427. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13428. EXPECT_TRUE(ws1.is_valid());
  13429. ws::WebSocketClient ws2("ws://example.com/path");
  13430. EXPECT_TRUE(ws2.is_valid());
  13431. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13432. EXPECT_TRUE(ws3.is_valid());
  13433. #ifdef CPPHTTPLIB_SSL_ENABLED
  13434. ws::WebSocketClient wss1("wss://example.com/path");
  13435. EXPECT_TRUE(wss1.is_valid());
  13436. ws::WebSocketClient wss2("wss://example.com:443/path");
  13437. EXPECT_TRUE(wss2.is_valid());
  13438. #endif
  13439. }
  13440. TEST(WebSocketTest, InvalidURL) {
  13441. // No scheme
  13442. ws::WebSocketClient ws1("localhost:8080/path");
  13443. EXPECT_FALSE(ws1.is_valid());
  13444. // No path
  13445. ws::WebSocketClient ws2("ws://localhost:8080");
  13446. EXPECT_FALSE(ws2.is_valid());
  13447. // Empty string
  13448. ws::WebSocketClient ws3("");
  13449. EXPECT_FALSE(ws3.is_valid());
  13450. // Missing host
  13451. ws::WebSocketClient ws4("ws://:8080/path");
  13452. EXPECT_FALSE(ws4.is_valid());
  13453. }
  13454. TEST(WebSocketTest, UnsupportedScheme) {
  13455. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13456. ws::WebSocketClient ws1("http://localhost:8080/path");
  13457. EXPECT_FALSE(ws1.is_valid());
  13458. ws::WebSocketClient ws2("https://localhost:8080/path");
  13459. EXPECT_FALSE(ws2.is_valid());
  13460. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13461. EXPECT_FALSE(ws3.is_valid());
  13462. #else
  13463. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13464. std::invalid_argument);
  13465. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13466. std::invalid_argument);
  13467. #endif
  13468. }
  13469. TEST(WebSocketTest, ConnectWhenInvalid) {
  13470. ws::WebSocketClient ws("not a valid url");
  13471. EXPECT_FALSE(ws.is_valid());
  13472. EXPECT_FALSE(ws.connect());
  13473. }
  13474. TEST(WebSocketTest, DefaultPort) {
  13475. ws::WebSocketClient ws1("ws://example.com/path");
  13476. EXPECT_TRUE(ws1.is_valid());
  13477. // ws:// defaults to port 80 (verified by successful parse)
  13478. #ifdef CPPHTTPLIB_SSL_ENABLED
  13479. ws::WebSocketClient ws2("wss://example.com/path");
  13480. EXPECT_TRUE(ws2.is_valid());
  13481. // wss:// defaults to port 443 (verified by successful parse)
  13482. #endif
  13483. }
  13484. TEST(WebSocketTest, IPv6LiteralAddress) {
  13485. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13486. EXPECT_TRUE(ws1.is_valid());
  13487. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13488. EXPECT_TRUE(ws2.is_valid());
  13489. }
  13490. TEST(WebSocketTest, ComplexPath) {
  13491. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13492. EXPECT_TRUE(ws1.is_valid());
  13493. ws::WebSocketClient ws2("ws://localhost:8080/");
  13494. EXPECT_TRUE(ws2.is_valid());
  13495. }
  13496. class WebSocketIntegrationTest : public ::testing::Test {
  13497. protected:
  13498. void SetUp() override {
  13499. server_ = httplib::detail::make_unique<Server>();
  13500. setup_server();
  13501. start_server();
  13502. }
  13503. void TearDown() override {
  13504. server_->stop();
  13505. if (server_thread_.joinable()) { server_thread_.join(); }
  13506. }
  13507. void setup_server() {
  13508. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13509. std::string msg;
  13510. ws::ReadResult ret;
  13511. while ((ret = ws.read(msg))) {
  13512. if (ret == ws::Binary) {
  13513. ws.send(msg.data(), msg.size());
  13514. } else {
  13515. ws.send(msg);
  13516. }
  13517. }
  13518. });
  13519. server_->WebSocket("/ws-echo-string",
  13520. [](const Request &, ws::WebSocket &ws) {
  13521. std::string msg;
  13522. while (ws.read(msg)) {
  13523. ws.send("echo: " + msg);
  13524. }
  13525. });
  13526. server_->WebSocket(
  13527. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13528. // Echo back request metadata
  13529. ws.send("path:" + req.path);
  13530. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13531. std::string msg;
  13532. while (ws.read(msg)) {}
  13533. });
  13534. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13535. std::string msg;
  13536. ws.read(msg); // wait for a message
  13537. ws.close();
  13538. });
  13539. server_->WebSocket("/ws-close-status",
  13540. [](const Request &, ws::WebSocket &ws) {
  13541. std::string msg;
  13542. ws.read(msg); // wait for a message
  13543. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13544. });
  13545. server_->WebSocket(
  13546. "/ws-subprotocol",
  13547. [](const Request &, ws::WebSocket &ws) {
  13548. std::string msg;
  13549. while (ws.read(msg)) {
  13550. ws.send(msg);
  13551. }
  13552. },
  13553. [](const std::vector<std::string> &protocols) -> std::string {
  13554. for (const auto &p : protocols) {
  13555. if (p == "graphql-ws") { return p; }
  13556. }
  13557. return "";
  13558. });
  13559. }
  13560. void start_server() {
  13561. port_ = server_->bind_to_any_port(HOST);
  13562. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13563. server_->wait_until_ready();
  13564. }
  13565. std::unique_ptr<Server> server_;
  13566. std::thread server_thread_;
  13567. int port_ = 0;
  13568. };
  13569. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13570. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13571. "/ws-echo");
  13572. ASSERT_TRUE(client.connect());
  13573. ASSERT_TRUE(client.is_open());
  13574. ASSERT_TRUE(client.send("Hello WebSocket"));
  13575. std::string msg;
  13576. EXPECT_EQ(ws::Text, client.read(msg));
  13577. EXPECT_EQ("Hello WebSocket", msg);
  13578. client.close();
  13579. }
  13580. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13581. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13582. "/ws-echo");
  13583. ASSERT_TRUE(client.connect());
  13584. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13585. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13586. std::string msg;
  13587. EXPECT_EQ(ws::Binary, client.read(msg));
  13588. EXPECT_EQ(binary_data, msg);
  13589. client.close();
  13590. }
  13591. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13593. "/ws-echo");
  13594. ASSERT_TRUE(client.connect());
  13595. for (int i = 0; i < 10; i++) {
  13596. auto text = "message " + std::to_string(i);
  13597. ASSERT_TRUE(client.send(text));
  13598. std::string msg;
  13599. ASSERT_TRUE(client.read(msg));
  13600. EXPECT_EQ(text, msg);
  13601. }
  13602. client.close();
  13603. }
  13604. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13606. "/ws-close");
  13607. ASSERT_TRUE(client.connect());
  13608. // Send a message to trigger the server to close
  13609. ASSERT_TRUE(client.send("trigger close"));
  13610. // The server will close, so read should return false
  13611. std::string msg;
  13612. EXPECT_FALSE(client.read(msg));
  13613. EXPECT_FALSE(client.is_open());
  13614. }
  13615. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13617. "/ws-echo");
  13618. ASSERT_TRUE(client.connect());
  13619. // 128KB message
  13620. std::string large_data(128 * 1024, 'X');
  13621. ASSERT_TRUE(client.send(large_data));
  13622. std::string msg;
  13623. ASSERT_TRUE(client.read(msg));
  13624. EXPECT_EQ(large_data, msg);
  13625. client.close();
  13626. }
  13627. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13628. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13629. "/ws-echo");
  13630. ASSERT_TRUE(client.connect());
  13631. const int num_threads = 4;
  13632. std::vector<std::thread> threads;
  13633. std::atomic<int> send_count{0};
  13634. for (int t = 0; t < num_threads; t++) {
  13635. threads.emplace_back([&client, &send_count, t]() {
  13636. for (int i = 0; i < 5; i++) {
  13637. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13638. if (client.send(text)) { send_count++; }
  13639. }
  13640. });
  13641. }
  13642. for (auto &th : threads) {
  13643. th.join();
  13644. }
  13645. int received = 0;
  13646. std::string msg;
  13647. while (received < send_count.load()) {
  13648. if (!client.read(msg)) { break; }
  13649. received++;
  13650. }
  13651. EXPECT_EQ(send_count.load(), received);
  13652. client.close();
  13653. }
  13654. TEST_F(WebSocketIntegrationTest, ReadString) {
  13655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13656. "/ws-echo-string");
  13657. ASSERT_TRUE(client.connect());
  13658. ASSERT_TRUE(client.send("hello"));
  13659. std::string msg;
  13660. ASSERT_TRUE(client.read(msg));
  13661. EXPECT_EQ("echo: hello", msg);
  13662. ASSERT_TRUE(client.send("world"));
  13663. ASSERT_TRUE(client.read(msg));
  13664. EXPECT_EQ("echo: world", msg);
  13665. client.close();
  13666. }
  13667. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13668. Headers headers = {{"X-Test-Header", "test-value"}};
  13669. ws::WebSocketClient client(
  13670. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13671. ASSERT_TRUE(client.connect());
  13672. std::string msg;
  13673. ASSERT_TRUE(client.read(msg));
  13674. EXPECT_EQ("path:/ws-request-info", msg);
  13675. ASSERT_TRUE(client.read(msg));
  13676. EXPECT_EQ("header:test-value", msg);
  13677. client.close();
  13678. }
  13679. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13680. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13681. "/ws-echo");
  13682. client.set_read_timeout(1, 0); // 1 second
  13683. ASSERT_TRUE(client.connect());
  13684. // Don't send anything — server echo handler waits for a message,
  13685. // so read() should time out and return false.
  13686. std::string msg;
  13687. EXPECT_FALSE(client.read(msg));
  13688. }
  13689. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13690. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13691. "/ws-echo");
  13692. client.set_read_timeout(5, 0);
  13693. ASSERT_TRUE(client.connect());
  13694. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13695. // The server should reject it and close the connection.
  13696. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13697. client.send(oversized);
  13698. // The server's read() should have failed due to payload limit,
  13699. // so our read() should return false (connection closed).
  13700. std::string msg;
  13701. EXPECT_FALSE(client.read(msg));
  13702. }
  13703. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13704. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13705. "/ws-echo");
  13706. client.set_read_timeout(10, 0);
  13707. ASSERT_TRUE(client.connect());
  13708. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13709. // This should succeed.
  13710. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13711. ASSERT_TRUE(client.send(at_limit));
  13712. std::string msg;
  13713. ASSERT_TRUE(client.read(msg));
  13714. EXPECT_EQ(at_limit.size(), msg.size());
  13715. client.close();
  13716. }
  13717. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13718. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13719. "/nonexistent");
  13720. EXPECT_FALSE(client.connect());
  13721. EXPECT_FALSE(client.is_open());
  13722. }
  13723. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13725. "/ws-echo");
  13726. ASSERT_TRUE(client.connect());
  13727. ASSERT_TRUE(client.send(""));
  13728. std::string msg;
  13729. EXPECT_EQ(ws::Text, client.read(msg));
  13730. EXPECT_EQ("", msg);
  13731. client.close();
  13732. }
  13733. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13735. "/ws-echo");
  13736. // First connection
  13737. ASSERT_TRUE(client.connect());
  13738. ASSERT_TRUE(client.send("first"));
  13739. std::string msg;
  13740. ASSERT_TRUE(client.read(msg));
  13741. EXPECT_EQ("first", msg);
  13742. client.close();
  13743. EXPECT_FALSE(client.is_open());
  13744. // Reconnect using the same client object
  13745. ASSERT_TRUE(client.connect());
  13746. ASSERT_TRUE(client.is_open());
  13747. ASSERT_TRUE(client.send("second"));
  13748. ASSERT_TRUE(client.read(msg));
  13749. EXPECT_EQ("second", msg);
  13750. client.close();
  13751. }
  13752. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13753. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13754. "/ws-close-status");
  13755. ASSERT_TRUE(client.connect());
  13756. // Trigger the server to close with GoingAway status
  13757. ASSERT_TRUE(client.send("trigger"));
  13758. // read() should return false after receiving the close frame
  13759. std::string msg;
  13760. EXPECT_FALSE(client.read(msg));
  13761. EXPECT_FALSE(client.is_open());
  13762. }
  13763. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13765. "/ws-echo");
  13766. ASSERT_TRUE(client.connect());
  13767. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13768. EXPECT_FALSE(client.is_open());
  13769. }
  13770. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13771. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13772. ws::WebSocketClient client(
  13773. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13774. ASSERT_TRUE(client.connect());
  13775. // Server should have selected graphql-ws
  13776. EXPECT_EQ("graphql-ws", client.subprotocol());
  13777. client.close();
  13778. }
  13779. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13780. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13781. ws::WebSocketClient client(
  13782. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13783. ASSERT_TRUE(client.connect());
  13784. // Server should not have selected any subprotocol
  13785. EXPECT_TRUE(client.subprotocol().empty());
  13786. client.close();
  13787. }
  13788. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13789. // Connect without requesting any subprotocol
  13790. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13791. "/ws-subprotocol");
  13792. ASSERT_TRUE(client.connect());
  13793. EXPECT_TRUE(client.subprotocol().empty());
  13794. client.close();
  13795. }
  13796. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13797. Server svr;
  13798. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13799. if (!req.has_header("Authorization")) {
  13800. res.status = StatusCode::Unauthorized_401;
  13801. res.set_content("Unauthorized", "text/plain");
  13802. return Server::HandlerResponse::Handled;
  13803. }
  13804. return Server::HandlerResponse::Unhandled;
  13805. });
  13806. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13807. std::string msg;
  13808. while (ws.read(msg)) {
  13809. ws.send(msg);
  13810. }
  13811. });
  13812. auto port = svr.bind_to_any_port("localhost");
  13813. std::thread t([&]() { svr.listen_after_bind(); });
  13814. svr.wait_until_ready();
  13815. // Without Authorization header - should be rejected before upgrade
  13816. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13817. EXPECT_FALSE(client1.connect());
  13818. // With Authorization header - should succeed
  13819. Headers headers = {{"Authorization", "Bearer token123"}};
  13820. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13821. headers);
  13822. ASSERT_TRUE(client2.connect());
  13823. ASSERT_TRUE(client2.send("hello"));
  13824. std::string msg;
  13825. ASSERT_TRUE(client2.read(msg));
  13826. EXPECT_EQ("hello", msg);
  13827. client2.close();
  13828. svr.stop();
  13829. t.join();
  13830. }
  13831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13832. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13833. protected:
  13834. void SetUp() override {
  13835. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13836. SERVER_PRIVATE_KEY_FILE);
  13837. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13838. std::string msg;
  13839. ws::ReadResult ret;
  13840. while ((ret = ws.read(msg))) {
  13841. if (ret == ws::Binary) {
  13842. ws.send(msg.data(), msg.size());
  13843. } else {
  13844. ws.send(msg);
  13845. }
  13846. }
  13847. });
  13848. port_ = server_->bind_to_any_port(HOST);
  13849. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13850. server_->wait_until_ready();
  13851. }
  13852. void TearDown() override {
  13853. server_->stop();
  13854. if (server_thread_.joinable()) { server_thread_.join(); }
  13855. }
  13856. std::unique_ptr<SSLServer> server_;
  13857. std::thread server_thread_;
  13858. int port_ = 0;
  13859. };
  13860. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  13861. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  13862. "/ws-echo");
  13863. client.enable_server_certificate_verification(false);
  13864. ASSERT_TRUE(client.connect());
  13865. ASSERT_TRUE(client.is_open());
  13866. ASSERT_TRUE(client.send("Hello WSS"));
  13867. std::string msg;
  13868. EXPECT_EQ(ws::Text, client.read(msg));
  13869. EXPECT_EQ("Hello WSS", msg);
  13870. client.close();
  13871. }
  13872. #endif