1
0

test.cc 516 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845
  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_TRUE(s0.is_peer_alive());
  269. EXPECT_EQ(0, close(fds[1]));
  270. EXPECT_FALSE(s0.is_peer_alive());
  271. return true;
  272. });
  273. EXPECT_EQ(0, close(fds[0]));
  274. }
  275. TEST(SocketStream, wait_writable_INET) {
  276. sockaddr_in addr;
  277. memset(&addr, 0, sizeof(addr));
  278. addr.sin_family = AF_INET;
  279. addr.sin_port = htons(PORT + 1);
  280. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  281. int disconnected_svr_sock = -1;
  282. std::thread svr{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, listen(s, 1));
  287. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  288. ASSERT_EQ(0, close(s));
  289. }};
  290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  291. std::thread cli{[&] {
  292. const int s = socket(AF_INET, SOCK_STREAM, 0);
  293. ASSERT_LE(0, s);
  294. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  295. ASSERT_EQ(0, close(s));
  296. }};
  297. cli.join();
  298. svr.join();
  299. ASSERT_NE(disconnected_svr_sock, -1);
  300. const auto asSocketStream = [&](socket_t fd,
  301. std::function<bool(Stream &)> func) {
  302. return detail::process_client_socket(
  303. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  304. };
  305. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  306. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  307. // wait_writable() returns true because select_write() only checks if the
  308. // send buffer has space. Peer disconnection is detected later by send().
  309. EXPECT_TRUE(ss.wait_writable());
  310. return true;
  311. });
  312. ASSERT_EQ(0, close(disconnected_svr_sock));
  313. }
  314. #endif // #ifndef _WIN32
  315. TEST(ClientTest, MoveConstructible) {
  316. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  317. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  318. }
  319. TEST(ClientTest, MoveAssignable) {
  320. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  321. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  322. }
  323. #ifdef _WIN32
  324. TEST(StartupTest, WSAStartup) {
  325. WSADATA wsaData;
  326. int ret = WSAStartup(0x0002, &wsaData);
  327. ASSERT_EQ(0, ret);
  328. }
  329. #endif
  330. TEST(DecodePathTest, PercentCharacter) {
  331. EXPECT_EQ(
  332. decode_path_component(
  333. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  334. U8("descrip=Gastos áéíóúñÑ 6"));
  335. }
  336. TEST(DecodePathTest, PercentCharacterNUL) {
  337. string expected;
  338. expected.push_back('x');
  339. expected.push_back('\0');
  340. expected.push_back('x');
  341. EXPECT_EQ(decode_path_component("x%00x"), expected);
  342. }
  343. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  348. string reservedCharacters = ";,/?:@&=+$";
  349. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  350. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  351. }
  352. TEST(ClientQueryOrder, PreserveOrder) {
  353. // This test reproduces Issue #2259: client may reorder query parameters
  354. // when sending a GET request. The expected behavior is that the client
  355. // preserves the original query string order when the caller supplied it
  356. // as part of the path.
  357. Server svr;
  358. svr.Get("/", [&](const Request &req, Response &res) {
  359. // Echo back the raw target so the test can assert ordering
  360. res.set_content(req.target, "text/plain");
  361. });
  362. std::thread t{[&] { svr.listen(HOST, PORT); }};
  363. auto se = detail::scope_exit([&] {
  364. svr.stop();
  365. t.join();
  366. ASSERT_FALSE(svr.is_running());
  367. });
  368. svr.wait_until_ready();
  369. Client cli(HOST, PORT);
  370. ASSERT_TRUE(cli.is_valid());
  371. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  372. auto res = cli.Get(original);
  373. ASSERT_TRUE(res);
  374. // Expect the echoed target to exactly match the original path (order
  375. // preserved)
  376. EXPECT_EQ(res->body, original);
  377. }
  378. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  379. string chineseCharacters = U8("中国語");
  380. string russianCharacters = U8("дом");
  381. string brazilianCharacters = U8("óculos");
  382. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  383. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  384. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  385. "%D0%B4%D0%BE%D0%BC");
  386. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  387. }
  388. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$";
  394. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  395. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  396. }
  397. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  398. string chineseCharacters = U8("中国語");
  399. string russianCharacters = U8("дом");
  400. string brazilianCharacters = U8("óculos");
  401. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  402. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  403. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  404. "%D0%B4%D0%BE%D0%BC");
  405. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  406. }
  407. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  408. // Issue #2082 use case: encoding path component with ampersand
  409. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  410. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  411. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  412. }
  413. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  414. string unescapedCharacters = "-_.!~*'()";
  415. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  416. }
  417. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  418. string reservedCharacters = ";,/?:@&=+$#";
  419. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  420. }
  421. TEST(EncodeUriTest, TestUTF8Characters) {
  422. string chineseCharacters = U8("中国語");
  423. string russianCharacters = U8("дом");
  424. string brazilianCharacters = U8("óculos");
  425. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  426. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  427. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  428. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  429. }
  430. TEST(EncodeUriTest, TestCompleteUri) {
  431. string uri =
  432. "https://example.com/path/to/resource?query=value&param=test#fragment";
  433. EXPECT_EQ(
  434. httplib::encode_uri(uri),
  435. "https://example.com/path/to/resource?query=value&param=test#fragment");
  436. }
  437. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  438. string uri =
  439. "https://example.com/path with spaces/file name.html?q=hello world";
  440. EXPECT_EQ(httplib::encode_uri(uri),
  441. "https://example.com/path%20with%20spaces/"
  442. "file%20name.html?q=hello%20world");
  443. }
  444. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  445. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  446. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  447. }
  448. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  449. string unescapedCharacters = "-_.!~*'()";
  450. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  451. }
  452. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  453. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  454. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  455. string encodedBrazilian = "%C3%B3culos";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  457. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  458. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  459. }
  460. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  461. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  462. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  463. "Piri Tommy Villiers - on & on");
  464. }
  465. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  466. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  467. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  468. }
  469. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  470. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  471. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  472. }
  473. TEST(DecodeUriTest, TestUTF8Characters) {
  474. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  475. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  476. string encodedBrazilian = "%C3%B3culos";
  477. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  478. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  479. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  480. }
  481. TEST(DecodeUriTest, TestCompleteUri) {
  482. string encodedUri = "https://example.com/path%20with%20spaces/"
  483. "file%20name.html?q=hello%20world";
  484. EXPECT_EQ(
  485. httplib::decode_uri(encodedUri),
  486. "https://example.com/path with spaces/file name.html?q=hello world");
  487. }
  488. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  489. string original =
  490. "https://example.com/path with spaces/file name.html?q=hello world";
  491. string encoded = httplib::encode_uri(original);
  492. string decoded = httplib::decode_uri(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  496. string original = "Piri Tommy Villiers - on & on";
  497. string encoded = httplib::encode_uri_component(original);
  498. string decoded = httplib::decode_uri_component(encoded);
  499. EXPECT_EQ(decoded, original);
  500. }
  501. TEST(TrimTests, TrimStringTests) {
  502. EXPECT_EQ("abc", detail::trim_copy("abc"));
  503. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  504. EXPECT_TRUE(detail::trim_copy("").empty());
  505. }
  506. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  507. // Simple case without quality values
  508. std::vector<std::string> result1;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json,text/plain", result1));
  511. EXPECT_EQ(result1.size(), 3U);
  512. EXPECT_EQ(result1[0], "text/html");
  513. EXPECT_EQ(result1[1], "application/json");
  514. EXPECT_EQ(result1[2], "text/plain");
  515. // With quality values
  516. std::vector<std::string> result2;
  517. EXPECT_TRUE(detail::parse_accept_header(
  518. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  519. EXPECT_EQ(result2.size(), 3U);
  520. EXPECT_EQ(result2[0], "application/json"); // highest q value
  521. EXPECT_EQ(result2[1], "text/html");
  522. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  523. }
  524. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  525. // Mixed with and without quality values
  526. std::vector<std::string> result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  529. EXPECT_EQ(result.size(), 3U);
  530. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  531. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  532. EXPECT_EQ(result[2], "application/json"); // q=0.5
  533. }
  534. TEST(ParseAcceptHeaderTest, EdgeCases) {
  535. // Empty header
  536. std::vector<std::string> empty_result;
  537. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  538. EXPECT_TRUE(empty_result.empty());
  539. // Single type
  540. std::vector<std::string> single_result;
  541. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  542. EXPECT_EQ(single_result.size(), 1U);
  543. EXPECT_EQ(single_result[0], "application/json");
  544. // Wildcard types
  545. std::vector<std::string> wildcard_result;
  546. EXPECT_TRUE(detail::parse_accept_header(
  547. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  548. EXPECT_EQ(wildcard_result.size(), 3U);
  549. EXPECT_EQ(wildcard_result[0], "application/json");
  550. EXPECT_EQ(wildcard_result[1], "text/*");
  551. EXPECT_EQ(wildcard_result[2], "*/*");
  552. }
  553. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  554. // Common browser Accept header
  555. std::vector<std::string> browser_result;
  556. EXPECT_TRUE(
  557. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  558. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  559. browser_result));
  560. EXPECT_EQ(browser_result.size(), 6U);
  561. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  562. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  563. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  564. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  565. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  566. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  567. // API client header
  568. std::vector<std::string> api_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  571. api_result));
  572. EXPECT_EQ(api_result.size(), 3U);
  573. EXPECT_EQ(api_result[0], "application/json");
  574. EXPECT_EQ(api_result[1], "application/xml");
  575. EXPECT_EQ(api_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, SpecialCases) {
  578. // Quality value with 3 decimal places
  579. std::vector<std::string> decimal_result;
  580. EXPECT_TRUE(detail::parse_accept_header(
  581. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  582. EXPECT_EQ(decimal_result.size(), 2U);
  583. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  584. EXPECT_EQ(decimal_result[1], "text/html");
  585. // Zero quality (should still be included but with lowest priority)
  586. std::vector<std::string> zero_q_result;
  587. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  588. zero_q_result));
  589. EXPECT_EQ(zero_q_result.size(), 2U);
  590. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  591. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  592. // No spaces around commas
  593. std::vector<std::string> no_space_result;
  594. EXPECT_TRUE(detail::parse_accept_header(
  595. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  596. no_space_result));
  597. EXPECT_EQ(no_space_result.size(), 3U);
  598. EXPECT_EQ(no_space_result[0], "text/html");
  599. EXPECT_EQ(no_space_result[1], "application/json");
  600. EXPECT_EQ(no_space_result[2], "text/plain");
  601. }
  602. TEST(ParseAcceptHeaderTest, InvalidCases) {
  603. std::vector<std::string> result;
  604. // Invalid quality value (> 1.0)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  607. // Invalid quality value (< 0.0)
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  610. // Invalid quality value (not a number)
  611. EXPECT_FALSE(detail::parse_accept_header(
  612. "text/html;q=invalid,application/json", result));
  613. // Empty quality value
  614. EXPECT_FALSE(
  615. detail::parse_accept_header("text/html;q=,application/json", result));
  616. // Invalid media type format (no slash and not wildcard)
  617. EXPECT_FALSE(
  618. detail::parse_accept_header("invalidtype,application/json", result));
  619. // Empty media type
  620. result.clear();
  621. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  622. // Only commas
  623. result.clear();
  624. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  625. // Valid cases should still work
  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("*", result));
  630. EXPECT_EQ(result.size(), 1U);
  631. EXPECT_EQ(result[0], "*");
  632. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  633. EXPECT_EQ(result.size(), 1U);
  634. EXPECT_EQ(result[0], "text/*");
  635. }
  636. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  637. Server svr;
  638. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  639. EXPECT_EQ(req.accept_content_types.size(), 3U);
  640. EXPECT_EQ(req.accept_content_types[0], "application/json");
  641. EXPECT_EQ(req.accept_content_types[1], "text/html");
  642. EXPECT_EQ(req.accept_content_types[2], "*/*");
  643. res.set_content("ok", "text/plain");
  644. });
  645. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  646. EXPECT_TRUE(false);
  647. res.set_content("bad request", "text/plain");
  648. });
  649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  650. auto se = detail::scope_exit([&] {
  651. svr.stop();
  652. listen_thread.join();
  653. ASSERT_FALSE(svr.is_running());
  654. });
  655. svr.wait_until_ready();
  656. Client cli("localhost", PORT);
  657. {
  658. auto res =
  659. cli.Get("/accept_ok",
  660. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::OK_200, res->status);
  663. }
  664. {
  665. auto res = cli.Get("/accept_bad_request",
  666. {{"Accept", "text/html;q=abc,application/json"}});
  667. ASSERT_TRUE(res);
  668. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  669. }
  670. }
  671. TEST(DivideTest, DivideStringTests) {
  672. auto divide = [](const std::string &str, char d) {
  673. std::string lhs;
  674. std::string rhs;
  675. detail::divide(str, d,
  676. [&](const char *lhs_data, std::size_t lhs_size,
  677. const char *rhs_data, std::size_t rhs_size) {
  678. lhs.assign(lhs_data, lhs_size);
  679. rhs.assign(rhs_data, rhs_size);
  680. });
  681. return std::make_pair(std::move(lhs), std::move(rhs));
  682. };
  683. {
  684. const auto res = divide("", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "");
  687. }
  688. {
  689. const auto res = divide("=", '=');
  690. EXPECT_EQ(res.first, "");
  691. EXPECT_EQ(res.second, "");
  692. }
  693. {
  694. const auto res = divide(" ", '=');
  695. EXPECT_EQ(res.first, " ");
  696. EXPECT_EQ(res.second, "");
  697. }
  698. {
  699. const auto res = divide("a", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "");
  702. }
  703. {
  704. const auto res = divide("a=", '=');
  705. EXPECT_EQ(res.first, "a");
  706. EXPECT_EQ(res.second, "");
  707. }
  708. {
  709. const auto res = divide("=b", '=');
  710. EXPECT_EQ(res.first, "");
  711. EXPECT_EQ(res.second, "b");
  712. }
  713. {
  714. const auto res = divide("a=b", '=');
  715. EXPECT_EQ(res.first, "a");
  716. EXPECT_EQ(res.second, "b");
  717. }
  718. {
  719. const auto res = divide("a=b=", '=');
  720. EXPECT_EQ(res.first, "a");
  721. EXPECT_EQ(res.second, "b=");
  722. }
  723. {
  724. const auto res = divide("a=b=c", '=');
  725. EXPECT_EQ(res.first, "a");
  726. EXPECT_EQ(res.second, "b=c");
  727. }
  728. }
  729. TEST(SplitTest, ParseQueryString) {
  730. string s = "key1=val1&key2=val2&key3=val3";
  731. Params dic;
  732. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  733. [&](const char *b, const char *e) {
  734. string key, val;
  735. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  736. if (key.empty()) {
  737. key.assign(b2, e2);
  738. } else {
  739. val.assign(b2, e2);
  740. }
  741. });
  742. dic.emplace(key, val);
  743. });
  744. EXPECT_EQ("val1", dic.find("key1")->second);
  745. EXPECT_EQ("val2", dic.find("key2")->second);
  746. EXPECT_EQ("val3", dic.find("key3")->second);
  747. }
  748. TEST(SplitTest, ParseInvalidQueryTests) {
  749. {
  750. string s = " ";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. {
  756. string s = " = =";
  757. Params dict;
  758. detail::parse_query_text(s, dict);
  759. EXPECT_TRUE(dict.empty());
  760. }
  761. }
  762. TEST(ParseQueryTest, ParseQueryString) {
  763. {
  764. std::string s = "key1=val1&key2=val2&key3=val3";
  765. Params dic;
  766. detail::parse_query_text(s, dic);
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. {
  772. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  773. Params dic;
  774. detail::parse_query_text(s, dic);
  775. EXPECT_EQ("", dic.find("key1")->second);
  776. EXPECT_EQ("val1", dic.find("key2")->second);
  777. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  778. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  779. }
  780. }
  781. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  782. Params dic;
  783. EXPECT_EQ(detail::params_to_query_str(dic), "");
  784. dic.emplace("key1", "val1");
  785. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  786. dic.emplace("key2", "val2");
  787. dic.emplace("key3", "val3");
  788. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  789. }
  790. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  791. string content_type = "multipart/form-data; boundary=something";
  792. string boundary;
  793. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  794. EXPECT_TRUE(ret);
  795. EXPECT_EQ(boundary, "something");
  796. }
  797. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  798. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  799. string boundary;
  800. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  803. }
  804. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  805. string content_type =
  806. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  807. string boundary;
  808. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  811. }
  812. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  813. string content_type =
  814. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  819. }
  820. TEST(GetHeaderValueTest, DefaultValue) {
  821. Headers headers = {{"Dummy", "Dummy"}};
  822. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  823. EXPECT_STREQ("text/plain", val);
  824. }
  825. TEST(GetHeaderValueTest, DefaultValueInt) {
  826. Headers headers = {{"Dummy", "Dummy"}};
  827. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  828. EXPECT_EQ(100ull, val);
  829. }
  830. TEST(GetHeaderValueTest, RegularValue) {
  831. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  833. EXPECT_STREQ("text/html", val);
  834. }
  835. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  836. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  837. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  838. EXPECT_STREQ("text/html", val);
  839. }
  840. TEST(GetHeaderValueTest, SetContent) {
  841. Response res;
  842. res.set_content("html", "text/html");
  843. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  844. res.set_content("text", "text/plain");
  845. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  846. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  847. }
  848. TEST(GetHeaderValueTest, RegularValueInt) {
  849. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  854. Headers headers = {{"Content-Length", "x"}};
  855. auto is_invalid_value = false;
  856. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  857. is_invalid_value);
  858. EXPECT_EQ(0ull, val);
  859. EXPECT_TRUE(is_invalid_value);
  860. }
  861. TEST(GetHeaderValueTest, Range) {
  862. {
  863. Headers headers = {make_range_header({{1, -1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=1-", val);
  866. }
  867. {
  868. Headers headers = {make_range_header({{-1, 1}})};
  869. auto val = detail::get_header_value(headers, "Range", 0, 0);
  870. EXPECT_STREQ("bytes=-1", val);
  871. }
  872. {
  873. Headers headers = {make_range_header({{1, 10}})};
  874. auto val = detail::get_header_value(headers, "Range", 0, 0);
  875. EXPECT_STREQ("bytes=1-10", val);
  876. }
  877. {
  878. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  879. auto val = detail::get_header_value(headers, "Range", 0, 0);
  880. EXPECT_STREQ("bytes=1-10, 100-", val);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  884. auto val = detail::get_header_value(headers, "Range", 0, 0);
  885. EXPECT_STREQ("bytes=1-10, 100-200", val);
  886. }
  887. {
  888. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  889. auto val = detail::get_header_value(headers, "Range", 0, 0);
  890. EXPECT_STREQ("bytes=0-0, -1", val);
  891. }
  892. }
  893. TEST(ParseHeaderValueTest, Range) {
  894. {
  895. Ranges ranges;
  896. auto ret = detail::parse_range_header("bytes=1-", ranges);
  897. EXPECT_TRUE(ret);
  898. EXPECT_EQ(1u, ranges.size());
  899. EXPECT_EQ(1u, ranges[0].first);
  900. EXPECT_EQ(-1, ranges[0].second);
  901. }
  902. {
  903. Ranges ranges;
  904. auto ret = detail::parse_range_header("bytes=-1", ranges);
  905. EXPECT_TRUE(ret);
  906. EXPECT_EQ(1u, ranges.size());
  907. EXPECT_EQ(-1, ranges[0].first);
  908. EXPECT_EQ(1u, ranges[0].second);
  909. }
  910. {
  911. Ranges ranges;
  912. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  913. EXPECT_TRUE(ret);
  914. EXPECT_EQ(1u, ranges.size());
  915. EXPECT_EQ(1u, ranges[0].first);
  916. EXPECT_EQ(10u, ranges[0].second);
  917. }
  918. {
  919. Ranges ranges;
  920. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  921. EXPECT_FALSE(ret);
  922. }
  923. {
  924. Ranges ranges;
  925. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  926. EXPECT_TRUE(ret);
  927. EXPECT_EQ(2u, ranges.size());
  928. EXPECT_EQ(1u, ranges[0].first);
  929. EXPECT_EQ(10u, ranges[0].second);
  930. EXPECT_EQ(100u, ranges[1].first);
  931. EXPECT_EQ(-1, ranges[1].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret =
  936. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  937. EXPECT_TRUE(ret);
  938. EXPECT_EQ(3u, ranges.size());
  939. EXPECT_EQ(1u, ranges[0].first);
  940. EXPECT_EQ(10u, ranges[0].second);
  941. EXPECT_EQ(100u, ranges[1].first);
  942. EXPECT_EQ(200u, ranges[1].second);
  943. EXPECT_EQ(300u, ranges[2].first);
  944. EXPECT_EQ(400u, ranges[2].second);
  945. }
  946. {
  947. Ranges 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=0", 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=,", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  955. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  956. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  957. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  958. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  959. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  960. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  961. EXPECT_TRUE(ranges.empty());
  962. }
  963. }
  964. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  972. #else
  973. EXPECT_TRUE(ret == detail::EncodingType::None);
  974. #endif
  975. }
  976. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  977. Request req;
  978. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  979. Response res;
  980. res.set_header("Content-Type", "text/plain");
  981. auto ret = detail::encoding_type(req, res);
  982. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  983. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  984. #elif CPPHTTPLIB_ZLIB_SUPPORT
  985. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  986. #elif CPPHTTPLIB_ZSTD_SUPPORT
  987. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  988. #else
  989. EXPECT_TRUE(ret == detail::EncodingType::None);
  990. #endif
  991. }
  992. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  993. Request req;
  994. req.set_header("Accept-Encoding",
  995. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  996. Response res;
  997. res.set_header("Content-Type", "text/plain");
  998. auto ret = detail::encoding_type(req, res);
  999. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1000. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1001. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1002. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1003. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1004. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1005. #else
  1006. EXPECT_TRUE(ret == detail::EncodingType::None);
  1007. #endif
  1008. }
  1009. TEST(BufferStreamTest, read) {
  1010. detail::BufferStream strm1;
  1011. Stream &strm = strm1;
  1012. EXPECT_EQ(5, strm.write("hello"));
  1013. char buf[512];
  1014. EXPECT_EQ(2, strm.read(buf, 2));
  1015. EXPECT_EQ('h', buf[0]);
  1016. EXPECT_EQ('e', buf[1]);
  1017. EXPECT_EQ(2, strm.read(buf, 2));
  1018. EXPECT_EQ('l', buf[0]);
  1019. EXPECT_EQ('l', buf[1]);
  1020. EXPECT_EQ(1, strm.read(buf, 1));
  1021. EXPECT_EQ('o', buf[0]);
  1022. EXPECT_EQ(0, strm.read(buf, 1));
  1023. }
  1024. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1025. auto host = "www.httpwatch.com";
  1026. auto ip = hosted_at(host);
  1027. EXPECT_EQ("23.96.13.243", ip);
  1028. std::vector<std::string> addrs;
  1029. hosted_at(host, addrs);
  1030. EXPECT_EQ(1u, addrs.size());
  1031. }
  1032. #if 0 // It depends on each test environment...
  1033. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1034. auto host = "www.youtube.com";
  1035. std::vector<std::string> addrs;
  1036. hosted_at(host, addrs);
  1037. EXPECT_EQ(20u, addrs.size());
  1038. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1039. EXPECT_TRUE(it != addrs.end());
  1040. }
  1041. #endif
  1042. class ChunkedEncodingTest : public ::testing::Test {
  1043. protected:
  1044. ChunkedEncodingTest()
  1045. : cli_(HOST, PORT)
  1046. #ifdef CPPHTTPLIB_SSL_ENABLED
  1047. ,
  1048. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1049. #endif
  1050. {
  1051. cli_.set_connection_timeout(2);
  1052. #ifdef CPPHTTPLIB_SSL_ENABLED
  1053. cli_.enable_server_certificate_verification(false);
  1054. #endif
  1055. }
  1056. virtual void SetUp() {
  1057. read_file("./image.jpg", image_data_);
  1058. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1059. res.set_content("Hello World!", "text/plain");
  1060. });
  1061. svr_.Get(
  1062. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1063. res.set_chunked_content_provider(
  1064. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1065. size_t remaining = image_data_.size() - offset;
  1066. if (remaining == 0) {
  1067. sink.done();
  1068. } else {
  1069. constexpr size_t CHUNK_SIZE = 1024;
  1070. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1071. sink.write(&image_data_[offset], send_size);
  1072. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1073. }
  1074. return true;
  1075. });
  1076. });
  1077. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1078. svr_.wait_until_ready();
  1079. }
  1080. virtual void TearDown() {
  1081. svr_.stop();
  1082. if (!request_threads_.empty()) {
  1083. std::this_thread::sleep_for(std::chrono::seconds(1));
  1084. for (auto &t : request_threads_) {
  1085. t.join();
  1086. }
  1087. }
  1088. t_.join();
  1089. }
  1090. #ifdef CPPHTTPLIB_SSL_ENABLED
  1091. SSLClient cli_;
  1092. SSLServer svr_;
  1093. #else
  1094. Client cli_;
  1095. Server svr_;
  1096. #endif
  1097. thread t_;
  1098. std::vector<thread> request_threads_;
  1099. std::string image_data_;
  1100. };
  1101. TEST_F(ChunkedEncodingTest, NormalGet) {
  1102. auto res = cli_.Get("/chunked");
  1103. ASSERT_TRUE(res);
  1104. std::string out;
  1105. read_file("./image.jpg", out);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. EXPECT_EQ(out, res->body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1122. std::string body;
  1123. auto res = cli_.Get(
  1124. "/chunked",
  1125. [&](const Response &response) {
  1126. EXPECT_EQ(StatusCode::OK_200, response.status);
  1127. return true;
  1128. },
  1129. [&](const char *data, size_t data_length) {
  1130. body.append(data, data_length);
  1131. return true;
  1132. });
  1133. ASSERT_TRUE(res);
  1134. std::string out;
  1135. read_file("./image.jpg", out);
  1136. EXPECT_EQ(StatusCode::OK_200, res->status);
  1137. EXPECT_EQ(out, body);
  1138. }
  1139. TEST(RangeTest, FromHTTPBin_Online) {
  1140. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1141. auto host = "httpcan.org";
  1142. auto path = std::string{"/range/32"};
  1143. #else
  1144. auto host = "nghttp2.org";
  1145. auto path = std::string{"/httpbin/range/32"};
  1146. #endif
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. auto port = 443;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 80;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(5);
  1155. {
  1156. auto res = cli.Get(path);
  1157. ASSERT_TRUE(res);
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1159. EXPECT_EQ(StatusCode::OK_200, res->status);
  1160. }
  1161. {
  1162. Headers headers = {make_range_header({{1, -1}})};
  1163. auto res = cli.Get(path, headers);
  1164. ASSERT_TRUE(res);
  1165. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1167. }
  1168. {
  1169. Headers headers = {make_range_header({{1, 10}})};
  1170. auto res = cli.Get(path, headers);
  1171. ASSERT_TRUE(res);
  1172. EXPECT_EQ("bcdefghijk", res->body);
  1173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1174. }
  1175. {
  1176. Headers headers = {make_range_header({{0, 31}})};
  1177. auto res = cli.Get(path, headers);
  1178. ASSERT_TRUE(res);
  1179. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1180. EXPECT_EQ(StatusCode::OK_200, res->status);
  1181. }
  1182. {
  1183. Headers headers = {make_range_header({{0, -1}})};
  1184. auto res = cli.Get(path, headers);
  1185. ASSERT_TRUE(res);
  1186. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1187. EXPECT_EQ(StatusCode::OK_200, res->status);
  1188. }
  1189. {
  1190. Headers headers = {make_range_header({{0, 32}})};
  1191. auto res = cli.Get(path, headers);
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1194. }
  1195. }
  1196. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1197. auto host = "unresolvableaddress.local";
  1198. auto path = std::string{"/"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(1);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_FALSE(res);
  1210. }
  1211. std::this_thread::sleep_for(std::chrono::seconds(8));
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHost) {
  1214. auto host = "-abcde.com";
  1215. #ifdef CPPHTTPLIB_SSL_ENABLED
  1216. auto port = 443;
  1217. SSLClient cli(host, port);
  1218. #else
  1219. auto port = 80;
  1220. Client cli(host, port);
  1221. #endif
  1222. cli.set_connection_timeout(std::chrono::seconds(2));
  1223. auto res = cli.Get("/");
  1224. ASSERT_TRUE(!res);
  1225. EXPECT_EQ(Error::Connection, res.error());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidHost2) {
  1228. auto host = "httpcan.org/";
  1229. #ifdef CPPHTTPLIB_SSL_ENABLED
  1230. SSLClient cli(host);
  1231. #else
  1232. Client cli(host);
  1233. #endif
  1234. cli.set_connection_timeout(std::chrono::seconds(2));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(!res);
  1237. EXPECT_EQ(Error::Connection, res.error());
  1238. }
  1239. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1240. auto host = "httpcan.org/";
  1241. #ifdef CPPHTTPLIB_SSL_ENABLED
  1242. SSLClient cli(host);
  1243. #else
  1244. Client cli(host);
  1245. #endif
  1246. cli.set_connection_timeout(std::chrono::seconds(2));
  1247. auto res = cli.Get("/");
  1248. ASSERT_TRUE(!res);
  1249. stringstream s;
  1250. s << "error code: " << res.error();
  1251. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1252. }
  1253. TEST(ConnectionErrorTest, InvalidPort) {
  1254. auto host = "localhost";
  1255. auto port = 44380;
  1256. #ifdef CPPHTTPLIB_SSL_ENABLED
  1257. SSLClient cli(host, port);
  1258. #else
  1259. Client cli(host, port);
  1260. #endif
  1261. cli.set_connection_timeout(std::chrono::seconds(2));
  1262. auto res = cli.Get("/");
  1263. ASSERT_TRUE(!res);
  1264. EXPECT_TRUE(Error::Connection == res.error() ||
  1265. Error::ConnectionTimeout == res.error());
  1266. }
  1267. TEST(ConnectionErrorTest, Timeout_Online) {
  1268. auto host = "google.com";
  1269. #ifdef CPPHTTPLIB_SSL_ENABLED
  1270. auto port = 44380;
  1271. SSLClient cli(host, port);
  1272. #else
  1273. auto port = 8080;
  1274. Client cli(host, port);
  1275. #endif
  1276. cli.set_connection_timeout(std::chrono::seconds(2));
  1277. // only probe one address type so that the error reason
  1278. // correlates to the timed-out IPv4, not the unsupported
  1279. // IPv6 connection attempt
  1280. cli.set_address_family(AF_INET);
  1281. auto res = cli.Get("/");
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1284. }
  1285. TEST(CancelTest, NoCancel_Online) {
  1286. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1287. auto host = "httpcan.org";
  1288. auto path = std::string{"/range/32"};
  1289. #else
  1290. auto host = "nghttp2.org";
  1291. auto path = std::string{"/httpbin/range/32"};
  1292. #endif
  1293. #ifdef CPPHTTPLIB_SSL_ENABLED
  1294. auto port = 443;
  1295. SSLClient cli(host, port);
  1296. #else
  1297. auto port = 80;
  1298. Client cli(host, port);
  1299. #endif
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1302. ASSERT_TRUE(res);
  1303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1304. EXPECT_EQ(StatusCode::OK_200, res->status);
  1305. }
  1306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1307. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1308. auto host = "httpcan.org";
  1309. auto path = std::string{"/range/32"};
  1310. #else
  1311. auto host = "nghttp2.org";
  1312. auto path = std::string{"/httpbin/range/32"};
  1313. #endif
  1314. #ifdef CPPHTTPLIB_SSL_ENABLED
  1315. auto port = 443;
  1316. SSLClient cli(host, port);
  1317. #else
  1318. auto port = 80;
  1319. Client cli(host, port);
  1320. #endif
  1321. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1322. cli.set_connection_timeout(std::chrono::seconds(5));
  1323. ASSERT_TRUE(!res);
  1324. EXPECT_EQ(Error::Canceled, res.error());
  1325. }
  1326. TEST(CancelTest, WithCancelLargePayload_Online) {
  1327. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1328. auto host = "httpcan.org";
  1329. auto path = std::string{"/range/65536"};
  1330. #else
  1331. auto host = "nghttp2.org";
  1332. auto path = std::string{"/httpbin/range/65536"};
  1333. #endif
  1334. #ifdef CPPHTTPLIB_SSL_ENABLED
  1335. auto port = 443;
  1336. SSLClient cli(host, port);
  1337. #else
  1338. auto port = 80;
  1339. Client cli(host, port);
  1340. #endif
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. uint32_t count = 0;
  1343. auto res =
  1344. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPost) {
  1349. Server svr;
  1350. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1370. Server svr;
  1371. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPost) {
  1390. Server svr;
  1391. svr.set_payload_max_length(200 * 1024 * 1024);
  1392. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1393. res.set_content(LARGE_DATA, "text/plain");
  1394. });
  1395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. thread.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, PORT);
  1403. cli.set_payload_max_length(200 * 1024 * 1024);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return false; });
  1408. ASSERT_TRUE(!res);
  1409. EXPECT_EQ(Error::Canceled, res.error());
  1410. }
  1411. TEST(CancelTest, NoCancelPut) {
  1412. Server svr;
  1413. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1414. res.set_content("Hello World!", "text/plain");
  1415. });
  1416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1417. auto se = detail::scope_exit([&] {
  1418. svr.stop();
  1419. thread.join();
  1420. ASSERT_FALSE(svr.is_running());
  1421. });
  1422. svr.wait_until_ready();
  1423. Client cli(HOST, PORT);
  1424. cli.set_connection_timeout(std::chrono::seconds(5));
  1425. auto res =
  1426. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1427. "application/json", [](uint64_t, uint64_t) { return true; });
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ("Hello World!", res->body);
  1430. EXPECT_EQ(StatusCode::OK_200, res->status);
  1431. }
  1432. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content("Hello World!", "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, WithCancelLargePayloadPut) {
  1453. Server svr;
  1454. svr.set_payload_max_length(200 * 1024 * 1024);
  1455. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1456. res.set_content(LARGE_DATA, "text/plain");
  1457. });
  1458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. thread.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. Client cli(HOST, PORT);
  1466. cli.set_payload_max_length(200 * 1024 * 1024);
  1467. cli.set_connection_timeout(std::chrono::seconds(5));
  1468. auto res =
  1469. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1470. "application/json", [](uint64_t, uint64_t) { return false; });
  1471. ASSERT_TRUE(!res);
  1472. EXPECT_EQ(Error::Canceled, res.error());
  1473. }
  1474. TEST(CancelTest, NoCancelPatch) {
  1475. Server svr;
  1476. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1477. res.set_content("Hello World!", "text/plain");
  1478. });
  1479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. thread.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. Client cli(HOST, PORT);
  1487. cli.set_connection_timeout(std::chrono::seconds(5));
  1488. auto res =
  1489. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1490. "application/json", [](uint64_t, uint64_t) { return true; });
  1491. ASSERT_TRUE(res);
  1492. EXPECT_EQ("Hello World!", res->body);
  1493. EXPECT_EQ(StatusCode::OK_200, res->status);
  1494. }
  1495. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1496. Server svr;
  1497. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1498. res.set_content("Hello World!", "text/plain");
  1499. });
  1500. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1501. auto se = detail::scope_exit([&] {
  1502. svr.stop();
  1503. thread.join();
  1504. ASSERT_FALSE(svr.is_running());
  1505. });
  1506. svr.wait_until_ready();
  1507. Client cli(HOST, PORT);
  1508. cli.set_connection_timeout(std::chrono::seconds(5));
  1509. auto res =
  1510. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1511. "application/json", [](uint64_t, uint64_t) { return false; });
  1512. ASSERT_TRUE(!res);
  1513. EXPECT_EQ(Error::Canceled, res.error());
  1514. }
  1515. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1516. Server svr;
  1517. svr.set_payload_max_length(200 * 1024 * 1024);
  1518. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1519. res.set_content(LARGE_DATA, "text/plain");
  1520. });
  1521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. thread.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. Client cli(HOST, PORT);
  1529. cli.set_payload_max_length(200 * 1024 * 1024);
  1530. cli.set_connection_timeout(std::chrono::seconds(5));
  1531. auto res =
  1532. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1533. "application/json", [](uint64_t, uint64_t) { return false; });
  1534. ASSERT_TRUE(!res);
  1535. EXPECT_EQ(Error::Canceled, res.error());
  1536. }
  1537. TEST(CancelTest, NoCancelDelete) {
  1538. Server svr;
  1539. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1540. res.set_content("Hello World!", "text/plain");
  1541. });
  1542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1543. auto se = detail::scope_exit([&] {
  1544. svr.stop();
  1545. thread.join();
  1546. ASSERT_FALSE(svr.is_running());
  1547. });
  1548. svr.wait_until_ready();
  1549. Client cli(HOST, PORT);
  1550. cli.set_connection_timeout(std::chrono::seconds(5));
  1551. auto res =
  1552. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1553. "application/json", [](uint64_t, uint64_t) { return true; });
  1554. ASSERT_TRUE(res);
  1555. EXPECT_EQ("Hello World!", res->body);
  1556. EXPECT_EQ(StatusCode::OK_200, res->status);
  1557. }
  1558. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1559. Server svr;
  1560. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1561. res.set_content("Hello World!", "text/plain");
  1562. });
  1563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1564. auto se = detail::scope_exit([&] {
  1565. svr.stop();
  1566. thread.join();
  1567. ASSERT_FALSE(svr.is_running());
  1568. });
  1569. svr.wait_until_ready();
  1570. Client cli(HOST, PORT);
  1571. cli.set_connection_timeout(std::chrono::seconds(5));
  1572. auto res =
  1573. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1574. "application/json", [](uint64_t, uint64_t) { return false; });
  1575. ASSERT_TRUE(!res);
  1576. EXPECT_EQ(Error::Canceled, res.error());
  1577. }
  1578. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1579. Server svr;
  1580. svr.set_payload_max_length(200 * 1024 * 1024);
  1581. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1582. res.set_content(LARGE_DATA, "text/plain");
  1583. });
  1584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1585. auto se = detail::scope_exit([&] {
  1586. svr.stop();
  1587. thread.join();
  1588. ASSERT_FALSE(svr.is_running());
  1589. });
  1590. svr.wait_until_ready();
  1591. Client cli(HOST, PORT);
  1592. cli.set_payload_max_length(200 * 1024 * 1024);
  1593. cli.set_connection_timeout(std::chrono::seconds(5));
  1594. auto res =
  1595. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1596. "application/json", [](uint64_t, uint64_t) { return false; });
  1597. ASSERT_TRUE(!res);
  1598. EXPECT_EQ(Error::Canceled, res.error());
  1599. }
  1600. static std::string remove_whitespace(const std::string &input) {
  1601. std::string output;
  1602. output.reserve(input.size());
  1603. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1604. [](unsigned char c) { return !std::isspace(c); });
  1605. return output;
  1606. }
  1607. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1608. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1609. auto host = "httpcan.org";
  1610. auto path = std::string{"/basic-auth/hello/world"};
  1611. #else
  1612. auto host = "nghttp2.org";
  1613. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1614. #endif
  1615. #ifdef CPPHTTPLIB_SSL_ENABLED
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. #else
  1619. auto port = 80;
  1620. Client cli(host, port);
  1621. #endif
  1622. {
  1623. auto res = cli.Get(path);
  1624. ASSERT_TRUE(res);
  1625. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1626. }
  1627. {
  1628. auto res =
  1629. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1630. ASSERT_TRUE(res);
  1631. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1632. remove_whitespace(res->body));
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. }
  1635. {
  1636. cli.set_basic_auth("hello", "world");
  1637. auto res = cli.Get(path);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1640. remove_whitespace(res->body));
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. {
  1644. cli.set_basic_auth("hello", "bad");
  1645. auto res = cli.Get(path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_basic_auth("bad", "world");
  1651. auto res = cli.Get(path);
  1652. ASSERT_TRUE(res);
  1653. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1654. }
  1655. }
  1656. #ifdef CPPHTTPLIB_SSL_ENABLED
  1657. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1658. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1659. auto host = "httpcan.org";
  1660. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1661. auto paths = std::vector<std::string>{
  1662. "/digest-auth/auth/hello/world/MD5",
  1663. "/digest-auth/auth/hello/world/SHA-256",
  1664. "/digest-auth/auth/hello/world/SHA-512",
  1665. };
  1666. #else
  1667. auto host = "nghttp2.org";
  1668. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1669. auto paths = std::vector<std::string>{
  1670. "/httpbin/digest-auth/auth/hello/world/MD5",
  1671. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1672. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1673. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1674. };
  1675. #endif
  1676. auto port = 443;
  1677. SSLClient cli(host, port);
  1678. {
  1679. auto res = cli.Get(unauth_path);
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1682. }
  1683. {
  1684. cli.set_digest_auth("hello", "world");
  1685. for (const auto &path : paths) {
  1686. auto res = cli.Get(path.c_str());
  1687. ASSERT_TRUE(res);
  1688. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1689. std::string algo(path.substr(path.rfind('/') + 1));
  1690. EXPECT_EQ(
  1691. remove_whitespace("{\"algorithm\":\"" + algo +
  1692. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1693. remove_whitespace(res->body));
  1694. #else
  1695. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1696. remove_whitespace(res->body));
  1697. #endif
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1701. cli.set_digest_auth("hello", "bad");
  1702. for (const auto &path : paths) {
  1703. auto res = cli.Get(path.c_str());
  1704. ASSERT_TRUE(res);
  1705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1706. }
  1707. #endif
  1708. }
  1709. }
  1710. #endif
  1711. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1712. auto host = "google.com";
  1713. auto another_host = "example.com";
  1714. auto wrong_ip = "0.0.0.0";
  1715. #ifdef CPPHTTPLIB_SSL_ENABLED
  1716. SSLClient cli(host);
  1717. #else
  1718. Client cli(host);
  1719. #endif
  1720. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1721. auto res = cli.Get("/");
  1722. ASSERT_TRUE(res);
  1723. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1724. }
  1725. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1726. auto host = "google.com";
  1727. auto wrong_ip = "0.0.0.0";
  1728. #ifdef CPPHTTPLIB_SSL_ENABLED
  1729. SSLClient cli(host);
  1730. #else
  1731. Client cli(host);
  1732. #endif
  1733. cli.set_hostname_addr_map({{host, wrong_ip}});
  1734. auto res = cli.Get("/");
  1735. ASSERT_TRUE(!res);
  1736. EXPECT_EQ(Error::Connection, res.error());
  1737. }
  1738. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1739. auto host = "nghttp2.org";
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. SSLClient cli(host);
  1742. #else
  1743. Client cli(host);
  1744. #endif
  1745. cli.set_follow_location(true);
  1746. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1747. ASSERT_TRUE(res);
  1748. EXPECT_EQ(StatusCode::OK_200, res->status);
  1749. }
  1750. TEST(RedirectTest, Redirect_Online) {
  1751. auto host = "nghttp2.org";
  1752. #ifdef CPPHTTPLIB_SSL_ENABLED
  1753. SSLClient cli(host);
  1754. #else
  1755. Client cli(host);
  1756. #endif
  1757. cli.set_follow_location(true);
  1758. auto res = cli.Get("/httpbin/redirect/3");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. }
  1762. TEST(RelativeRedirectTest, Redirect_Online) {
  1763. auto host = "nghttp2.org";
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/httpbin/relative-redirect/3");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(TooManyRedirectTest, Redirect_Online) {
  1775. auto host = "nghttp2.org";
  1776. #ifdef CPPHTTPLIB_SSL_ENABLED
  1777. SSLClient cli(host);
  1778. #else
  1779. Client cli(host);
  1780. #endif
  1781. cli.set_follow_location(true);
  1782. auto res = cli.Get("/httpbin/redirect/21");
  1783. ASSERT_TRUE(!res);
  1784. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1785. }
  1786. #ifdef CPPHTTPLIB_SSL_ENABLED
  1787. TEST(YahooRedirectTest, Redirect_Online) {
  1788. Client cli("yahoo.com");
  1789. auto res = cli.Get("/");
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1792. cli.set_follow_location(true);
  1793. res = cli.Get("/");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(StatusCode::OK_200, res->status);
  1796. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1797. }
  1798. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1799. #define REDIR_HOST "httpbingo.org"
  1800. #define REDIR_PATH "/redirect-to"
  1801. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1802. SSLClient cli(REDIR_HOST);
  1803. cli.set_follow_location(true);
  1804. auto res =
  1805. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. }
  1809. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1810. SSLClient cli(REDIR_HOST);
  1811. cli.set_follow_location(true);
  1812. Params params;
  1813. params.emplace("url", "http://example.com");
  1814. params.emplace("status_code", "302");
  1815. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. }
  1819. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1820. SSLClient cli(REDIR_HOST);
  1821. cli.set_follow_location(true);
  1822. Params params;
  1823. params.emplace("url", "http://example.com");
  1824. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1825. ASSERT_TRUE(res);
  1826. EXPECT_EQ(StatusCode::OK_200, res->status);
  1827. }
  1828. TEST(UrlWithSpace, Redirect_Online) {
  1829. SSLClient cli("edge.forgecdn.net");
  1830. cli.set_follow_location(true);
  1831. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1832. ASSERT_TRUE(res);
  1833. EXPECT_EQ(StatusCode::OK_200, res->status);
  1834. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1835. }
  1836. #endif
  1837. #if !defined(_WIN32) && !defined(_WIN64)
  1838. TEST(ReceiveSignals, Signal) {
  1839. auto setupSignalHandlers = []() {
  1840. struct sigaction act;
  1841. sigemptyset(&act.sa_mask);
  1842. act.sa_flags = SA_SIGINFO;
  1843. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1844. switch (sig) {
  1845. case SIGINT:
  1846. default: break;
  1847. }
  1848. };
  1849. ::sigaction(SIGINT, &act, nullptr);
  1850. };
  1851. Server svr;
  1852. int port = 0;
  1853. auto thread = std::thread([&]() {
  1854. setupSignalHandlers();
  1855. port = svr.bind_to_any_port(HOST);
  1856. svr.listen_after_bind();
  1857. });
  1858. auto se = detail::scope_exit([&] {
  1859. svr.stop();
  1860. thread.join();
  1861. ASSERT_FALSE(svr.is_running());
  1862. });
  1863. svr.wait_until_ready();
  1864. ASSERT_TRUE(svr.is_running());
  1865. pthread_kill(thread.native_handle(), SIGINT);
  1866. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1867. ASSERT_TRUE(svr.is_running());
  1868. }
  1869. #endif
  1870. TEST(RedirectToDifferentPort, Redirect) {
  1871. Server svr1;
  1872. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1873. res.set_content("Hello World!", "text/plain");
  1874. });
  1875. int svr1_port = 0;
  1876. auto thread1 = std::thread([&]() {
  1877. svr1_port = svr1.bind_to_any_port(HOST);
  1878. svr1.listen_after_bind();
  1879. });
  1880. Server svr2;
  1881. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1882. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1883. });
  1884. int svr2_port = 0;
  1885. auto thread2 = std::thread([&]() {
  1886. svr2_port = svr2.bind_to_any_port(HOST);
  1887. svr2.listen_after_bind();
  1888. });
  1889. auto se = detail::scope_exit([&] {
  1890. svr2.stop();
  1891. thread2.join();
  1892. svr1.stop();
  1893. thread1.join();
  1894. ASSERT_FALSE(svr2.is_running());
  1895. ASSERT_FALSE(svr1.is_running());
  1896. });
  1897. svr1.wait_until_ready();
  1898. svr2.wait_until_ready();
  1899. Client cli("localhost", svr2_port);
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get("/2");
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. }
  1906. TEST(RedirectFromPageWithContent, Redirect) {
  1907. Server svr;
  1908. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1909. res.set_content("___", "text/plain");
  1910. res.set_redirect("/2");
  1911. });
  1912. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1913. res.set_content("Hello World!", "text/plain");
  1914. });
  1915. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1916. auto se = detail::scope_exit([&] {
  1917. svr.stop();
  1918. th.join();
  1919. ASSERT_FALSE(svr.is_running());
  1920. });
  1921. svr.wait_until_ready();
  1922. {
  1923. Client cli("localhost", PORT);
  1924. cli.set_follow_location(true);
  1925. std::string body;
  1926. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1927. body.append(data, data_length);
  1928. return true;
  1929. });
  1930. ASSERT_TRUE(res);
  1931. EXPECT_EQ(StatusCode::OK_200, res->status);
  1932. EXPECT_EQ("Hello World!", body);
  1933. }
  1934. {
  1935. Client cli("localhost", PORT);
  1936. std::string body;
  1937. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(StatusCode::Found_302, res->status);
  1943. EXPECT_EQ("___", body);
  1944. }
  1945. }
  1946. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1947. Server svr;
  1948. auto port_str = std::to_string(PORT);
  1949. auto redirect_url = "http://[::1]:" + port_str + "/2";
  1950. auto expected_host = "[::1]:" + port_str;
  1951. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("___", "text/plain");
  1953. // res.set_redirect("/2");
  1954. res.set_redirect(redirect_url);
  1955. });
  1956. svr.Get("/2", [&](const Request &req, Response &res) {
  1957. auto host_header = req.headers.find("Host");
  1958. ASSERT_TRUE(host_header != req.headers.end());
  1959. EXPECT_EQ(expected_host, host_header->second);
  1960. res.set_content("Hello World!", "text/plain");
  1961. });
  1962. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  1963. auto se = detail::scope_exit([&] {
  1964. svr.stop();
  1965. th.join();
  1966. ASSERT_FALSE(svr.is_running());
  1967. });
  1968. // When IPV6 support isn't available svr.listen("::1", PORT) never
  1969. // actually starts anything, so the condition !svr.is_running() will
  1970. // always remain true, and the loop never stops.
  1971. // This basically counts how many milliseconds have passed since the
  1972. // call to svr.listen(), and if after 5 seconds nothing started yet
  1973. // aborts the test.
  1974. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1975. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1976. ASSERT_LT(milliseconds, 5000U);
  1977. }
  1978. {
  1979. Client cli("::1", PORT);
  1980. cli.set_follow_location(true);
  1981. std::string body;
  1982. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1983. body.append(data, data_length);
  1984. return true;
  1985. });
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::OK_200, res->status);
  1988. EXPECT_EQ("Hello World!", body);
  1989. }
  1990. {
  1991. Client cli("::1", PORT);
  1992. std::string body;
  1993. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1994. body.append(data, data_length);
  1995. return true;
  1996. });
  1997. ASSERT_TRUE(res);
  1998. EXPECT_EQ(StatusCode::Found_302, res->status);
  1999. EXPECT_EQ("___", body);
  2000. }
  2001. }
  2002. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2003. Server svr;
  2004. svr.Get("/foo", [](const Request &req, Response &res) {
  2005. auto a = req.params.find("a");
  2006. if (a != req.params.end()) {
  2007. res.set_content((*a).second, "text/plain");
  2008. res.status = StatusCode::OK_200;
  2009. } else {
  2010. res.status = StatusCode::BadRequest_400;
  2011. }
  2012. });
  2013. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2014. auto se = detail::scope_exit([&] {
  2015. svr.stop();
  2016. thread.join();
  2017. ASSERT_FALSE(svr.is_running());
  2018. });
  2019. svr.wait_until_ready();
  2020. {
  2021. Client cli(HOST, PORT);
  2022. cli.set_path_encode(false);
  2023. auto res = cli.Get("/foo?a=explicitly+encoded");
  2024. ASSERT_TRUE(res);
  2025. EXPECT_EQ(StatusCode::OK_200, res->status);
  2026. // This expects it back with a space, as the `+` won't have been
  2027. // url-encoded, and server-side the params get decoded turning `+`
  2028. // into spaces.
  2029. EXPECT_EQ("explicitly encoded", res->body);
  2030. }
  2031. }
  2032. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2033. Server svr;
  2034. svr.Get("/", [](const Request &req, Response &) {
  2035. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2036. });
  2037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2038. auto se = detail::scope_exit([&] {
  2039. svr.stop();
  2040. thread.join();
  2041. ASSERT_FALSE(svr.is_running());
  2042. });
  2043. svr.wait_until_ready();
  2044. {
  2045. Client cli(HOST, PORT);
  2046. cli.set_path_encode(false);
  2047. auto res = cli.Get("/?something=%0A");
  2048. ASSERT_TRUE(res);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. }
  2052. TEST(BindServerTest, DISABLED_BindDualStack) {
  2053. Server svr;
  2054. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2055. res.set_content("Hello World!", "text/plain");
  2056. });
  2057. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2058. auto se = detail::scope_exit([&] {
  2059. svr.stop();
  2060. thread.join();
  2061. ASSERT_FALSE(svr.is_running());
  2062. });
  2063. svr.wait_until_ready();
  2064. {
  2065. Client cli("127.0.0.1", PORT);
  2066. auto res = cli.Get("/1");
  2067. ASSERT_TRUE(res);
  2068. EXPECT_EQ(StatusCode::OK_200, res->status);
  2069. EXPECT_EQ("Hello World!", res->body);
  2070. }
  2071. {
  2072. Client cli("::1", PORT);
  2073. auto res = cli.Get("/1");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(StatusCode::OK_200, res->status);
  2076. EXPECT_EQ("Hello World!", res->body);
  2077. }
  2078. }
  2079. TEST(BindServerTest, BindAndListenSeparately) {
  2080. Server svr;
  2081. int port = svr.bind_to_any_port("0.0.0.0");
  2082. ASSERT_TRUE(svr.is_valid());
  2083. ASSERT_TRUE(port > 0);
  2084. svr.stop();
  2085. }
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2089. CLIENT_CA_CERT_DIR);
  2090. int port = svr.bind_to_any_port("0.0.0.0");
  2091. ASSERT_TRUE(svr.is_valid());
  2092. ASSERT_TRUE(port > 0);
  2093. svr.stop();
  2094. }
  2095. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2096. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2097. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2098. int port = svr.bind_to_any_port("0.0.0.0");
  2099. ASSERT_TRUE(svr.is_valid());
  2100. ASSERT_TRUE(port > 0);
  2101. svr.stop();
  2102. }
  2103. TEST(BindServerTest, UpdateCertsPem) {
  2104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2105. int port = svr.bind_to_any_port("0.0.0.0");
  2106. ASSERT_TRUE(svr.is_valid());
  2107. ASSERT_TRUE(port > 0);
  2108. // Read PEM files
  2109. std::string cert_pem, key_pem, ca_pem;
  2110. read_file(SERVER_CERT_FILE, cert_pem);
  2111. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2112. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2113. // Update server certificates using PEM API
  2114. ASSERT_TRUE(
  2115. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2116. ASSERT_TRUE(svr.is_valid());
  2117. svr.stop();
  2118. }
  2119. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2120. // Start server with client CA (enables client auth)
  2121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2122. ASSERT_TRUE(svr.is_valid());
  2123. bool handler_called = false;
  2124. svr.Get("/test", [&](const Request &req, Response &res) {
  2125. handler_called = true;
  2126. // Verify client certificate is present
  2127. auto cert = req.peer_cert();
  2128. EXPECT_TRUE(static_cast<bool>(cert));
  2129. res.set_content("ok", "text/plain");
  2130. });
  2131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2132. auto se = detail::scope_exit([&] {
  2133. svr.stop();
  2134. t.join();
  2135. ASSERT_FALSE(svr.is_running());
  2136. });
  2137. svr.wait_until_ready();
  2138. // Read PEM files
  2139. std::string cert_pem, key_pem, ca_pem;
  2140. read_file(SERVER_CERT_FILE, cert_pem);
  2141. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2142. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2143. // Update server certificates and client CA using PEM API while server running
  2144. ASSERT_TRUE(
  2145. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2146. // Connect with client certificate
  2147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2148. cli.enable_server_certificate_verification(false);
  2149. cli.set_connection_timeout(30);
  2150. auto res = cli.Get("/test");
  2151. ASSERT_TRUE(res);
  2152. ASSERT_EQ(StatusCode::OK_200, res->status);
  2153. ASSERT_TRUE(handler_called);
  2154. EXPECT_EQ("ok", res->body);
  2155. }
  2156. #endif
  2157. TEST(ErrorHandlerTest, ContentLength) {
  2158. Server svr;
  2159. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2160. res.status = StatusCode::OK_200;
  2161. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2162. "text/html"); // <= Content-Length still 13
  2163. });
  2164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2165. res.set_content("Hello World!\n", "text/plain");
  2166. res.status = 524;
  2167. });
  2168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2169. auto se = detail::scope_exit([&] {
  2170. svr.stop();
  2171. thread.join();
  2172. ASSERT_FALSE(svr.is_running());
  2173. });
  2174. svr.wait_until_ready();
  2175. {
  2176. Client cli(HOST, PORT);
  2177. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(StatusCode::OK_200, res->status);
  2180. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2181. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2182. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2183. }
  2184. }
  2185. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2186. TEST(ExceptionTest, WithoutExceptionHandler) {
  2187. Server svr;
  2188. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2189. throw std::runtime_error("exception...");
  2190. });
  2191. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2192. throw std::runtime_error("exception\r\n...");
  2193. });
  2194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. listen_thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. Client cli("localhost", PORT);
  2202. {
  2203. auto res = cli.Get("/exception");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2206. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2207. }
  2208. {
  2209. auto res = cli.Get("/unknown");
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2213. }
  2214. }
  2215. TEST(ExceptionTest, WithExceptionHandler) {
  2216. Server svr;
  2217. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2218. std::exception_ptr ep) {
  2219. EXPECT_FALSE(ep == nullptr);
  2220. try {
  2221. std::rethrow_exception(ep);
  2222. } catch (std::exception &e) {
  2223. EXPECT_EQ("abc", std::string(e.what()));
  2224. } catch (...) {}
  2225. res.status = StatusCode::InternalServerError_500;
  2226. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2227. "text/html"); // <= Content-Length still 13 at this point
  2228. });
  2229. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2230. res.set_content("Hello World!\n", "text/plain");
  2231. throw std::runtime_error("abc");
  2232. });
  2233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2234. auto se = detail::scope_exit([&] {
  2235. svr.stop();
  2236. thread.join();
  2237. ASSERT_FALSE(svr.is_running());
  2238. });
  2239. svr.wait_until_ready();
  2240. for (size_t i = 0; i < 10; i++) {
  2241. Client cli(HOST, PORT);
  2242. for (size_t j = 0; j < 100; j++) {
  2243. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2244. ASSERT_TRUE(res);
  2245. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2249. }
  2250. cli.set_keep_alive(true);
  2251. for (size_t j = 0; j < 100; j++) {
  2252. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2253. ASSERT_TRUE(res);
  2254. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2255. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2256. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2257. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2258. }
  2259. }
  2260. }
  2261. TEST(ExceptionTest, AndErrorHandler) {
  2262. Server svr;
  2263. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2264. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2265. });
  2266. svr.set_exception_handler(
  2267. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2268. EXPECT_FALSE(ep == nullptr);
  2269. try {
  2270. std::rethrow_exception(ep);
  2271. } catch (std::exception &e) {
  2272. res.set_content(e.what(), "text/html");
  2273. } catch (...) {}
  2274. res.status = StatusCode::InternalServerError_500;
  2275. });
  2276. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2277. throw std::runtime_error("EXCEPTION");
  2278. });
  2279. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2280. res.set_content("ERROR", "text/html");
  2281. res.status = StatusCode::InternalServerError_500;
  2282. });
  2283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2284. auto se = detail::scope_exit([&] {
  2285. svr.stop();
  2286. thread.join();
  2287. ASSERT_FALSE(svr.is_running());
  2288. });
  2289. svr.wait_until_ready();
  2290. Client cli(HOST, PORT);
  2291. {
  2292. auto res = cli.Get("/exception");
  2293. ASSERT_TRUE(res);
  2294. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2295. EXPECT_EQ("EXCEPTION", res->body);
  2296. }
  2297. {
  2298. auto res = cli.Get("/error");
  2299. ASSERT_TRUE(res);
  2300. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2301. EXPECT_EQ("ERROR", res->body);
  2302. }
  2303. {
  2304. auto res = cli.Get("/invalid");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2307. EXPECT_EQ("NOT_FOUND", res->body);
  2308. }
  2309. }
  2310. #endif
  2311. TEST(NoContentTest, ContentLength) {
  2312. Server svr;
  2313. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2314. res.status = StatusCode::NoContent_204;
  2315. });
  2316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2317. auto se = detail::scope_exit([&] {
  2318. svr.stop();
  2319. thread.join();
  2320. ASSERT_FALSE(svr.is_running());
  2321. });
  2322. svr.wait_until_ready();
  2323. {
  2324. Client cli(HOST, PORT);
  2325. auto res = cli.Get("/hi");
  2326. ASSERT_TRUE(res);
  2327. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2329. }
  2330. }
  2331. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2334. ASSERT_TRUE(svr.is_valid());
  2335. #else
  2336. Server svr;
  2337. #endif
  2338. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2339. if (req.path == "/routing_handler") {
  2340. res.set_header("PRE_ROUTING", "on");
  2341. res.set_content("Routing Handler", "text/plain");
  2342. return httplib::Server::HandlerResponse::Handled;
  2343. }
  2344. return httplib::Server::HandlerResponse::Unhandled;
  2345. });
  2346. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2347. res.set_content("Error", "text/html");
  2348. });
  2349. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2350. if (req.path == "/routing_handler") {
  2351. res.set_header("POST_ROUTING", "on");
  2352. }
  2353. });
  2354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2355. res.set_content("Hello World!\n", "text/plain");
  2356. });
  2357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2358. auto se = detail::scope_exit([&] {
  2359. svr.stop();
  2360. thread.join();
  2361. ASSERT_FALSE(svr.is_running());
  2362. });
  2363. svr.wait_until_ready();
  2364. {
  2365. #ifdef CPPHTTPLIB_SSL_ENABLED
  2366. SSLClient cli(HOST, PORT);
  2367. cli.enable_server_certificate_verification(false);
  2368. #else
  2369. Client cli(HOST, PORT);
  2370. #endif
  2371. auto res = cli.Get("/routing_handler");
  2372. ASSERT_TRUE(res);
  2373. EXPECT_EQ(StatusCode::OK_200, res->status);
  2374. EXPECT_EQ("Routing Handler", res->body);
  2375. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2376. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2377. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2378. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2379. }
  2380. {
  2381. #ifdef CPPHTTPLIB_SSL_ENABLED
  2382. SSLClient cli(HOST, PORT);
  2383. cli.enable_server_certificate_verification(false);
  2384. #else
  2385. Client cli(HOST, PORT);
  2386. #endif
  2387. auto res = cli.Get("/hi");
  2388. ASSERT_TRUE(res);
  2389. EXPECT_EQ(StatusCode::OK_200, res->status);
  2390. EXPECT_EQ("Hello World!\n", res->body);
  2391. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2392. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2393. }
  2394. {
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. SSLClient cli(HOST, PORT);
  2397. cli.enable_server_certificate_verification(false);
  2398. #else
  2399. Client cli(HOST, PORT);
  2400. #endif
  2401. auto res = cli.Get("/aaa");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("Error", res->body);
  2405. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2406. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2407. }
  2408. }
  2409. TEST(RequestHandlerTest, PreRequestHandler) {
  2410. auto route_path = "/user/:user";
  2411. Server svr;
  2412. svr.Get("/hi", [](const Request &, Response &res) {
  2413. res.set_content("hi", "text/plain");
  2414. });
  2415. svr.Get(route_path, [](const Request &req, Response &res) {
  2416. res.set_content(req.path_params.at("user"), "text/plain");
  2417. });
  2418. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2419. if (req.matched_route == route_path) {
  2420. auto user = req.path_params.at("user");
  2421. if (user != "john") {
  2422. res.status = StatusCode::Forbidden_403;
  2423. res.set_content("error", "text/html");
  2424. return Server::HandlerResponse::Handled;
  2425. }
  2426. }
  2427. return Server::HandlerResponse::Unhandled;
  2428. });
  2429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2430. auto se = detail::scope_exit([&] {
  2431. svr.stop();
  2432. thread.join();
  2433. ASSERT_FALSE(svr.is_running());
  2434. });
  2435. svr.wait_until_ready();
  2436. Client cli(HOST, PORT);
  2437. {
  2438. auto res = cli.Get("/hi");
  2439. ASSERT_TRUE(res);
  2440. EXPECT_EQ(StatusCode::OK_200, res->status);
  2441. EXPECT_EQ("hi", res->body);
  2442. }
  2443. {
  2444. auto res = cli.Get("/user/john");
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ(StatusCode::OK_200, res->status);
  2447. EXPECT_EQ("john", res->body);
  2448. }
  2449. {
  2450. auto res = cli.Get("/user/invalid-user");
  2451. ASSERT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2453. EXPECT_EQ("error", res->body);
  2454. }
  2455. }
  2456. TEST(AnyTest, BasicOperations) {
  2457. // Default construction
  2458. httplib::any a;
  2459. EXPECT_FALSE(a.has_value());
  2460. // Value construction and any_cast (pointer form, noexcept)
  2461. httplib::any b(42);
  2462. EXPECT_TRUE(b.has_value());
  2463. auto *p = httplib::any_cast<int>(&b);
  2464. ASSERT_NE(nullptr, p);
  2465. EXPECT_EQ(42, *p);
  2466. // Type mismatch → nullptr
  2467. auto *q = httplib::any_cast<std::string>(&b);
  2468. EXPECT_EQ(nullptr, q);
  2469. // any_cast (value form) succeeds
  2470. EXPECT_EQ(42, httplib::any_cast<int>(b));
  2471. // any_cast (value form) throws on type mismatch
  2472. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2473. EXPECT_THROW(httplib::any_cast<std::string>(b), httplib::bad_any_cast);
  2474. #endif
  2475. // Copy
  2476. httplib::any c = b;
  2477. EXPECT_EQ(42, httplib::any_cast<int>(c));
  2478. // Move
  2479. httplib::any d = std::move(c);
  2480. EXPECT_EQ(42, httplib::any_cast<int>(d));
  2481. // Assignment with different type
  2482. b = std::string("hello");
  2483. EXPECT_EQ("hello", httplib::any_cast<std::string>(b));
  2484. // Reset
  2485. b.reset();
  2486. EXPECT_FALSE(b.has_value());
  2487. }
  2488. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2489. struct AuthCtx {
  2490. std::string user_id;
  2491. };
  2492. Server svr;
  2493. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2494. res.user_data["auth"] = AuthCtx{"alice"};
  2495. return Server::HandlerResponse::Unhandled;
  2496. });
  2497. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2498. auto *ctx = httplib::any_cast<AuthCtx>(&res.user_data["auth"]);
  2499. ASSERT_NE(nullptr, ctx);
  2500. res.set_content("Hello " + ctx->user_id, "text/plain");
  2501. });
  2502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2503. auto se = detail::scope_exit([&] {
  2504. svr.stop();
  2505. thread.join();
  2506. ASSERT_FALSE(svr.is_running());
  2507. });
  2508. svr.wait_until_ready();
  2509. Client cli(HOST, PORT);
  2510. auto res = cli.Get("/me");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(StatusCode::OK_200, res->status);
  2513. EXPECT_EQ("Hello alice", res->body);
  2514. }
  2515. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2516. struct RoleCtx {
  2517. std::string role;
  2518. };
  2519. Server svr;
  2520. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2521. res.user_data["role"] = RoleCtx{"admin"};
  2522. return Server::HandlerResponse::Unhandled;
  2523. });
  2524. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2525. auto *ctx = httplib::any_cast<RoleCtx>(&res.user_data["role"]);
  2526. ASSERT_NE(nullptr, ctx);
  2527. res.set_content(ctx->role, "text/plain");
  2528. });
  2529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2530. auto se = detail::scope_exit([&] {
  2531. svr.stop();
  2532. thread.join();
  2533. ASSERT_FALSE(svr.is_running());
  2534. });
  2535. svr.wait_until_ready();
  2536. Client cli(HOST, PORT);
  2537. auto res = cli.Get("/role");
  2538. ASSERT_TRUE(res);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. EXPECT_EQ("admin", res->body);
  2541. }
  2542. TEST(InvalidFormatTest, StatusCode) {
  2543. Server svr;
  2544. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2545. res.set_content("Hello World!\n", "text/plain");
  2546. res.status = 9999; // Status should be a three-digit code...
  2547. });
  2548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2549. auto se = detail::scope_exit([&] {
  2550. svr.stop();
  2551. thread.join();
  2552. ASSERT_FALSE(svr.is_running());
  2553. });
  2554. svr.wait_until_ready();
  2555. {
  2556. Client cli(HOST, PORT);
  2557. auto res = cli.Get("/hi");
  2558. ASSERT_FALSE(res);
  2559. }
  2560. }
  2561. TEST(URLFragmentTest, WithFragment) {
  2562. Server svr;
  2563. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2564. EXPECT_TRUE(req.target == "/hi");
  2565. });
  2566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2567. auto se = detail::scope_exit([&] {
  2568. svr.stop();
  2569. thread.join();
  2570. ASSERT_FALSE(svr.is_running());
  2571. });
  2572. svr.wait_until_ready();
  2573. {
  2574. Client cli(HOST, PORT);
  2575. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2576. EXPECT_TRUE(res);
  2577. EXPECT_EQ(StatusCode::OK_200, res->status);
  2578. res = cli.Get("/hi%23key1=val1=key2=val2");
  2579. EXPECT_TRUE(res);
  2580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2581. }
  2582. }
  2583. TEST(HeaderWriter, SetHeaderWriter) {
  2584. Server svr;
  2585. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2586. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2587. return detail::write_headers(strm, hdrs);
  2588. });
  2589. svr.Get("/hi", [](const Request &req, Response &res) {
  2590. auto it = req.headers.find("CustomClientHeader");
  2591. EXPECT_TRUE(it != req.headers.end());
  2592. EXPECT_EQ(it->second, "CustomClientValue");
  2593. res.set_content("Hello World!\n", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. {
  2603. Client cli(HOST, PORT);
  2604. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2605. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2606. return detail::write_headers(strm, hdrs);
  2607. });
  2608. auto res = cli.Get("/hi");
  2609. EXPECT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. auto it = res->headers.find("CustomServerHeader");
  2612. EXPECT_TRUE(it != res->headers.end());
  2613. EXPECT_EQ(it->second, "CustomServerValue");
  2614. }
  2615. }
  2616. class ServerTest : public ::testing::Test {
  2617. protected:
  2618. ServerTest()
  2619. : cli_(HOST, PORT)
  2620. #ifdef CPPHTTPLIB_SSL_ENABLED
  2621. ,
  2622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2623. #endif
  2624. {
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. cli_.enable_server_certificate_verification(false);
  2627. #endif
  2628. // Allow LARGE_DATA (100MB) responses
  2629. cli_.set_payload_max_length(200 * 1024 * 1024);
  2630. }
  2631. virtual void SetUp() {
  2632. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2633. svr_.set_payload_max_length(200 * 1024 * 1024);
  2634. svr_.set_mount_point("/", "./www");
  2635. svr_.set_mount_point("/mount", "./www2");
  2636. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2637. svr_.Get("/hi",
  2638. [&](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!", "text/plain");
  2640. })
  2641. .Get("/file_content",
  2642. [&](const Request & /*req*/, Response &res) {
  2643. res.set_file_content("./www/dir/test.html");
  2644. })
  2645. .Get("/file_content_with_content_type",
  2646. [&](const Request & /*req*/, Response &res) {
  2647. res.set_file_content("./www/file", "text/plain");
  2648. })
  2649. .Get("/invalid_file_content",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. res.set_file_content("./www/dir/invalid_file_path");
  2652. })
  2653. .Get("/http_response_splitting",
  2654. [&](const Request & /*req*/, Response &res) {
  2655. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2656. EXPECT_EQ(0U, res.headers.size());
  2657. EXPECT_FALSE(res.has_header("a"));
  2658. res.set_header("a", "1\nSet-Cookie: a=1");
  2659. EXPECT_EQ(0U, res.headers.size());
  2660. EXPECT_FALSE(res.has_header("a"));
  2661. res.set_header("a", "1\rSet-Cookie: a=1");
  2662. EXPECT_EQ(0U, res.headers.size());
  2663. EXPECT_FALSE(res.has_header("a"));
  2664. res.set_header("a\r\nb", "0");
  2665. EXPECT_EQ(0U, res.headers.size());
  2666. EXPECT_FALSE(res.has_header("a"));
  2667. res.set_header("a\rb", "0");
  2668. EXPECT_EQ(0U, res.headers.size());
  2669. EXPECT_FALSE(res.has_header("a"));
  2670. res.set_header("a\nb", "0");
  2671. EXPECT_EQ(0U, res.headers.size());
  2672. EXPECT_FALSE(res.has_header("a"));
  2673. res.set_redirect("1\r\nSet-Cookie: a=1");
  2674. EXPECT_EQ(0U, res.headers.size());
  2675. EXPECT_FALSE(res.has_header("Location"));
  2676. })
  2677. .Get("/slow",
  2678. [&](const Request & /*req*/, Response &res) {
  2679. std::this_thread::sleep_for(std::chrono::seconds(2));
  2680. res.set_content("slow", "text/plain");
  2681. })
  2682. #if 0
  2683. .Post("/slowpost",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. std::this_thread::sleep_for(std::chrono::seconds(2));
  2686. res.set_content("slow", "text/plain");
  2687. })
  2688. #endif
  2689. .Get("/remote_addr",
  2690. [&](const Request &req, Response &res) {
  2691. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2692. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2694. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2695. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2696. #endif
  2697. res.set_content(req.remote_addr, "text/plain");
  2698. })
  2699. .Get("/local_addr",
  2700. [&](const Request &req, Response &res) {
  2701. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2702. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2703. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2704. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2705. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2706. #endif
  2707. auto local_addr = req.local_addr;
  2708. auto local_port = std::to_string(req.local_port);
  2709. res.set_content(local_addr.append(":").append(local_port),
  2710. "text/plain");
  2711. })
  2712. .Get("/endwith%",
  2713. [&](const Request & /*req*/, Response &res) {
  2714. res.set_content("Hello World!", "text/plain");
  2715. })
  2716. .Get("/a\\+\\+b",
  2717. [&](const Request &req, Response &res) {
  2718. ASSERT_TRUE(req.has_param("a +b"));
  2719. auto val = req.get_param_value("a +b");
  2720. res.set_content(val, "text/plain");
  2721. })
  2722. .Get("/", [&](const Request & /*req*/,
  2723. Response &res) { res.set_redirect("/hi"); })
  2724. .Post("/1",
  2725. [](const Request & /*req*/, Response &res) {
  2726. res.set_redirect("/2", StatusCode::SeeOther_303);
  2727. })
  2728. .Get("/2",
  2729. [](const Request & /*req*/, Response &res) {
  2730. res.set_content("redirected.", "text/plain");
  2731. res.status = StatusCode::OK_200;
  2732. })
  2733. .Post("/person",
  2734. [&](const Request &req, Response &res) {
  2735. if (req.has_param("name") && req.has_param("note")) {
  2736. persons_[req.get_param_value("name")] =
  2737. req.get_param_value("note");
  2738. } else {
  2739. res.status = StatusCode::BadRequest_400;
  2740. }
  2741. })
  2742. .Put("/person",
  2743. [&](const Request &req, Response &res) {
  2744. if (req.has_param("name") && req.has_param("note")) {
  2745. persons_[req.get_param_value("name")] =
  2746. req.get_param_value("note");
  2747. } else {
  2748. res.status = StatusCode::BadRequest_400;
  2749. }
  2750. })
  2751. .Get("/person/(.*)",
  2752. [&](const Request &req, Response &res) {
  2753. string name = req.matches[1];
  2754. if (persons_.find(name) != persons_.end()) {
  2755. auto note = persons_[name];
  2756. res.set_content(note, "text/plain");
  2757. } else {
  2758. res.status = StatusCode::NotFound_404;
  2759. }
  2760. })
  2761. .Delete("/person",
  2762. [&](const Request &req, Response &res) {
  2763. if (req.has_param("name")) {
  2764. string name = req.get_param_value("name");
  2765. if (persons_.find(name) != persons_.end()) {
  2766. persons_.erase(name);
  2767. res.set_content("DELETED", "text/plain");
  2768. } else {
  2769. res.status = StatusCode::NotFound_404;
  2770. }
  2771. } else {
  2772. res.status = StatusCode::BadRequest_400;
  2773. }
  2774. })
  2775. .Post("/x-www-form-urlencoded-json",
  2776. [&](const Request &req, Response &res) {
  2777. auto json = req.get_param_value("json");
  2778. ASSERT_EQ(JSON_DATA, json);
  2779. res.set_content(json, "appliation/json");
  2780. res.status = StatusCode::OK_200;
  2781. })
  2782. .Get("/streamed-chunked",
  2783. [&](const Request & /*req*/, Response &res) {
  2784. res.set_chunked_content_provider(
  2785. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2786. sink.os << "123";
  2787. sink.os << "456";
  2788. sink.os << "789";
  2789. sink.done();
  2790. return true;
  2791. });
  2792. })
  2793. .Get("/streamed-chunked-with-prohibited-trailer",
  2794. [&](const Request & /*req*/, Response &res) {
  2795. auto i = new int(0);
  2796. // Declare both a prohibited trailer (Content-Length) and an
  2797. // allowed one
  2798. res.set_header("Trailer", "Content-Length, X-Allowed");
  2799. res.set_chunked_content_provider(
  2800. "text/plain",
  2801. [i](size_t /*offset*/, DataSink &sink) {
  2802. switch (*i) {
  2803. case 0: sink.os << "123"; break;
  2804. case 1: sink.os << "456"; break;
  2805. case 2: sink.os << "789"; break;
  2806. case 3: {
  2807. sink.done_with_trailer(
  2808. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2809. } break;
  2810. }
  2811. (*i)++;
  2812. return true;
  2813. },
  2814. [i](bool success) {
  2815. EXPECT_TRUE(success);
  2816. delete i;
  2817. });
  2818. })
  2819. .Get("/streamed-chunked2",
  2820. [&](const Request & /*req*/, Response &res) {
  2821. auto i = new int(0);
  2822. res.set_chunked_content_provider(
  2823. "text/plain",
  2824. [i](size_t /*offset*/, DataSink &sink) {
  2825. switch (*i) {
  2826. case 0: sink.os << "123"; break;
  2827. case 1: sink.os << "456"; break;
  2828. case 2: sink.os << "789"; break;
  2829. case 3: sink.done(); break;
  2830. }
  2831. (*i)++;
  2832. return true;
  2833. },
  2834. [i](bool success) {
  2835. EXPECT_TRUE(success);
  2836. delete i;
  2837. });
  2838. })
  2839. .Get("/streamed-chunked-with-trailer",
  2840. [&](const Request & /*req*/, Response &res) {
  2841. auto i = new int(0);
  2842. res.set_header("Trailer", "Dummy1, Dummy2");
  2843. res.set_chunked_content_provider(
  2844. "text/plain",
  2845. [i](size_t /*offset*/, DataSink &sink) {
  2846. switch (*i) {
  2847. case 0: sink.os << "123"; break;
  2848. case 1: sink.os << "456"; break;
  2849. case 2: sink.os << "789"; break;
  2850. case 3: {
  2851. sink.done_with_trailer(
  2852. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2853. } break;
  2854. }
  2855. (*i)++;
  2856. return true;
  2857. },
  2858. [i](bool success) {
  2859. EXPECT_TRUE(success);
  2860. delete i;
  2861. });
  2862. })
  2863. .Get("/streamed",
  2864. [&](const Request & /*req*/, Response &res) {
  2865. res.set_content_provider(
  2866. 6, "text/plain",
  2867. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2868. sink.os << (offset < 3 ? "a" : "b");
  2869. return true;
  2870. });
  2871. })
  2872. .Get("/streamed-with-range",
  2873. [&](const Request &req, Response &res) {
  2874. auto data = new std::string("abcdefg");
  2875. res.set_content_provider(
  2876. data->size(), "text/plain",
  2877. [data](size_t offset, size_t length, DataSink &sink) {
  2878. size_t DATA_CHUNK_SIZE = 4;
  2879. const auto &d = *data;
  2880. auto out_len =
  2881. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2882. auto ret =
  2883. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2884. EXPECT_TRUE(ret);
  2885. return true;
  2886. },
  2887. [data, &req](bool success) {
  2888. EXPECT_EQ(success, !req.has_param("error"));
  2889. delete data;
  2890. });
  2891. })
  2892. .Get("/streamed-cancel",
  2893. [&](const Request & /*req*/, Response &res) {
  2894. res.set_content_provider(
  2895. size_t(-1), "text/plain",
  2896. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2897. sink.os << "data_chunk";
  2898. return true;
  2899. });
  2900. })
  2901. .Get("/regex-with-delimiter",
  2902. [&](const Request &req, Response & /*res*/) {
  2903. ASSERT_TRUE(req.has_param("key"));
  2904. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2905. })
  2906. .Get("/with-range",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_content("abcdefg", "text/plain");
  2909. })
  2910. .Get("/test-start-time",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_NE(req.start_time_,
  2913. std::chrono::steady_clock::time_point::min());
  2914. })
  2915. .Get("/with-range-customized-response",
  2916. [&](const Request & /*req*/, Response &res) {
  2917. res.status = StatusCode::BadRequest_400;
  2918. res.set_content(JSON_DATA, "application/json");
  2919. })
  2920. .Post("/chunked",
  2921. [&](const Request &req, Response & /*res*/) {
  2922. EXPECT_EQ(req.body, "dechunked post body");
  2923. })
  2924. .Post("/large-chunked",
  2925. [&](const Request &req, Response & /*res*/) {
  2926. std::string expected(6 * 30 * 1024u, 'a');
  2927. EXPECT_EQ(req.body, expected);
  2928. })
  2929. .Post("/multipart",
  2930. [&](const Request &req, Response & /*res*/) {
  2931. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2932. req.form.get_field_count("text2") +
  2933. req.form.get_field_count("file3") +
  2934. req.form.get_field_count("file4"));
  2935. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2936. req.form.get_file_count("file2"));
  2937. ASSERT_TRUE(!req.form.has_file("???"));
  2938. ASSERT_TRUE(!req.form.has_field("???"));
  2939. ASSERT_TRUE(req.body.empty());
  2940. {
  2941. const auto &text = req.form.get_field("text1");
  2942. EXPECT_EQ("text default", text);
  2943. }
  2944. {
  2945. const auto &text = req.form.get_field("text2");
  2946. EXPECT_EQ("aωb", text);
  2947. }
  2948. {
  2949. const auto &file = req.form.get_file("file1");
  2950. EXPECT_EQ("hello.txt", file.filename);
  2951. EXPECT_EQ("text/plain", file.content_type);
  2952. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2953. }
  2954. {
  2955. const auto &file = req.form.get_file("file2");
  2956. EXPECT_EQ("world.json", file.filename);
  2957. EXPECT_EQ("application/json", file.content_type);
  2958. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2959. }
  2960. {
  2961. const auto &text = req.form.get_field("file3");
  2962. EXPECT_EQ(0u, text.size());
  2963. }
  2964. {
  2965. const auto &text = req.form.get_field("file4");
  2966. EXPECT_EQ(0u, text.size());
  2967. }
  2968. })
  2969. .Post("/multipart/multi_file_values",
  2970. [&](const Request &req, Response & /*res*/) {
  2971. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2972. req.form.get_field_count("multi_text1"));
  2973. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2974. ASSERT_TRUE(!req.form.has_file("???"));
  2975. ASSERT_TRUE(!req.form.has_field("???"));
  2976. ASSERT_TRUE(req.body.empty());
  2977. {
  2978. const auto &text = req.form.get_field("text");
  2979. EXPECT_EQ("default text", text);
  2980. }
  2981. {
  2982. const auto &text1_values = req.form.get_fields("multi_text1");
  2983. EXPECT_EQ(2u, text1_values.size());
  2984. EXPECT_EQ("aaaaa", text1_values[0]);
  2985. EXPECT_EQ("bbbbb", text1_values[1]);
  2986. }
  2987. {
  2988. const auto &file1_values = req.form.get_files("multi_file1");
  2989. EXPECT_EQ(2u, file1_values.size());
  2990. auto file1 = file1_values[0];
  2991. EXPECT_EQ(file1.filename, "hello.txt");
  2992. EXPECT_EQ(file1.content_type, "text/plain");
  2993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2994. auto file2 = file1_values[1];
  2995. EXPECT_EQ(file2.filename, "world.json");
  2996. EXPECT_EQ(file2.content_type, "application/json");
  2997. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2998. }
  2999. })
  3000. .Post("/empty",
  3001. [&](const Request &req, Response &res) {
  3002. EXPECT_EQ(req.body, "");
  3003. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3004. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3005. res.set_content("empty", "text/plain");
  3006. })
  3007. .Post("/empty-no-content-type",
  3008. [&](const Request &req, Response &res) {
  3009. EXPECT_EQ(req.body, "");
  3010. EXPECT_FALSE(req.has_header("Content-Type"));
  3011. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3012. res.set_content("empty-no-content-type", "text/plain");
  3013. })
  3014. .Post("/path-only",
  3015. [&](const Request &req, Response &res) {
  3016. EXPECT_EQ(req.body, "");
  3017. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3018. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3019. res.set_content("path-only", "text/plain");
  3020. })
  3021. .Post("/path-headers-only",
  3022. [&](const Request &req, Response &res) {
  3023. EXPECT_EQ(req.body, "");
  3024. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3025. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3026. EXPECT_EQ("world", req.get_header_value("hello"));
  3027. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3028. res.set_content("path-headers-only", "text/plain");
  3029. })
  3030. .Post("/post-large",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(req.body, LARGE_DATA);
  3033. res.set_content(req.body, "text/plain");
  3034. })
  3035. .Post("/post-loopback",
  3036. [&](const Request &, Response &res,
  3037. ContentReader const &content_reader) {
  3038. std::string body;
  3039. content_reader([&](const char *data, size_t data_length) {
  3040. body.append(data, data_length);
  3041. return true;
  3042. });
  3043. res.set_content(body, "text/plain");
  3044. })
  3045. .Put("/put-loopback",
  3046. [&](const Request &, Response &res,
  3047. ContentReader const &content_reader) {
  3048. std::string body;
  3049. content_reader([&](const char *data, size_t data_length) {
  3050. body.append(data, data_length);
  3051. return true;
  3052. });
  3053. res.set_content(body, "text/plain");
  3054. })
  3055. .Patch("/patch-loopback",
  3056. [&](const Request &, Response &res,
  3057. ContentReader const &content_reader) {
  3058. std::string body;
  3059. content_reader([&](const char *data, size_t data_length) {
  3060. body.append(data, data_length);
  3061. return true;
  3062. });
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Put("/empty-no-content-type",
  3066. [&](const Request &req, Response &res) {
  3067. EXPECT_EQ(req.body, "");
  3068. EXPECT_FALSE(req.has_header("Content-Type"));
  3069. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3070. res.set_content("empty-no-content-type", "text/plain");
  3071. })
  3072. .Put("/put",
  3073. [&](const Request &req, Response &res) {
  3074. EXPECT_EQ(req.body, "PUT");
  3075. res.set_content(req.body, "text/plain");
  3076. })
  3077. .Put("/put-large",
  3078. [&](const Request &req, Response &res) {
  3079. EXPECT_EQ(req.body, LARGE_DATA);
  3080. res.set_content(req.body, "text/plain");
  3081. })
  3082. .Patch("/patch",
  3083. [&](const Request &req, Response &res) {
  3084. EXPECT_EQ(req.body, "PATCH");
  3085. res.set_content(req.body, "text/plain");
  3086. })
  3087. .Delete("/delete",
  3088. [&](const Request & /*req*/, Response &res) {
  3089. res.set_content("DELETE", "text/plain");
  3090. })
  3091. .Delete("/delete-body",
  3092. [&](const Request &req, Response &res) {
  3093. EXPECT_EQ(req.body, "content");
  3094. res.set_content(req.body, "text/plain");
  3095. })
  3096. .Options(R"(\*)",
  3097. [&](const Request & /*req*/, Response &res) {
  3098. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3099. })
  3100. .Get("/request-target",
  3101. [&](const Request &req, Response & /*res*/) {
  3102. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3103. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3104. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3105. })
  3106. .Get("/long-query-value",
  3107. [&](const Request &req, Response & /*res*/) {
  3108. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3109. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3110. })
  3111. .Get("/too-long-query-value",
  3112. [&](const Request &req, Response & /*res*/) {
  3113. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3114. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3115. })
  3116. .Get("/array-param",
  3117. [&](const Request &req, Response & /*res*/) {
  3118. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3119. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3120. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3121. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3122. })
  3123. .Post("/validate-no-multiple-headers",
  3124. [&](const Request &req, Response & /*res*/) {
  3125. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3126. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3127. })
  3128. .Post("/content_receiver",
  3129. [&](const Request &req, Response &res,
  3130. const ContentReader &content_reader) {
  3131. if (req.is_multipart_form_data()) {
  3132. std::vector<FormData> items;
  3133. content_reader(
  3134. [&](const FormData &file) {
  3135. items.push_back(file);
  3136. return true;
  3137. },
  3138. [&](const char *data, size_t data_length) {
  3139. items.back().content.append(data, data_length);
  3140. return true;
  3141. });
  3142. EXPECT_EQ(5u, items.size());
  3143. {
  3144. const auto &file = get_file_value(items, "text1");
  3145. EXPECT_TRUE(file.filename.empty());
  3146. EXPECT_EQ("text default", file.content);
  3147. }
  3148. {
  3149. const auto &file = get_file_value(items, "text2");
  3150. EXPECT_TRUE(file.filename.empty());
  3151. EXPECT_EQ("aωb", file.content);
  3152. }
  3153. {
  3154. const auto &file = get_file_value(items, "file1");
  3155. EXPECT_EQ("hello.txt", file.filename);
  3156. EXPECT_EQ("text/plain", file.content_type);
  3157. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3158. }
  3159. {
  3160. const auto &file = get_file_value(items, "file2");
  3161. EXPECT_EQ("world.json", file.filename);
  3162. EXPECT_EQ("application/json", file.content_type);
  3163. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3164. }
  3165. {
  3166. const auto &file = get_file_value(items, "file3");
  3167. EXPECT_TRUE(file.filename.empty());
  3168. EXPECT_EQ("application/octet-stream", file.content_type);
  3169. EXPECT_EQ(0u, file.content.size());
  3170. }
  3171. } else {
  3172. std::string body;
  3173. content_reader([&](const char *data, size_t data_length) {
  3174. EXPECT_EQ(7U, data_length);
  3175. body.append(data, data_length);
  3176. return true;
  3177. });
  3178. EXPECT_EQ(body, "content");
  3179. res.set_content(body, "text/plain");
  3180. }
  3181. })
  3182. .Put("/content_receiver",
  3183. [&](const Request & /*req*/, Response &res,
  3184. const ContentReader &content_reader) {
  3185. std::string body;
  3186. content_reader([&](const char *data, size_t data_length) {
  3187. body.append(data, data_length);
  3188. return true;
  3189. });
  3190. EXPECT_EQ(body, "content");
  3191. res.set_content(body, "text/plain");
  3192. })
  3193. .Patch("/content_receiver",
  3194. [&](const Request & /*req*/, Response &res,
  3195. const ContentReader &content_reader) {
  3196. std::string body;
  3197. content_reader([&](const char *data, size_t data_length) {
  3198. body.append(data, data_length);
  3199. return true;
  3200. });
  3201. EXPECT_EQ(body, "content");
  3202. res.set_content(body, "text/plain");
  3203. })
  3204. .Post("/query-string-and-body",
  3205. [&](const Request &req, Response & /*res*/) {
  3206. ASSERT_TRUE(req.has_param("key"));
  3207. EXPECT_EQ(req.get_param_value("key"), "value");
  3208. EXPECT_EQ(req.body, "content");
  3209. })
  3210. .Get("/last-request",
  3211. [&](const Request &req, Response & /*res*/) {
  3212. EXPECT_EQ("close", req.get_header_value("Connection"));
  3213. })
  3214. .Get(R"(/redirect/(\d+))",
  3215. [&](const Request &req, Response &res) {
  3216. auto num = std::stoi(req.matches[1]) + 1;
  3217. std::string url = "/redirect/" + std::to_string(num);
  3218. res.set_redirect(url);
  3219. })
  3220. .Post("/binary",
  3221. [&](const Request &req, Response &res) {
  3222. EXPECT_EQ(4U, req.body.size());
  3223. EXPECT_EQ("application/octet-stream",
  3224. req.get_header_value("Content-Type"));
  3225. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3226. res.set_content(req.body, "application/octet-stream");
  3227. })
  3228. .Put("/binary",
  3229. [&](const Request &req, Response &res) {
  3230. EXPECT_EQ(4U, req.body.size());
  3231. EXPECT_EQ("application/octet-stream",
  3232. req.get_header_value("Content-Type"));
  3233. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3234. res.set_content(req.body, "application/octet-stream");
  3235. })
  3236. .Patch("/binary",
  3237. [&](const Request &req, Response &res) {
  3238. EXPECT_EQ(4U, req.body.size());
  3239. EXPECT_EQ("application/octet-stream",
  3240. req.get_header_value("Content-Type"));
  3241. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3242. res.set_content(req.body, "application/octet-stream");
  3243. })
  3244. .Delete("/binary",
  3245. [&](const Request &req, Response &res) {
  3246. EXPECT_EQ(4U, req.body.size());
  3247. EXPECT_EQ("application/octet-stream",
  3248. req.get_header_value("Content-Type"));
  3249. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3250. res.set_content(req.body, "application/octet-stream");
  3251. })
  3252. .Get("/issue1772",
  3253. [&](const Request & /*req*/, Response &res) {
  3254. res.status = 401;
  3255. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3256. })
  3257. .Delete("/issue609",
  3258. [](const httplib::Request &, httplib::Response &res,
  3259. const httplib::ContentReader &) {
  3260. res.set_content("ok", "text/plain");
  3261. })
  3262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3263. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3264. .Get("/compress",
  3265. [&](const Request & /*req*/, Response &res) {
  3266. res.set_content(
  3267. "12345678901234567890123456789012345678901234567890123456789"
  3268. "01234567890123456789012345678901234567890",
  3269. "text/plain");
  3270. })
  3271. .Get("/compress-with-charset",
  3272. [&](const Request & /*req*/, Response &res) {
  3273. res.set_content(
  3274. "12345678901234567890123456789012345678901234567890123456789"
  3275. "01234567890123456789012345678901234567890",
  3276. "application/json; charset=utf-8");
  3277. })
  3278. .Get("/nocompress",
  3279. [&](const Request & /*req*/, Response &res) {
  3280. res.set_content(
  3281. "12345678901234567890123456789012345678901234567890123456789"
  3282. "01234567890123456789012345678901234567890",
  3283. "application/octet-stream");
  3284. })
  3285. .Post("/compress-multipart",
  3286. [&](const Request &req, Response & /*res*/) {
  3287. EXPECT_EQ(2u, req.form.fields.size());
  3288. ASSERT_TRUE(!req.form.has_field("???"));
  3289. {
  3290. const auto &text = req.form.get_field("key1");
  3291. EXPECT_EQ("test", text);
  3292. }
  3293. {
  3294. const auto &text = req.form.get_field("key2");
  3295. EXPECT_EQ("--abcdefg123", text);
  3296. }
  3297. })
  3298. #endif
  3299. ;
  3300. persons_["john"] = "programmer";
  3301. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3302. svr_.wait_until_ready();
  3303. }
  3304. virtual void TearDown() {
  3305. svr_.stop();
  3306. if (!request_threads_.empty()) {
  3307. std::this_thread::sleep_for(std::chrono::seconds(1));
  3308. for (auto &t : request_threads_) {
  3309. t.join();
  3310. }
  3311. }
  3312. t_.join();
  3313. }
  3314. map<string, string> persons_;
  3315. #ifdef CPPHTTPLIB_SSL_ENABLED
  3316. SSLClient cli_;
  3317. SSLServer svr_;
  3318. #else
  3319. Client cli_;
  3320. Server svr_;
  3321. #endif
  3322. thread t_;
  3323. std::vector<thread> request_threads_;
  3324. };
  3325. TEST_F(ServerTest, GetMethod200) {
  3326. auto res = cli_.Get("/hi");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ("HTTP/1.1", res->version);
  3329. EXPECT_EQ(StatusCode::OK_200, res->status);
  3330. EXPECT_EQ("OK", res->reason);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3333. EXPECT_EQ("Hello World!", res->body);
  3334. }
  3335. TEST_F(ServerTest, GetEmptyFile) {
  3336. auto res = cli_.Get("/empty_file");
  3337. ASSERT_TRUE(res);
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3340. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3341. EXPECT_EQ("", res->body);
  3342. }
  3343. TEST_F(ServerTest, GetFileContent) {
  3344. auto res = cli_.Get("/file_content");
  3345. ASSERT_TRUE(res);
  3346. EXPECT_EQ(StatusCode::OK_200, res->status);
  3347. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3348. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3349. EXPECT_EQ("test.html", res->body);
  3350. }
  3351. TEST_F(ServerTest, GetFileContentWithRange) {
  3352. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3353. ASSERT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3355. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3356. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3357. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3358. EXPECT_EQ("est", res->body);
  3359. }
  3360. TEST_F(ServerTest, GetFileContentWithContentType) {
  3361. auto res = cli_.Get("/file_content_with_content_type");
  3362. ASSERT_TRUE(res);
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3365. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3366. EXPECT_EQ("file\n", res->body);
  3367. }
  3368. TEST_F(ServerTest, GetInvalidFileContent) {
  3369. auto res = cli_.Get("/invalid_file_content");
  3370. ASSERT_TRUE(res);
  3371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3372. }
  3373. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3374. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3375. ASSERT_TRUE(res);
  3376. EXPECT_EQ("HTTP/1.1", res->version);
  3377. EXPECT_EQ(StatusCode::OK_200, res->status);
  3378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3380. EXPECT_EQ("Hello World!", res->body);
  3381. }
  3382. TEST_F(ServerTest, GetMethod302) {
  3383. auto res = cli_.Get("/");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(StatusCode::Found_302, res->status);
  3386. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3387. }
  3388. TEST_F(ServerTest, GetMethod302Redirect) {
  3389. cli_.set_follow_location(true);
  3390. auto res = cli_.Get("/");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::OK_200, res->status);
  3393. EXPECT_EQ("Hello World!", res->body);
  3394. EXPECT_EQ("/hi", res->location);
  3395. }
  3396. TEST_F(ServerTest, GetMethod404) {
  3397. auto res = cli_.Get("/invalid");
  3398. ASSERT_TRUE(res);
  3399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3400. }
  3401. TEST_F(ServerTest, HeadMethod200) {
  3402. auto res = cli_.Head("/hi");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. EXPECT_TRUE(res->body.empty());
  3407. }
  3408. TEST_F(ServerTest, HeadMethod200Static) {
  3409. auto res = cli_.Head("/mount/dir/index.html");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(StatusCode::OK_200, res->status);
  3412. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3413. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3414. EXPECT_TRUE(res->body.empty());
  3415. }
  3416. TEST_F(ServerTest, HeadMethod404) {
  3417. auto res = cli_.Head("/invalid");
  3418. ASSERT_TRUE(res);
  3419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3420. EXPECT_TRUE(res->body.empty());
  3421. }
  3422. TEST_F(ServerTest, GetMethodPersonJohn) {
  3423. auto res = cli_.Get("/person/john");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3427. EXPECT_EQ("programmer", res->body);
  3428. }
  3429. TEST_F(ServerTest, PostMethod1) {
  3430. auto res = cli_.Get("/person/john1");
  3431. ASSERT_TRUE(res);
  3432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3433. res = cli_.Post("/person", "name=john1&note=coder",
  3434. "application/x-www-form-urlencoded");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::OK_200, res->status);
  3437. res = cli_.Get("/person/john1");
  3438. ASSERT_TRUE(res);
  3439. ASSERT_EQ(StatusCode::OK_200, res->status);
  3440. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3441. ASSERT_EQ("coder", res->body);
  3442. }
  3443. TEST_F(ServerTest, PostMethod2) {
  3444. auto res = cli_.Get("/person/john2");
  3445. ASSERT_TRUE(res);
  3446. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3447. Params params;
  3448. params.emplace("name", "john2");
  3449. params.emplace("note", "coder");
  3450. res = cli_.Post("/person", params);
  3451. ASSERT_TRUE(res);
  3452. ASSERT_EQ(StatusCode::OK_200, res->status);
  3453. res = cli_.Get("/person/john2");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3457. ASSERT_EQ("coder", res->body);
  3458. }
  3459. TEST_F(ServerTest, PutMethod3) {
  3460. auto res = cli_.Get("/person/john3");
  3461. ASSERT_TRUE(res);
  3462. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3463. Params params;
  3464. params.emplace("name", "john3");
  3465. params.emplace("note", "coder");
  3466. res = cli_.Put("/person", params);
  3467. ASSERT_TRUE(res);
  3468. ASSERT_EQ(StatusCode::OK_200, res->status);
  3469. res = cli_.Get("/person/john3");
  3470. ASSERT_TRUE(res);
  3471. ASSERT_EQ(StatusCode::OK_200, res->status);
  3472. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3473. ASSERT_EQ("coder", res->body);
  3474. }
  3475. TEST_F(ServerTest, DeleteMethod1) {
  3476. auto res = cli_.Get("/person/john4");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3479. Params params;
  3480. params.emplace("name", "john4");
  3481. params.emplace("note", "coder");
  3482. res = cli_.Post("/person", params);
  3483. ASSERT_TRUE(res);
  3484. ASSERT_EQ(StatusCode::OK_200, res->status);
  3485. res = cli_.Get("/person/john4");
  3486. ASSERT_TRUE(res);
  3487. ASSERT_EQ(StatusCode::OK_200, res->status);
  3488. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3489. ASSERT_EQ("coder", res->body);
  3490. Params delete_params;
  3491. delete_params.emplace("name", "john4");
  3492. res = cli_.Delete("/person", delete_params);
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ("DELETED", res->body);
  3496. res = cli_.Get("/person/john4");
  3497. ASSERT_TRUE(res);
  3498. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3499. }
  3500. TEST_F(ServerTest, DeleteMethod2) {
  3501. auto res = cli_.Get("/person/john5");
  3502. ASSERT_TRUE(res);
  3503. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3504. Params params;
  3505. params.emplace("name", "john5");
  3506. params.emplace("note", "developer");
  3507. res = cli_.Post("/person", params);
  3508. ASSERT_TRUE(res);
  3509. ASSERT_EQ(StatusCode::OK_200, res->status);
  3510. res = cli_.Get("/person/john5");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::OK_200, res->status);
  3513. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3514. ASSERT_EQ("developer", res->body);
  3515. Params delete_params;
  3516. delete_params.emplace("name", "john5");
  3517. Headers headers;
  3518. headers.emplace("Custom-Header", "test-value");
  3519. res = cli_.Delete("/person", headers, delete_params);
  3520. ASSERT_TRUE(res);
  3521. ASSERT_EQ(StatusCode::OK_200, res->status);
  3522. ASSERT_EQ("DELETED", res->body);
  3523. res = cli_.Get("/person/john5");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3526. }
  3527. TEST_F(ServerTest, DeleteMethod3) {
  3528. auto res = cli_.Get("/person/john6");
  3529. ASSERT_TRUE(res);
  3530. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3531. Params params;
  3532. params.emplace("name", "john6");
  3533. params.emplace("note", "tester");
  3534. res = cli_.Post("/person", params);
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::OK_200, res->status);
  3537. res = cli_.Get("/person/john6");
  3538. ASSERT_TRUE(res);
  3539. ASSERT_EQ(StatusCode::OK_200, res->status);
  3540. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3541. ASSERT_EQ("tester", res->body);
  3542. Params delete_params;
  3543. delete_params.emplace("name", "john6");
  3544. Headers headers;
  3545. headers.emplace("Custom-Header", "test-value");
  3546. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::OK_200, res->status);
  3549. ASSERT_EQ("DELETED", res->body);
  3550. res = cli_.Get("/person/john6");
  3551. ASSERT_TRUE(res);
  3552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3553. }
  3554. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3555. Params params;
  3556. params.emplace("json", JSON_DATA);
  3557. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ(JSON_DATA, res->body);
  3561. }
  3562. TEST_F(ServerTest, PostEmptyContent) {
  3563. auto res = cli_.Post("/empty", "", "text/plain");
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. ASSERT_EQ("empty", res->body);
  3567. }
  3568. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3569. auto res = cli_.Post("/empty-no-content-type");
  3570. ASSERT_TRUE(res);
  3571. ASSERT_EQ(StatusCode::OK_200, res->status);
  3572. ASSERT_EQ("empty-no-content-type", res->body);
  3573. }
  3574. TEST_F(ServerTest, PostPathOnly) {
  3575. auto res = cli_.Post("/path-only");
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ("path-only", res->body);
  3579. }
  3580. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3581. auto res = cli_.Post("/path-headers-only",
  3582. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(StatusCode::OK_200, res->status);
  3585. ASSERT_EQ("path-headers-only", res->body);
  3586. }
  3587. TEST_F(ServerTest, PostLarge) {
  3588. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3589. ASSERT_TRUE(res);
  3590. ASSERT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ(LARGE_DATA, res->body);
  3592. }
  3593. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3594. auto res = cli_.Put("/empty-no-content-type");
  3595. ASSERT_TRUE(res);
  3596. ASSERT_EQ(StatusCode::OK_200, res->status);
  3597. ASSERT_EQ("empty-no-content-type", res->body);
  3598. }
  3599. TEST_F(ServerTest, GetMethodDir) {
  3600. auto res = cli_.Get("/dir/");
  3601. ASSERT_TRUE(res);
  3602. EXPECT_EQ(StatusCode::OK_200, res->status);
  3603. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3604. auto body = R"(<html>
  3605. <head>
  3606. </head>
  3607. <body>
  3608. <a href="/dir/test.html">Test</a>
  3609. <a href="/hi">hi</a>
  3610. </body>
  3611. </html>
  3612. )";
  3613. EXPECT_EQ(body, res->body);
  3614. }
  3615. TEST_F(ServerTest, GetMethodDirTest) {
  3616. auto res = cli_.Get("/dir/test.html");
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("test.html", res->body);
  3621. }
  3622. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3623. auto res = cli_.Get("/dir/../dir/test.html");
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(StatusCode::OK_200, res->status);
  3626. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3627. EXPECT_EQ("test.html", res->body);
  3628. }
  3629. TEST_F(ServerTest, GetMethodInvalidPath) {
  3630. auto res = cli_.Get("/dir/../test.html");
  3631. ASSERT_TRUE(res);
  3632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3633. }
  3634. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3635. auto res = cli_.Get("/../www/dir/test.html");
  3636. ASSERT_TRUE(res);
  3637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3638. }
  3639. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3640. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3643. }
  3644. TEST_F(ServerTest, GetMethodDirMountTest) {
  3645. auto res = cli_.Get("/mount/dir/test.html");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("test.html", res->body);
  3650. }
  3651. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3652. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3656. EXPECT_EQ("test.html", res->body);
  3657. }
  3658. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3659. auto res = cli_.Get("/mount/dir/../test.html");
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3662. }
  3663. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3664. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3665. ASSERT_TRUE(res);
  3666. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3667. }
  3668. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3669. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3672. }
  3673. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3674. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3677. }
  3678. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3679. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3682. }
  3683. TEST_F(ServerTest, PostMethod303) {
  3684. auto res = cli_.Post("/1", "body", "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3687. EXPECT_EQ("/2", res->get_header_value("Location"));
  3688. }
  3689. TEST_F(ServerTest, PostMethod303Redirect) {
  3690. cli_.set_follow_location(true);
  3691. auto res = cli_.Post("/1", "body", "text/plain");
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("redirected.", res->body);
  3695. EXPECT_EQ("/2", res->location);
  3696. }
  3697. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3698. auto res = cli_.Get("/dir/test.abcde");
  3699. ASSERT_TRUE(res);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3702. EXPECT_EQ("abcde", res->body);
  3703. }
  3704. TEST_F(ServerTest, StaticFileRange) {
  3705. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3706. ASSERT_TRUE(res);
  3707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3708. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3709. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ(true, res->has_header("Content-Range"));
  3711. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3712. EXPECT_EQ(std::string("cd"), res->body);
  3713. }
  3714. TEST_F(ServerTest, StaticFileRanges) {
  3715. auto res =
  3716. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3719. EXPECT_TRUE(
  3720. res->get_header_value("Content-Type")
  3721. .find(
  3722. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3723. 0);
  3724. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3725. }
  3726. TEST_F(ServerTest, StaticFileRangeHead) {
  3727. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3730. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3731. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3732. EXPECT_EQ(true, res->has_header("Content-Range"));
  3733. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3734. }
  3735. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3736. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3740. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3741. EXPECT_EQ(true, res->has_header("Content-Range"));
  3742. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3743. res->get_header_value("Content-Range"));
  3744. EXPECT_EQ("LAST\n", res->body);
  3745. }
  3746. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3747. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3751. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3752. EXPECT_EQ(true, res->has_header("Content-Range"));
  3753. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3754. }
  3755. TEST_F(ServerTest, StaticFileBigFile) {
  3756. auto res = cli_.Get("/dir/1MB.txt");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3761. }
  3762. TEST_F(ServerTest, InvalidBaseDirMount) {
  3763. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3764. }
  3765. TEST_F(ServerTest, Binary) {
  3766. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3767. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3768. "application/octet-stream");
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ(4U, res->body.size());
  3772. res = cli_.Put("/binary", binary.data(), binary.size(),
  3773. "application/octet-stream");
  3774. ASSERT_TRUE(res);
  3775. ASSERT_EQ(StatusCode::OK_200, res->status);
  3776. ASSERT_EQ(4U, res->body.size());
  3777. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3778. "application/octet-stream");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(StatusCode::OK_200, res->status);
  3781. ASSERT_EQ(4U, res->body.size());
  3782. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3783. "application/octet-stream");
  3784. ASSERT_TRUE(res);
  3785. ASSERT_EQ(StatusCode::OK_200, res->status);
  3786. ASSERT_EQ(4U, res->body.size());
  3787. }
  3788. TEST_F(ServerTest, BinaryString) {
  3789. auto binary = std::string("\x00\x01\x02\x03", 4);
  3790. auto res = cli_.Post("/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_.Put("/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. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3799. ASSERT_TRUE(res);
  3800. ASSERT_EQ(StatusCode::OK_200, res->status);
  3801. ASSERT_EQ(4U, res->body.size());
  3802. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3803. ASSERT_TRUE(res);
  3804. ASSERT_EQ(StatusCode::OK_200, res->status);
  3805. ASSERT_EQ(4U, res->body.size());
  3806. }
  3807. TEST_F(ServerTest, EmptyRequest) {
  3808. auto res = cli_.Get("");
  3809. ASSERT_TRUE(!res);
  3810. EXPECT_EQ(Error::Connection, res.error());
  3811. }
  3812. TEST_F(ServerTest, LongRequest) {
  3813. std::string request;
  3814. for (size_t i = 0; i < 545; i++) {
  3815. request += "/TooLongRequest";
  3816. }
  3817. request += "OK";
  3818. auto res = cli_.Get(request.c_str());
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, TooLongRequest) {
  3823. std::string request;
  3824. for (size_t i = 0; i < 546; i++) {
  3825. request += "/TooLongRequest";
  3826. }
  3827. request += "_NG";
  3828. auto start = std::chrono::high_resolution_clock::now();
  3829. cli_.set_keep_alive(true);
  3830. auto res = cli_.Get(request.c_str());
  3831. auto end = std::chrono::high_resolution_clock::now();
  3832. auto elapsed =
  3833. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3834. .count();
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3837. EXPECT_LE(elapsed, 1000);
  3838. EXPECT_EQ("close", res->get_header_value("Connection"));
  3839. EXPECT_FALSE(cli_.is_socket_open());
  3840. }
  3841. TEST_F(ServerTest, AlmostTooLongRequest) {
  3842. // test for #2046 - URI length check shouldn't include other content on req
  3843. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3844. // leading /, space, HTTP/1.1)
  3845. std::string request =
  3846. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3847. auto res = cli_.Get(request.c_str());
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3850. }
  3851. TEST_F(ServerTest, LongHeader) {
  3852. Request req;
  3853. req.method = "GET";
  3854. req.path = "/hi";
  3855. std::string host_and_port;
  3856. host_and_port += HOST;
  3857. host_and_port += ":";
  3858. host_and_port += std::to_string(PORT);
  3859. req.headers.emplace("Host", host_and_port.c_str());
  3860. req.headers.emplace("Accept", "*/*");
  3861. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3862. req.headers.emplace(
  3863. "Header-Name",
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3892. "@@@@@@@@@@@@@@@@");
  3893. auto res = std::make_shared<Response>();
  3894. auto error = Error::Success;
  3895. auto ret = cli_.send(req, *res, error);
  3896. ASSERT_TRUE(ret);
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. }
  3899. TEST_F(ServerTest, LongQueryValue) {
  3900. auto start = std::chrono::high_resolution_clock::now();
  3901. cli_.set_keep_alive(true);
  3902. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3903. auto end = std::chrono::high_resolution_clock::now();
  3904. auto elapsed =
  3905. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3906. .count();
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3909. EXPECT_LE(elapsed, 1000);
  3910. EXPECT_EQ("close", res->get_header_value("Connection"));
  3911. EXPECT_FALSE(cli_.is_socket_open());
  3912. }
  3913. TEST_F(ServerTest, TooLongQueryValue) {
  3914. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3915. ASSERT_FALSE(res);
  3916. EXPECT_EQ(Error::Read, res.error());
  3917. }
  3918. TEST_F(ServerTest, TooLongHeader) {
  3919. Request req;
  3920. req.method = "GET";
  3921. req.path = "/hi";
  3922. std::string host_and_port;
  3923. host_and_port += HOST;
  3924. host_and_port += ":";
  3925. host_and_port += std::to_string(PORT);
  3926. req.headers.emplace("Host", host_and_port.c_str());
  3927. req.headers.emplace("Accept", "*/*");
  3928. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3929. req.headers.emplace(
  3930. "Header-Name",
  3931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3959. "@@@@@@@@@@@@@@@@@");
  3960. auto res = std::make_shared<Response>();
  3961. auto error = Error::Success;
  3962. auto ret = cli_.send(req, *res, error);
  3963. ASSERT_TRUE(ret);
  3964. EXPECT_EQ(StatusCode::OK_200, res->status);
  3965. }
  3966. TEST_F(ServerTest, HeaderCountAtLimit) {
  3967. // Test with headers just under the 100 limit
  3968. httplib::Headers headers;
  3969. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3970. // This should keep us just under the 100 header limit
  3971. for (int i = 0; i < 95; i++) {
  3972. std::string name = "X-Test-Header-" + std::to_string(i);
  3973. std::string value = "value" + std::to_string(i);
  3974. headers.emplace(name, value);
  3975. }
  3976. // This should work fine as we're under the limit
  3977. auto res = cli_.Get("/hi", headers);
  3978. EXPECT_TRUE(res);
  3979. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3980. }
  3981. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3982. // Test with many headers to exceed the 100 limit
  3983. httplib::Headers headers;
  3984. // Add 150 headers to definitely exceed the 100 limit
  3985. for (int i = 0; i < 150; i++) {
  3986. std::string name = "X-Test-Header-" + std::to_string(i);
  3987. std::string value = "value" + std::to_string(i);
  3988. headers.emplace(name, value);
  3989. }
  3990. // This should fail due to exceeding header count limit
  3991. cli_.set_keep_alive(true);
  3992. auto res = cli_.Get("/hi", headers);
  3993. // The server should respond with 400 Bad Request
  3994. ASSERT_TRUE(res);
  3995. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3996. EXPECT_EQ("close", res->get_header_value("Connection"));
  3997. EXPECT_FALSE(cli_.is_socket_open());
  3998. }
  3999. TEST_F(ServerTest, PercentEncoding) {
  4000. auto res = cli_.Get("/e%6edwith%");
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::OK_200, res->status);
  4003. }
  4004. TEST_F(ServerTest, PercentEncodingUnicode) {
  4005. auto res = cli_.Get("/e%u006edwith%");
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::OK_200, res->status);
  4008. }
  4009. TEST_F(ServerTest, InvalidPercentEncoding) {
  4010. auto res = cli_.Get("/%endwith%");
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4013. }
  4014. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4015. auto res = cli_.Get("/%uendwith%");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4018. }
  4019. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4020. auto res = cli_.Get("/hello?aaa=bbb%");
  4021. ASSERT_TRUE(res);
  4022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4023. }
  4024. TEST_F(ServerTest, PlusSignEncoding) {
  4025. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::OK_200, res->status);
  4028. EXPECT_EQ("a +b", res->body);
  4029. }
  4030. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4031. // This test simulates a potential DoS attack using many headers
  4032. // to verify our security fix prevents memory exhaustion
  4033. httplib::Headers attack_headers;
  4034. // Attempt to add many headers like an attacker would (200 headers to far
  4035. // exceed limit)
  4036. for (int i = 0; i < 200; i++) {
  4037. std::string name = "X-Attack-Header-" + std::to_string(i);
  4038. std::string value = "attack_payload_" + std::to_string(i);
  4039. attack_headers.emplace(name, value);
  4040. }
  4041. // Try to POST with excessive headers
  4042. cli_.set_keep_alive(true);
  4043. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4044. // Should either fail or return 400 Bad Request due to security limit
  4045. if (res) {
  4046. // If we get a response, it should be 400 Bad Request
  4047. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4048. EXPECT_EQ("close", res->get_header_value("Connection"));
  4049. }
  4050. EXPECT_FALSE(cli_.is_socket_open());
  4051. }
  4052. TEST_F(ServerTest, MultipartFormData) {
  4053. UploadFormDataItems items = {
  4054. {"text1", "text default", "", ""},
  4055. {"text2", "aωb", "", ""},
  4056. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4057. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4058. {"file3", "", "", "application/octet-stream"},
  4059. {"file4", "", "", " application/json tmp-string "}};
  4060. auto res = cli_.Post("/multipart", items);
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::OK_200, res->status);
  4063. }
  4064. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4065. UploadFormDataItems items = {
  4066. {"text", "default text", "", ""},
  4067. {"multi_text1", "aaaaa", "", ""},
  4068. {"multi_text1", "bbbbb", "", ""},
  4069. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4070. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4071. "application/json"},
  4072. };
  4073. auto res = cli_.Post("/multipart/multi_file_values", items);
  4074. ASSERT_TRUE(res);
  4075. EXPECT_EQ(StatusCode::OK_200, res->status);
  4076. }
  4077. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4078. auto res = cli_.Get("/hi");
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4082. EXPECT_EQ("Hello World!", res->body);
  4083. }
  4084. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4085. Request req;
  4086. req.method = "POST";
  4087. req.path = "/chunked";
  4088. std::string host_and_port;
  4089. host_and_port += HOST;
  4090. host_and_port += ":";
  4091. host_and_port += std::to_string(PORT);
  4092. req.headers.emplace("Host", host_and_port.c_str());
  4093. req.headers.emplace("Accept", "*/*");
  4094. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4095. req.headers.emplace("Content-Type", "text/plain");
  4096. req.headers.emplace("Content-Length", "0");
  4097. req.headers.emplace(
  4098. "Transfer-Encoding",
  4099. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4100. // Client does not chunk, so make a chunked body manually.
  4101. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4102. auto res = std::make_shared<Response>();
  4103. auto error = Error::Success;
  4104. auto ret = cli_.send(req, *res, error);
  4105. ASSERT_TRUE(ret);
  4106. EXPECT_EQ(StatusCode::OK_200, res->status);
  4107. }
  4108. TEST_F(ServerTest, GetStreamed2) {
  4109. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4112. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4113. EXPECT_EQ(true, res->has_header("Content-Range"));
  4114. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4115. EXPECT_EQ(std::string("ab"), res->body);
  4116. }
  4117. TEST_F(ServerTest, GetStreamed) {
  4118. auto res = cli_.Get("/streamed");
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::OK_200, res->status);
  4121. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4122. EXPECT_EQ(std::string("aaabbb"), res->body);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithRange1) {
  4125. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4126. ASSERT_TRUE(res);
  4127. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4128. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4129. EXPECT_EQ(true, res->has_header("Content-Range"));
  4130. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4131. EXPECT_EQ(std::string("def"), res->body);
  4132. }
  4133. TEST_F(ServerTest, GetStreamedWithRange2) {
  4134. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4137. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ(true, res->has_header("Content-Range"));
  4139. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4140. EXPECT_EQ(std::string("bcdefg"), res->body);
  4141. }
  4142. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4143. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4146. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4147. EXPECT_EQ(true, res->has_header("Content-Range"));
  4148. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4149. EXPECT_EQ(std::string("efg"), res->body);
  4150. }
  4151. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4152. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ(false, res->has_header("Content-Range"));
  4157. EXPECT_EQ(0U, res->body.size());
  4158. }
  4159. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4160. auto res = cli_.Get("/streamed-with-range",
  4161. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4162. "92233720368547758079223372036854775807"}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4166. EXPECT_EQ(false, res->has_header("Content-Range"));
  4167. EXPECT_EQ(0U, res->body.size());
  4168. }
  4169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4170. auto res = cli_.Get(
  4171. "/with-range",
  4172. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4173. {"Accept-Encoding", ""}});
  4174. ASSERT_TRUE(res);
  4175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4176. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ(true, res->has_header("Content-Range"));
  4178. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4179. EXPECT_EQ(std::string("abcdefg"), res->body);
  4180. }
  4181. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4182. auto res = cli_.Get("/with-range", {
  4183. {"Range", "bytes=0-"},
  4184. {"Accept-Encoding", ""},
  4185. });
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4188. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4189. EXPECT_EQ(true, res->has_header("Content-Range"));
  4190. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4191. EXPECT_EQ(std::string("abcdefg"), res->body);
  4192. }
  4193. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4194. auto res =
  4195. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4196. ASSERT_TRUE(res);
  4197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4198. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4199. EXPECT_EQ(false, res->has_header("Content-Range"));
  4200. EXPECT_EQ(267U, res->body.size());
  4201. // Check that both range contents are present
  4202. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4203. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4204. // Check that Content-Range headers are present for both ranges
  4205. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4206. std::string::npos);
  4207. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4208. std::string::npos);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4211. Ranges ranges;
  4212. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4213. ranges.emplace_back(0, -1);
  4214. }
  4215. auto res =
  4216. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4219. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4220. EXPECT_EQ(false, res->has_header("Content-Range"));
  4221. EXPECT_EQ(0U, res->body.size());
  4222. }
  4223. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4224. auto res =
  4225. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4228. EXPECT_EQ(5U, res->body.size());
  4229. // Check that overlapping ranges are coalesced into a single range
  4230. EXPECT_EQ("bcdef", res->body);
  4231. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4232. // Should be single range, not multipart
  4233. EXPECT_TRUE(res->has_header("Content-Range"));
  4234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4235. }
  4236. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4237. auto res =
  4238. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ(268U, res->body.size());
  4242. // Check that both range contents are present
  4243. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4244. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4245. // Check that Content-Range headers are present for both ranges
  4246. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4247. std::string::npos);
  4248. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4249. std::string::npos);
  4250. }
  4251. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4252. auto res =
  4253. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4256. EXPECT_EQ(269U, res->body.size());
  4257. // Check that both duplicate range contents are present
  4258. size_t first_abc = res->body.find("abc\r\n");
  4259. EXPECT_TRUE(first_abc != std::string::npos);
  4260. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4261. EXPECT_TRUE(second_abc != std::string::npos);
  4262. // Check that Content-Range headers are present for both ranges
  4263. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4264. EXPECT_TRUE(first_range != std::string::npos);
  4265. size_t second_range =
  4266. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4267. EXPECT_TRUE(second_range != std::string::npos);
  4268. }
  4269. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4270. auto res = cli_.Get("/streamed-with-range?error",
  4271. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4274. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4275. EXPECT_EQ(false, res->has_header("Content-Range"));
  4276. EXPECT_EQ(0U, res->body.size());
  4277. }
  4278. TEST_F(ServerTest, GetStreamedEndless) {
  4279. uint64_t offset = 0;
  4280. auto res = cli_.Get("/streamed-cancel",
  4281. [&](const char * /*data*/, uint64_t data_length) {
  4282. if (offset < 100) {
  4283. offset += data_length;
  4284. return true;
  4285. }
  4286. return false;
  4287. });
  4288. ASSERT_TRUE(!res);
  4289. EXPECT_EQ(Error::Canceled, res.error());
  4290. }
  4291. TEST_F(ServerTest, ClientStop) {
  4292. std::atomic_size_t count{4};
  4293. std::vector<std::thread> threads;
  4294. for (auto i = count.load(); i != 0; --i) {
  4295. threads.emplace_back([&]() {
  4296. auto res = cli_.Get("/streamed-cancel",
  4297. [&](const char *, uint64_t) { return true; });
  4298. --count;
  4299. ASSERT_TRUE(!res);
  4300. EXPECT_TRUE(res.error() == Error::Canceled ||
  4301. res.error() == Error::Read || res.error() == Error::Write);
  4302. });
  4303. }
  4304. std::this_thread::sleep_for(std::chrono::seconds(2));
  4305. while (count != 0) {
  4306. cli_.stop();
  4307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4308. }
  4309. for (auto &t : threads) {
  4310. t.join();
  4311. }
  4312. }
  4313. TEST_F(ServerTest, GetWithRange1) {
  4314. auto res = cli_.Get("/with-range", {
  4315. make_range_header({{3, 5}}),
  4316. {"Accept-Encoding", ""},
  4317. });
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4320. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4321. EXPECT_EQ(true, res->has_header("Content-Range"));
  4322. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4323. EXPECT_EQ(std::string("def"), res->body);
  4324. }
  4325. TEST_F(ServerTest, GetWithRange2) {
  4326. auto res = cli_.Get("/with-range", {
  4327. make_range_header({{1, -1}}),
  4328. {"Accept-Encoding", ""},
  4329. });
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4332. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4333. EXPECT_EQ(true, res->has_header("Content-Range"));
  4334. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4335. EXPECT_EQ(std::string("bcdefg"), res->body);
  4336. }
  4337. TEST_F(ServerTest, GetWithRange3) {
  4338. auto res = cli_.Get("/with-range", {
  4339. make_range_header({{0, 0}}),
  4340. {"Accept-Encoding", ""},
  4341. });
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4344. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4345. EXPECT_EQ(true, res->has_header("Content-Range"));
  4346. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4347. EXPECT_EQ(std::string("a"), res->body);
  4348. }
  4349. TEST_F(ServerTest, GetWithRange4) {
  4350. auto res = cli_.Get("/with-range", {
  4351. make_range_header({{-1, 2}}),
  4352. {"Accept-Encoding", ""},
  4353. });
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4356. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4357. EXPECT_EQ(true, res->has_header("Content-Range"));
  4358. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4359. EXPECT_EQ(std::string("fg"), res->body);
  4360. }
  4361. TEST_F(ServerTest, GetWithRange5) {
  4362. auto res = cli_.Get("/with-range", {
  4363. make_range_header({{0, 5}}),
  4364. {"Accept-Encoding", ""},
  4365. });
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4368. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4371. EXPECT_EQ(std::string("abcdef"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4374. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4377. }
  4378. TEST_F(ServerTest, GetWithRangeMultipart) {
  4379. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4382. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4383. EXPECT_EQ(false, res->has_header("Content-Range"));
  4384. EXPECT_EQ(267U, res->body.size());
  4385. }
  4386. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4387. auto res =
  4388. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4391. }
  4392. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4393. auto res = cli_.Get("/with-range-customized-response",
  4394. {{make_range_header({{1, 2}})}});
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4397. EXPECT_EQ(true, res->has_header("Content-Length"));
  4398. EXPECT_EQ(false, res->has_header("Content-Range"));
  4399. EXPECT_EQ(JSON_DATA, res->body);
  4400. }
  4401. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4402. auto res = cli_.Get("/with-range-customized-response",
  4403. {{make_range_header({{1, 2}, {4, 5}})}});
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4406. EXPECT_EQ(true, res->has_header("Content-Length"));
  4407. EXPECT_EQ(false, res->has_header("Content-Range"));
  4408. EXPECT_EQ(JSON_DATA, res->body);
  4409. }
  4410. TEST_F(ServerTest, Issue1772) {
  4411. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4414. }
  4415. TEST_F(ServerTest, Issue609) {
  4416. auto res = cli_.Delete("/issue609");
  4417. ASSERT_TRUE(res);
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. EXPECT_EQ(std::string("ok"), res->body);
  4420. }
  4421. TEST_F(ServerTest, GetStreamedChunked) {
  4422. auto res = cli_.Get("/streamed-chunked");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. EXPECT_EQ(std::string("123456789"), res->body);
  4426. }
  4427. TEST_F(ServerTest, GetStreamedChunked2) {
  4428. auto res = cli_.Get("/streamed-chunked2");
  4429. ASSERT_TRUE(res);
  4430. EXPECT_EQ(StatusCode::OK_200, res->status);
  4431. EXPECT_EQ(std::string("123456789"), res->body);
  4432. }
  4433. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4434. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. EXPECT_EQ(std::string("123456789"), res->body);
  4438. EXPECT_TRUE(res->has_header("Trailer"));
  4439. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4440. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4441. // Trailers are now stored separately from headers (security fix)
  4442. EXPECT_EQ(2U, res->trailers.size());
  4443. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4444. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4445. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4446. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4447. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4448. // Verify trailers are NOT in headers (security verification)
  4449. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4450. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4451. }
  4452. TEST_F(ServerTest, LargeChunkedPost) {
  4453. Request req;
  4454. req.method = "POST";
  4455. req.path = "/large-chunked";
  4456. std::string host_and_port;
  4457. host_and_port += HOST;
  4458. host_and_port += ":";
  4459. host_and_port += std::to_string(PORT);
  4460. req.headers.emplace("Host", host_and_port.c_str());
  4461. req.headers.emplace("Accept", "*/*");
  4462. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4463. req.headers.emplace("Content-Type", "text/plain");
  4464. req.headers.emplace("Content-Length", "0");
  4465. req.headers.emplace("Transfer-Encoding", "chunked");
  4466. std::string long_string(30 * 1024u, 'a');
  4467. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4468. // Attempt to make a large enough post to exceed OS buffers, to test that
  4469. // the server handles short reads if the full chunk data isn't available.
  4470. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4471. auto res = std::make_shared<Response>();
  4472. auto error = Error::Success;
  4473. auto ret = cli_.send(req, *res, error);
  4474. ASSERT_TRUE(ret);
  4475. EXPECT_EQ(StatusCode::OK_200, res->status);
  4476. }
  4477. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4478. auto res = cli_.Get("/remote_addr");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4482. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4483. }
  4484. TEST_F(ServerTest, GetMethodLocalAddr) {
  4485. auto res = cli_.Get("/local_addr");
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4489. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4490. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4491. }
  4492. TEST_F(ServerTest, HTTPResponseSplitting) {
  4493. auto res = cli_.Get("/http_response_splitting");
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. }
  4497. TEST_F(ServerTest, SlowRequest) {
  4498. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4499. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4500. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4501. }
  4502. #if 0
  4503. TEST_F(ServerTest, SlowPost) {
  4504. char buffer[64 * 1024];
  4505. memset(buffer, 0x42, sizeof(buffer));
  4506. auto res = cli_.Post(
  4507. "/slowpost", 64 * 1024 * 1024,
  4508. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4509. auto ret = sink.write(buffer, sizeof(buffer));
  4510. EXPECT_TRUE(ret);
  4511. return true;
  4512. },
  4513. "text/plain");
  4514. ASSERT_TRUE(res);
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. }
  4517. TEST_F(ServerTest, SlowPostFail) {
  4518. char buffer[64 * 1024];
  4519. memset(buffer, 0x42, sizeof(buffer));
  4520. cli_.set_write_timeout(std::chrono::seconds(0));
  4521. auto res = cli_.Post(
  4522. "/slowpost", 64 * 1024 * 1024,
  4523. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4524. sink.write(buffer, sizeof(buffer));
  4525. return true;
  4526. },
  4527. "text/plain");
  4528. ASSERT_TRUE(!res);
  4529. EXPECT_EQ(Error::Write, res.error());
  4530. }
  4531. #endif
  4532. TEST_F(ServerTest, Put) {
  4533. auto res = cli_.Put("/put", "PUT", "text/plain");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("PUT", res->body);
  4537. }
  4538. TEST_F(ServerTest, PutWithContentProvider) {
  4539. auto res = cli_.Put(
  4540. "/put", 3,
  4541. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4542. sink.os << "PUT";
  4543. return true;
  4544. },
  4545. "text/plain");
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("PUT", res->body);
  4549. }
  4550. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4551. auto res = cli_.Post(
  4552. "/post", 42,
  4553. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4554. return false;
  4555. },
  4556. "text/plain");
  4557. ASSERT_TRUE(!res);
  4558. EXPECT_EQ(Error::Canceled, res.error());
  4559. }
  4560. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4561. auto res = cli_.Put(
  4562. "/put",
  4563. [](size_t /*offset*/, DataSink &sink) {
  4564. sink.os << "PUT";
  4565. sink.done();
  4566. return true;
  4567. },
  4568. "text/plain");
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("PUT", res->body);
  4572. }
  4573. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4574. auto res = cli_.Post(
  4575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PostLoopBack) {
  4581. std::string body;
  4582. auto res = cli_.Post(
  4583. "/post-loopback", 9,
  4584. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4585. EXPECT_EQ(9u, length);
  4586. sink.write("123", 3);
  4587. sink.write("456", 3);
  4588. sink.write("789", 3);
  4589. return true;
  4590. },
  4591. "text/plain",
  4592. [&body](const char *data, size_t data_length) {
  4593. body.append(data, data_length);
  4594. return true;
  4595. });
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. EXPECT_EQ("123456789", body);
  4599. }
  4600. TEST_F(ServerTest, PutLoopBack) {
  4601. std::string body;
  4602. auto res = cli_.Put(
  4603. "/put-loopback", 9,
  4604. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4605. EXPECT_EQ(9u, length);
  4606. sink.write("123", 3);
  4607. sink.write("456", 3);
  4608. sink.write("789", 3);
  4609. return true;
  4610. },
  4611. "text/plain",
  4612. [&body](const char *data, size_t data_length) {
  4613. body.append(data, data_length);
  4614. return true;
  4615. });
  4616. ASSERT_TRUE(res);
  4617. EXPECT_EQ(StatusCode::OK_200, res->status);
  4618. EXPECT_EQ("123456789", body);
  4619. }
  4620. TEST_F(ServerTest, PatchLoopBack) {
  4621. std::string body;
  4622. auto res = cli_.Patch(
  4623. "/patch-loopback", 9,
  4624. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4625. EXPECT_EQ(9u, length);
  4626. sink.write("123", 3);
  4627. sink.write("456", 3);
  4628. sink.write("789", 3);
  4629. return true;
  4630. },
  4631. "text/plain",
  4632. [&body](const char *data, size_t data_length) {
  4633. body.append(data, data_length);
  4634. return true;
  4635. });
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("123456789", body);
  4639. }
  4640. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4641. std::string body;
  4642. auto res = cli_.Post(
  4643. "/post-loopback",
  4644. [](size_t /*offset*/, DataSink &sink) {
  4645. sink.write("123", 3);
  4646. sink.write("456", 3);
  4647. sink.write("789", 3);
  4648. sink.done();
  4649. return true;
  4650. },
  4651. "text/plain",
  4652. [&body](const char *data, size_t data_length) {
  4653. body.append(data, data_length);
  4654. return true;
  4655. });
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. EXPECT_EQ("123456789", body);
  4659. }
  4660. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4661. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4662. cli_.set_compress(true);
  4663. auto res = cli_.Put(
  4664. "/put", 3,
  4665. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4666. sink.os << "PUT";
  4667. return true;
  4668. },
  4669. "text/plain");
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("PUT", res->body);
  4673. }
  4674. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4675. cli_.set_compress(true);
  4676. auto res = cli_.Post(
  4677. "/post", 42,
  4678. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4679. return false;
  4680. },
  4681. "text/plain");
  4682. ASSERT_TRUE(!res);
  4683. EXPECT_EQ(Error::Canceled, res.error());
  4684. }
  4685. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4686. cli_.set_compress(true);
  4687. auto res = cli_.Put(
  4688. "/put",
  4689. [](size_t /*offset*/, DataSink &sink) {
  4690. sink.os << "PUT";
  4691. sink.done();
  4692. return true;
  4693. },
  4694. "text/plain");
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::OK_200, res->status);
  4697. EXPECT_EQ("PUT", res->body);
  4698. }
  4699. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4700. cli_.set_compress(true);
  4701. auto res = cli_.Post(
  4702. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4703. "text/plain");
  4704. ASSERT_TRUE(!res);
  4705. EXPECT_EQ(Error::Canceled, res.error());
  4706. }
  4707. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4708. cli_.set_compress(true);
  4709. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4710. ASSERT_TRUE(res);
  4711. EXPECT_EQ(StatusCode::OK_200, res->status);
  4712. EXPECT_EQ(LARGE_DATA, res->body);
  4713. }
  4714. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4715. #ifdef CPPHTTPLIB_SSL_ENABLED
  4716. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4717. Client cli(s.c_str());
  4718. cli.enable_server_certificate_verification(false);
  4719. #else
  4720. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4721. Client cli(s.c_str());
  4722. #endif
  4723. cli.set_compress(true);
  4724. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4725. ASSERT_TRUE(res);
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ(LARGE_DATA, res->body);
  4728. // The compressed size should be less than a 10th of the original. May vary
  4729. // depending on the zlib library.
  4730. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4731. static_cast<uint64_t>(10 * 1024 * 1024));
  4732. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4733. }
  4734. TEST_F(ServerTest, PutContentWithDeflate) {
  4735. cli_.set_compress(false);
  4736. Headers headers;
  4737. headers.emplace("Content-Encoding", "deflate");
  4738. // PUT in deflate format:
  4739. auto res = cli_.Put("/put", headers,
  4740. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("PUT", res->body);
  4744. }
  4745. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4746. Headers headers;
  4747. headers.emplace("Accept-Encoding", "gzip, deflate");
  4748. auto res = cli_.Get("/streamed-chunked", headers);
  4749. ASSERT_TRUE(res);
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. EXPECT_EQ(std::string("123456789"), res->body);
  4752. }
  4753. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4754. Headers headers;
  4755. headers.emplace("Accept-Encoding", "gzip, deflate");
  4756. auto res = cli_.Get("/streamed-chunked2", headers);
  4757. ASSERT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::OK_200, res->status);
  4759. EXPECT_EQ(std::string("123456789"), res->body);
  4760. }
  4761. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4762. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST(GzipDecompressor, ChunkedDecompression) {
  4767. std::string data;
  4768. for (size_t i = 0; i < 32 * 1024; ++i) {
  4769. data.push_back(static_cast<char>('a' + i % 26));
  4770. }
  4771. std::string compressed_data;
  4772. {
  4773. httplib::detail::gzip_compressor compressor;
  4774. bool result = compressor.compress(
  4775. data.data(), data.size(),
  4776. /*last=*/true,
  4777. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4778. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4779. compressed_data_size);
  4780. return true;
  4781. });
  4782. ASSERT_TRUE(result);
  4783. }
  4784. std::string decompressed_data;
  4785. {
  4786. httplib::detail::gzip_decompressor decompressor;
  4787. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4788. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4789. size_t chunk_size = 130;
  4790. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4791. chunk_begin += chunk_size) {
  4792. size_t current_chunk_size =
  4793. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4794. bool result = decompressor.decompress(
  4795. compressed_data.data() + chunk_begin, current_chunk_size,
  4796. [&](const char *decompressed_data_chunk,
  4797. size_t decompressed_data_chunk_size) {
  4798. decompressed_data.insert(decompressed_data.size(),
  4799. decompressed_data_chunk,
  4800. decompressed_data_chunk_size);
  4801. return true;
  4802. });
  4803. ASSERT_TRUE(result);
  4804. }
  4805. }
  4806. ASSERT_EQ(data, decompressed_data);
  4807. }
  4808. TEST(GzipDecompressor, DeflateDecompression) {
  4809. std::string original_text = "Raw deflate without gzip";
  4810. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4811. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4812. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4813. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4814. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4815. std::string decompressed_data;
  4816. {
  4817. httplib::detail::gzip_decompressor decompressor;
  4818. bool result = decompressor.decompress(
  4819. compressed_data.data(), compressed_data.size(),
  4820. [&](const char *decompressed_data_chunk,
  4821. size_t decompressed_data_chunk_size) {
  4822. decompressed_data.insert(decompressed_data.size(),
  4823. decompressed_data_chunk,
  4824. decompressed_data_chunk_size);
  4825. return true;
  4826. });
  4827. ASSERT_TRUE(result);
  4828. }
  4829. ASSERT_EQ(original_text, decompressed_data);
  4830. }
  4831. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4832. std::string original_text = "Raw deflate without gzip";
  4833. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4834. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4835. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4836. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4837. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4838. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4839. std::string decompressed_data;
  4840. {
  4841. httplib::detail::gzip_decompressor decompressor;
  4842. bool result = decompressor.decompress(
  4843. compressed_data.data(), compressed_data.size(),
  4844. [&](const char *decompressed_data_chunk,
  4845. size_t decompressed_data_chunk_size) {
  4846. decompressed_data.insert(decompressed_data.size(),
  4847. decompressed_data_chunk,
  4848. decompressed_data_chunk_size);
  4849. return true;
  4850. });
  4851. ASSERT_TRUE(result);
  4852. }
  4853. ASSERT_EQ(original_text, decompressed_data);
  4854. }
  4855. #ifdef _WIN32
  4856. TEST(GzipDecompressor, LargeRandomData) {
  4857. // prepare large random data that is difficult to be compressed and is
  4858. // expected to have large size even when compressed
  4859. std::random_device seed_gen;
  4860. std::mt19937 random(seed_gen());
  4861. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4862. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4863. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4864. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4865. // compress data over 4GiB
  4866. std::string compressed_data;
  4867. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4868. httplib::detail::gzip_compressor compressor;
  4869. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4870. data.size() * sizeof(std::uint32_t), true,
  4871. [&](const char *data, size_t size) {
  4872. compressed_data.insert(
  4873. compressed_data.size(), data, size);
  4874. return true;
  4875. });
  4876. ASSERT_TRUE(result);
  4877. // FIXME: compressed data size is expected to be greater than 4GiB,
  4878. // but there is no guarantee
  4879. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4880. // decompress data over 4GiB
  4881. std::string decompressed_data;
  4882. decompressed_data.reserve(data_size);
  4883. httplib::detail::gzip_decompressor decompressor;
  4884. result = decompressor.decompress(
  4885. compressed_data.data(), compressed_data.size(),
  4886. [&](const char *data, size_t size) {
  4887. decompressed_data.insert(decompressed_data.size(), data, size);
  4888. return true;
  4889. });
  4890. ASSERT_TRUE(result);
  4891. // compare
  4892. ASSERT_EQ(data_size, decompressed_data.size());
  4893. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4894. 0);
  4895. }
  4896. #endif
  4897. #endif
  4898. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4899. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4900. Headers headers;
  4901. headers.emplace("Accept-Encoding", "br");
  4902. auto res = cli_.Get("/streamed-chunked", headers);
  4903. ASSERT_TRUE(res);
  4904. EXPECT_EQ(StatusCode::OK_200, res->status);
  4905. EXPECT_EQ(std::string("123456789"), res->body);
  4906. }
  4907. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4908. Headers headers;
  4909. headers.emplace("Accept-Encoding", "br");
  4910. auto res = cli_.Get("/streamed-chunked2", headers);
  4911. ASSERT_TRUE(res);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. EXPECT_EQ(std::string("123456789"), res->body);
  4914. }
  4915. #endif
  4916. TEST_F(ServerTest, Patch) {
  4917. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4918. ASSERT_TRUE(res);
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ("PATCH", res->body);
  4921. }
  4922. TEST_F(ServerTest, Delete) {
  4923. auto res = cli_.Delete("/delete");
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::OK_200, res->status);
  4926. EXPECT_EQ("DELETE", res->body);
  4927. }
  4928. TEST_F(ServerTest, DeleteContentReceiver) {
  4929. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::OK_200, res->status);
  4932. EXPECT_EQ("content", res->body);
  4933. }
  4934. TEST_F(ServerTest, Options) {
  4935. auto res = cli_.Options("*");
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(StatusCode::OK_200, res->status);
  4938. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4939. EXPECT_TRUE(res->body.empty());
  4940. }
  4941. TEST_F(ServerTest, URL) {
  4942. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. }
  4946. TEST_F(ServerTest, ArrayParam) {
  4947. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. }
  4951. TEST_F(ServerTest, NoMultipleHeaders) {
  4952. Headers headers = {{"Content-Length", "5"}};
  4953. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4954. "text/plain");
  4955. ASSERT_TRUE(res);
  4956. EXPECT_EQ(StatusCode::OK_200, res->status);
  4957. }
  4958. TEST_F(ServerTest, PostContentReceiver) {
  4959. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4960. ASSERT_TRUE(res);
  4961. ASSERT_EQ(StatusCode::OK_200, res->status);
  4962. ASSERT_EQ("content", res->body);
  4963. }
  4964. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4965. UploadFormDataItems items = {
  4966. {"text1", "text default", "", ""},
  4967. {"text2", "aωb", "", ""},
  4968. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4969. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4970. {"file3", "", "", "application/octet-stream"},
  4971. };
  4972. auto res = cli_.Post("/content_receiver", items);
  4973. ASSERT_TRUE(res);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. }
  4976. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4977. UploadFormDataItems items = {
  4978. {"text1", "text default", "", ""},
  4979. {"text2", "aωb", "", ""},
  4980. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4981. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4982. {"file3", "", "", "application/octet-stream"},
  4983. };
  4984. auto boundary = std::string("+++++");
  4985. std::string body;
  4986. for (const auto &item : items) {
  4987. body += "--" + boundary + "\r\n";
  4988. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4989. if (!item.filename.empty()) {
  4990. body += "; filename=\"" + item.filename + "\"";
  4991. }
  4992. body += "\r\n";
  4993. if (!item.content_type.empty()) {
  4994. body += "Content-Type: " + item.content_type + "\r\n";
  4995. }
  4996. body += "\r\n";
  4997. body += item.content + "\r\n";
  4998. }
  4999. body += "--" + boundary + "--\r\n";
  5000. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5001. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5002. ASSERT_TRUE(res);
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. }
  5005. TEST_F(ServerTest, PostContentReceiverGzip) {
  5006. cli_.set_compress(true);
  5007. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5008. ASSERT_TRUE(res);
  5009. ASSERT_EQ(StatusCode::OK_200, res->status);
  5010. ASSERT_EQ("content", res->body);
  5011. }
  5012. TEST_F(ServerTest, PutContentReceiver) {
  5013. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5014. ASSERT_TRUE(res);
  5015. ASSERT_EQ(StatusCode::OK_200, res->status);
  5016. ASSERT_EQ("content", res->body);
  5017. }
  5018. TEST_F(ServerTest, PatchContentReceiver) {
  5019. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5020. ASSERT_TRUE(res);
  5021. ASSERT_EQ(StatusCode::OK_200, res->status);
  5022. ASSERT_EQ("content", res->body);
  5023. }
  5024. template <typename ClientType>
  5025. void TestWithHeadersAndContentReceiver(
  5026. ClientType &cli,
  5027. std::function<Result(ClientType &, const std::string &, const Headers &,
  5028. const std::string &, const std::string &,
  5029. ContentReceiver, DownloadProgress)>
  5030. request_func) {
  5031. Headers headers;
  5032. headers.emplace("X-Custom-Header", "test-value");
  5033. std::string received_body;
  5034. auto res = request_func(
  5035. cli, "/content_receiver", headers, "content", "application/json",
  5036. [&](const char *data, size_t data_length) {
  5037. received_body.append(data, data_length);
  5038. return true;
  5039. },
  5040. nullptr);
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. EXPECT_EQ("content", received_body);
  5044. }
  5045. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5046. #ifdef CPPHTTPLIB_SSL_ENABLED
  5047. using ClientT = SSLClient;
  5048. #else
  5049. using ClientT = Client;
  5050. #endif
  5051. TestWithHeadersAndContentReceiver<ClientT>(
  5052. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5053. const std::string &body, const std::string &content_type,
  5054. ContentReceiver receiver, DownloadProgress progress) {
  5055. return cli.Post(path, headers, body, content_type, receiver, progress);
  5056. });
  5057. }
  5058. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5059. #ifdef CPPHTTPLIB_SSL_ENABLED
  5060. using ClientT = SSLClient;
  5061. #else
  5062. using ClientT = Client;
  5063. #endif
  5064. TestWithHeadersAndContentReceiver<ClientT>(
  5065. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5066. const std::string &body, const std::string &content_type,
  5067. ContentReceiver receiver, DownloadProgress progress) {
  5068. return cli.Put(path, headers, body, content_type, receiver, progress);
  5069. });
  5070. }
  5071. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5072. #ifdef CPPHTTPLIB_SSL_ENABLED
  5073. using ClientT = SSLClient;
  5074. #else
  5075. using ClientT = Client;
  5076. #endif
  5077. TestWithHeadersAndContentReceiver<ClientT>(
  5078. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5079. const std::string &body, const std::string &content_type,
  5080. ContentReceiver receiver, DownloadProgress progress) {
  5081. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5082. });
  5083. }
  5084. template <typename ClientType>
  5085. void TestWithHeadersAndContentReceiverWithProgress(
  5086. ClientType &cli,
  5087. std::function<Result(ClientType &, const std::string &, const Headers &,
  5088. const std::string &, const std::string &,
  5089. ContentReceiver, DownloadProgress)>
  5090. request_func) {
  5091. Headers headers;
  5092. headers.emplace("X-Test-Header", "progress-test");
  5093. std::string received_body;
  5094. auto progress_called = false;
  5095. auto res = request_func(
  5096. cli, "/content_receiver", headers, "content", "text/plain",
  5097. [&](const char *data, size_t data_length) {
  5098. received_body.append(data, data_length);
  5099. return true;
  5100. },
  5101. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5102. progress_called = true;
  5103. return true;
  5104. });
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("content", received_body);
  5108. EXPECT_TRUE(progress_called);
  5109. }
  5110. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5111. #ifdef CPPHTTPLIB_SSL_ENABLED
  5112. using ClientT = SSLClient;
  5113. #else
  5114. using ClientT = Client;
  5115. #endif
  5116. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5117. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5118. const std::string &body, const std::string &content_type,
  5119. ContentReceiver receiver, DownloadProgress progress) {
  5120. return cli.Post(path, headers, body, content_type, receiver, progress);
  5121. });
  5122. }
  5123. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5124. #ifdef CPPHTTPLIB_SSL_ENABLED
  5125. using ClientT = SSLClient;
  5126. #else
  5127. using ClientT = Client;
  5128. #endif
  5129. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5131. const std::string &body, const std::string &content_type,
  5132. ContentReceiver receiver, DownloadProgress progress) {
  5133. return cli.Put(path, headers, body, content_type, receiver, progress);
  5134. });
  5135. }
  5136. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5137. #ifdef CPPHTTPLIB_SSL_ENABLED
  5138. using ClientT = SSLClient;
  5139. #else
  5140. using ClientT = Client;
  5141. #endif
  5142. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5144. const std::string &body, const std::string &content_type,
  5145. ContentReceiver receiver, DownloadProgress progress) {
  5146. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5147. });
  5148. }
  5149. template <typename ClientType>
  5150. void TestWithHeadersAndContentReceiverError(
  5151. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5152. const Headers &, const std::string &,
  5153. const std::string &, ContentReceiver)>
  5154. request_func) {
  5155. Headers headers;
  5156. headers.emplace("X-Error-Test", "true");
  5157. std::string received_body;
  5158. auto receiver_failed = false;
  5159. auto res =
  5160. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5161. [&](const char *data, size_t data_length) {
  5162. received_body.append(data, data_length);
  5163. receiver_failed = true;
  5164. return false;
  5165. });
  5166. ASSERT_FALSE(res);
  5167. EXPECT_TRUE(receiver_failed);
  5168. }
  5169. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5170. #ifdef CPPHTTPLIB_SSL_ENABLED
  5171. using ClientT = SSLClient;
  5172. #else
  5173. using ClientT = Client;
  5174. #endif
  5175. TestWithHeadersAndContentReceiverError<ClientT>(
  5176. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5177. const std::string &body, const std::string &content_type,
  5178. ContentReceiver receiver) {
  5179. return cli.Post(path, headers, body, content_type, receiver);
  5180. });
  5181. }
  5182. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5183. #ifdef CPPHTTPLIB_SSL_ENABLED
  5184. using ClientT = SSLClient;
  5185. #else
  5186. using ClientT = Client;
  5187. #endif
  5188. TestWithHeadersAndContentReceiverError<ClientT>(
  5189. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5190. const std::string &body, const std::string &content_type,
  5191. ContentReceiver receiver) {
  5192. return cli.Put(path, headers, body, content_type, receiver);
  5193. });
  5194. }
  5195. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5196. #ifdef CPPHTTPLIB_SSL_ENABLED
  5197. using ClientT = SSLClient;
  5198. #else
  5199. using ClientT = Client;
  5200. #endif
  5201. TestWithHeadersAndContentReceiverError<ClientT>(
  5202. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5203. const std::string &body, const std::string &content_type,
  5204. ContentReceiver receiver) {
  5205. return cli.Patch(path, headers, body, content_type, receiver);
  5206. });
  5207. }
  5208. TEST_F(ServerTest, PostQueryStringAndBody) {
  5209. auto res =
  5210. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5211. ASSERT_TRUE(res);
  5212. ASSERT_EQ(StatusCode::OK_200, res->status);
  5213. }
  5214. TEST_F(ServerTest, HTTP2Magic) {
  5215. Request req;
  5216. req.method = "PRI";
  5217. req.path = "*";
  5218. req.body = "SM";
  5219. auto res = std::make_shared<Response>();
  5220. auto error = Error::Success;
  5221. auto ret = cli_.send(req, *res, error);
  5222. ASSERT_TRUE(ret);
  5223. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5224. }
  5225. TEST_F(ServerTest, KeepAlive) {
  5226. auto 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("/hi");
  5237. ASSERT_TRUE(res);
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ("Hello World!", res->body);
  5241. res = cli_.Get("/not-exist");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5244. res = cli_.Post("/empty", "", "text/plain");
  5245. ASSERT_TRUE(res);
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("empty", res->body);
  5249. EXPECT_EQ("close", res->get_header_value("Connection"));
  5250. res = cli_.Post(
  5251. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5252. "text/plain");
  5253. ASSERT_TRUE(res);
  5254. EXPECT_EQ(StatusCode::OK_200, res->status);
  5255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5256. EXPECT_EQ("empty", res->body);
  5257. cli_.set_keep_alive(false);
  5258. res = cli_.Get("/last-request");
  5259. ASSERT_TRUE(res);
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("close", res->get_header_value("Connection"));
  5262. }
  5263. TEST_F(ServerTest, TooManyRedirect) {
  5264. cli_.set_follow_location(true);
  5265. auto res = cli_.Get("/redirect/0");
  5266. ASSERT_TRUE(!res);
  5267. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5268. }
  5269. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5270. Request req;
  5271. req.method = "FOOBAR";
  5272. req.path = "/hi";
  5273. cli_.set_keep_alive(true);
  5274. auto res = cli_.send(req);
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5277. EXPECT_EQ("close", res->get_header_value("Connection"));
  5278. EXPECT_FALSE(cli_.is_socket_open());
  5279. }
  5280. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5281. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5282. TEST_F(ServerTest, Gzip) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "gzip, deflate");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "gzip, deflate");
  5298. auto res = cli_.Get("/compress-with-charset", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5301. EXPECT_EQ("application/json; charset=utf-8",
  5302. res->get_header_value("Content-Type"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "");
  5311. auto res = cli_.Get("/compress", headers);
  5312. ASSERT_TRUE(res);
  5313. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5315. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5316. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5317. "7890123456789012345678901234567890",
  5318. res->body);
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. }
  5321. TEST_F(ServerTest, GzipWithContentReceiver) {
  5322. Headers headers;
  5323. headers.emplace("Accept-Encoding", "gzip, deflate");
  5324. std::string body;
  5325. auto res = cli_.Get("/compress", headers,
  5326. [&](const char *data, uint64_t data_length) {
  5327. EXPECT_EQ(100U, data_length);
  5328. body.append(data, data_length);
  5329. return true;
  5330. });
  5331. ASSERT_TRUE(res);
  5332. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5333. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5334. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5335. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5336. "7890123456789012345678901234567890",
  5337. body);
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. }
  5340. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5341. Headers headers;
  5342. headers.emplace("Accept-Encoding", "gzip, deflate");
  5343. cli_.set_decompress(false);
  5344. auto res = cli_.Get("/compress", headers);
  5345. ASSERT_TRUE(res);
  5346. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5348. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5349. EXPECT_EQ(33U, res->body.size());
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "");
  5355. std::string body;
  5356. auto res = cli_.Get("/compress", headers,
  5357. [&](const char *data, uint64_t data_length) {
  5358. EXPECT_EQ(100U, data_length);
  5359. body.append(data, data_length);
  5360. return true;
  5361. });
  5362. ASSERT_TRUE(res);
  5363. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5367. "7890123456789012345678901234567890",
  5368. body);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. }
  5371. TEST_F(ServerTest, NoGzip) {
  5372. Headers headers;
  5373. headers.emplace("Accept-Encoding", "gzip, deflate");
  5374. auto res = cli_.Get("/nocompress", headers);
  5375. ASSERT_TRUE(res);
  5376. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5377. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5378. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5379. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5380. "7890123456789012345678901234567890",
  5381. res->body);
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. }
  5384. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5385. Headers headers;
  5386. headers.emplace("Accept-Encoding", "gzip, deflate");
  5387. std::string body;
  5388. auto res = cli_.Get("/nocompress", headers,
  5389. [&](const char *data, uint64_t data_length) {
  5390. EXPECT_EQ(100U, data_length);
  5391. body.append(data, data_length);
  5392. return true;
  5393. });
  5394. ASSERT_TRUE(res);
  5395. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5396. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5397. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5398. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5399. "7890123456789012345678901234567890",
  5400. body);
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST_F(ServerTest, MultipartFormDataGzip) {
  5404. UploadFormDataItems items = {
  5405. {"key1", "test", "", ""},
  5406. {"key2", "--abcdefg123", "", ""},
  5407. };
  5408. cli_.set_compress(true);
  5409. auto res = cli_.Post("/compress-multipart", items);
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. }
  5413. #endif
  5414. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5415. TEST_F(ServerTest, Brotli) {
  5416. Headers headers;
  5417. headers.emplace("Accept-Encoding", "br");
  5418. auto res = cli_.Get("/compress", headers);
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5423. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5424. "7890123456789012345678901234567890",
  5425. res->body);
  5426. EXPECT_EQ(StatusCode::OK_200, res->status);
  5427. }
  5428. #endif
  5429. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5430. TEST_F(ServerTest, Zstd) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "zstd");
  5433. auto res = cli_.Get("/compress", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5438. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5439. "7890123456789012345678901234567890",
  5440. res->body);
  5441. EXPECT_EQ(StatusCode::OK_200, res->status);
  5442. }
  5443. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5444. Headers headers;
  5445. headers.emplace("Accept-Encoding", "");
  5446. auto res = cli_.Get("/compress", headers);
  5447. ASSERT_TRUE(res);
  5448. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5450. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5452. "7890123456789012345678901234567890",
  5453. res->body);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. }
  5456. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "zstd");
  5459. std::string body;
  5460. auto res = cli_.Get("/compress", headers,
  5461. [&](const char *data, uint64_t data_length) {
  5462. EXPECT_EQ(100U, data_length);
  5463. body.append(data, data_length);
  5464. return true;
  5465. });
  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("123456789012345678901234567890123456789012345678901234567890123456"
  5471. "7890123456789012345678901234567890",
  5472. body);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. }
  5475. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5476. Headers headers;
  5477. headers.emplace("Accept-Encoding", "zstd");
  5478. cli_.set_decompress(false);
  5479. auto res = cli_.Get("/compress", headers);
  5480. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5481. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5482. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5483. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ(26U, res->body.size());
  5490. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5491. 0);
  5492. }
  5493. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "");
  5496. std::string body;
  5497. auto res = cli_.Get("/compress", headers,
  5498. [&](const char *data, uint64_t data_length) {
  5499. EXPECT_EQ(100U, data_length);
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res);
  5504. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5508. "7890123456789012345678901234567890",
  5509. body);
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. }
  5512. TEST_F(ServerTest, NoZstd) {
  5513. Headers headers;
  5514. headers.emplace("Accept-Encoding", "zstd");
  5515. auto res = cli_.Get("/nocompress", headers);
  5516. ASSERT_TRUE(res);
  5517. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5518. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5521. "7890123456789012345678901234567890",
  5522. res->body);
  5523. EXPECT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5526. Headers headers;
  5527. headers.emplace("Accept-Encoding", "zstd");
  5528. std::string body;
  5529. auto res = cli_.Get("/nocompress", headers,
  5530. [&](const char *data, uint64_t data_length) {
  5531. EXPECT_EQ(100U, data_length);
  5532. body.append(data, data_length);
  5533. return true;
  5534. });
  5535. ASSERT_TRUE(res);
  5536. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5537. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5538. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5540. "7890123456789012345678901234567890",
  5541. body);
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. }
  5544. // TODO: How to enable zstd ??
  5545. TEST_F(ServerTest, MultipartFormDataZstd) {
  5546. UploadFormDataItems items = {
  5547. {"key1", "test", "", ""},
  5548. {"key2", "--abcdefg123", "", ""},
  5549. };
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "zstd");
  5552. cli_.set_compress(true);
  5553. auto res = cli_.Post("/compress-multipart", headers, items);
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. }
  5557. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5558. Headers headers;
  5559. headers.emplace("Accept-Encoding", "zstd");
  5560. cli_.set_compress(true);
  5561. auto res = cli_.Put(
  5562. "/put", headers, 3,
  5563. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5564. sink.os << "PUT";
  5565. return true;
  5566. },
  5567. "text/plain");
  5568. ASSERT_TRUE(res);
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. EXPECT_EQ("PUT", res->body);
  5571. }
  5572. // Pre-compression logging tests
  5573. TEST_F(ServerTest, PreCompressionLogging) {
  5574. // Test data for compression (matches the actual /compress endpoint content)
  5575. const std::string test_content =
  5576. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5577. "3456789012345678901234567890";
  5578. // Variables to capture logging data
  5579. std::string pre_compression_body;
  5580. std::string pre_compression_content_type;
  5581. std::string pre_compression_content_encoding;
  5582. std::string post_compression_body;
  5583. std::string post_compression_content_type;
  5584. std::string post_compression_content_encoding;
  5585. // Set up pre-compression logger
  5586. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5587. const Response &res) {
  5588. pre_compression_body = res.body;
  5589. pre_compression_content_type = res.get_header_value("Content-Type");
  5590. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5591. });
  5592. // Set up post-compression logger
  5593. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5594. post_compression_body = res.body;
  5595. post_compression_content_type = res.get_header_value("Content-Type");
  5596. post_compression_content_encoding =
  5597. res.get_header_value("Content-Encoding");
  5598. });
  5599. // Test with gzip compression
  5600. Headers headers;
  5601. headers.emplace("Accept-Encoding", "gzip");
  5602. auto res = cli_.Get("/compress", headers);
  5603. // Verify response was compressed
  5604. ASSERT_TRUE(res);
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5607. // Verify pre-compression logger captured uncompressed content
  5608. EXPECT_EQ(test_content, pre_compression_body);
  5609. EXPECT_EQ("text/plain", pre_compression_content_type);
  5610. EXPECT_TRUE(pre_compression_content_encoding
  5611. .empty()); // No encoding header before compression
  5612. // Verify post-compression logger captured compressed content
  5613. EXPECT_NE(test_content,
  5614. post_compression_body); // Should be different after compression
  5615. EXPECT_EQ("text/plain", post_compression_content_type);
  5616. EXPECT_EQ("gzip", post_compression_content_encoding);
  5617. // Verify compressed content is smaller
  5618. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5619. }
  5620. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5621. const std::string test_content =
  5622. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5623. "3456789012345678901234567890";
  5624. std::string pre_compression_body;
  5625. std::string post_compression_body;
  5626. svr_.set_pre_compression_logger(
  5627. [&](const Request & /*req*/, const Response &res) {
  5628. pre_compression_body = res.body;
  5629. });
  5630. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5631. post_compression_body = res.body;
  5632. });
  5633. Headers headers;
  5634. headers.emplace("Accept-Encoding", "br");
  5635. auto res = cli_.Get("/compress", headers);
  5636. ASSERT_TRUE(res);
  5637. EXPECT_EQ(StatusCode::OK_200, res->status);
  5638. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5639. // Verify pre-compression content is uncompressed
  5640. EXPECT_EQ(test_content, pre_compression_body);
  5641. // Verify post-compression content is compressed
  5642. EXPECT_NE(test_content, post_compression_body);
  5643. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5644. }
  5645. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5646. const std::string test_content =
  5647. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5648. "3456789012345678901234567890";
  5649. std::string pre_compression_body;
  5650. std::string post_compression_body;
  5651. svr_.set_pre_compression_logger(
  5652. [&](const Request & /*req*/, const Response &res) {
  5653. pre_compression_body = res.body;
  5654. });
  5655. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5656. post_compression_body = res.body;
  5657. });
  5658. // Request without compression (use /nocompress endpoint)
  5659. Headers headers;
  5660. auto res = cli_.Get("/nocompress", headers);
  5661. ASSERT_TRUE(res);
  5662. EXPECT_EQ(StatusCode::OK_200, res->status);
  5663. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5664. // Pre-compression logger should not be called when no compression is applied
  5665. EXPECT_TRUE(
  5666. pre_compression_body.empty()); // Pre-compression logger not called
  5667. EXPECT_EQ(
  5668. test_content,
  5669. post_compression_body); // Post-compression logger captures final content
  5670. }
  5671. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5672. const std::string test_content =
  5673. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5674. "3456789012345678901234567890";
  5675. std::string pre_compression_body;
  5676. bool pre_logger_called = false;
  5677. // Set only pre-compression logger
  5678. svr_.set_pre_compression_logger(
  5679. [&](const Request & /*req*/, const Response &res) {
  5680. pre_compression_body = res.body;
  5681. pre_logger_called = true;
  5682. });
  5683. Headers headers;
  5684. headers.emplace("Accept-Encoding", "gzip");
  5685. auto res = cli_.Get("/compress", headers);
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5689. // Verify pre-compression logger was called
  5690. EXPECT_TRUE(pre_logger_called);
  5691. EXPECT_EQ(test_content, pre_compression_body);
  5692. }
  5693. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5694. {
  5695. // Test with Expect: 100-continue header - success case
  5696. // Server returns 100 Continue, client sends body, server returns 200 OK
  5697. Request req;
  5698. req.method = "POST";
  5699. req.path = "/post-large";
  5700. req.set_header("Expect", "100-continue");
  5701. req.body = LARGE_DATA;
  5702. Response res;
  5703. auto error = Error::Success;
  5704. cli_.set_keep_alive(true);
  5705. auto ret = cli_.send(req, res, error);
  5706. EXPECT_TRUE(ret);
  5707. EXPECT_EQ(StatusCode::OK_200, res.status);
  5708. EXPECT_EQ(LARGE_DATA, res.body);
  5709. }
  5710. {
  5711. // Test with Expect: 100-continue header - error case
  5712. // Client should not send the body when server returns an error
  5713. Request req;
  5714. req.method = "POST";
  5715. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5716. req.set_header("Expect", "100-continue");
  5717. req.body = LARGE_DATA;
  5718. Response res;
  5719. auto error = Error::Success;
  5720. auto start = std::chrono::high_resolution_clock::now();
  5721. cli_.set_keep_alive(true);
  5722. auto ret = cli_.send(req, res, error);
  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. // With Expect: 100-continue, request completes successfully but with error
  5728. EXPECT_TRUE(ret);
  5729. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5730. EXPECT_EQ("close", res.get_header_value("Connection"));
  5731. EXPECT_FALSE(cli_.is_socket_open());
  5732. EXPECT_LE(elapsed, 200);
  5733. }
  5734. {
  5735. // Send an extra GET request to ensure error recovery without hanging
  5736. Request req;
  5737. req.method = "GET";
  5738. req.path = "/hi";
  5739. auto start = std::chrono::high_resolution_clock::now();
  5740. auto res = cli_.send(req);
  5741. auto end = std::chrono::high_resolution_clock::now();
  5742. auto elapsed =
  5743. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5744. .count();
  5745. ASSERT_TRUE(res);
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("Hello World!", res->body);
  5748. EXPECT_LE(elapsed, 500);
  5749. }
  5750. }
  5751. TEST(ZstdDecompressor, ChunkedDecompression) {
  5752. std::string data;
  5753. for (size_t i = 0; i < 32 * 1024; ++i) {
  5754. data.push_back(static_cast<char>('a' + i % 26));
  5755. }
  5756. std::string compressed_data;
  5757. {
  5758. httplib::detail::zstd_compressor compressor;
  5759. bool result = compressor.compress(
  5760. data.data(), data.size(),
  5761. /*last=*/true,
  5762. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5763. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5764. compressed_data_size);
  5765. return true;
  5766. });
  5767. ASSERT_TRUE(result);
  5768. }
  5769. std::string decompressed_data;
  5770. {
  5771. httplib::detail::zstd_decompressor decompressor;
  5772. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5773. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5774. size_t chunk_size = 130;
  5775. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5776. chunk_begin += chunk_size) {
  5777. size_t current_chunk_size =
  5778. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5779. bool result = decompressor.decompress(
  5780. compressed_data.data() + chunk_begin, current_chunk_size,
  5781. [&](const char *decompressed_data_chunk,
  5782. size_t decompressed_data_chunk_size) {
  5783. decompressed_data.insert(decompressed_data.size(),
  5784. decompressed_data_chunk,
  5785. decompressed_data_chunk_size);
  5786. return true;
  5787. });
  5788. ASSERT_TRUE(result);
  5789. }
  5790. }
  5791. ASSERT_EQ(data, decompressed_data);
  5792. }
  5793. TEST(ZstdDecompressor, Decompress) {
  5794. std::string original_text = "Compressed with ZSTD";
  5795. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5796. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5797. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5798. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5799. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5800. std::string decompressed_data;
  5801. {
  5802. httplib::detail::zstd_decompressor decompressor;
  5803. bool result = decompressor.decompress(
  5804. compressed_data.data(), compressed_data.size(),
  5805. [&](const char *decompressed_data_chunk,
  5806. size_t decompressed_data_chunk_size) {
  5807. decompressed_data.insert(decompressed_data.size(),
  5808. decompressed_data_chunk,
  5809. decompressed_data_chunk_size);
  5810. return true;
  5811. });
  5812. ASSERT_TRUE(result);
  5813. }
  5814. ASSERT_EQ(original_text, decompressed_data);
  5815. }
  5816. #endif
  5817. // Sends a raw request to a server listening at HOST:PORT.
  5818. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5819. std::string *resp = nullptr) {
  5820. auto error = Error::Success;
  5821. auto client_sock = detail::create_client_socket(
  5822. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5823. /*connection_timeout_sec=*/5, 0,
  5824. /*read_timeout_sec=*/5, 0,
  5825. /*write_timeout_sec=*/5, 0, std::string(), error);
  5826. if (client_sock == INVALID_SOCKET) { return false; }
  5827. auto ret = detail::process_client_socket(
  5828. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5829. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5830. if (req.size() !=
  5831. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5832. return false;
  5833. }
  5834. char buf[512];
  5835. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5836. while (line_reader.getline()) {
  5837. if (resp) { *resp += line_reader.ptr(); }
  5838. }
  5839. return true;
  5840. });
  5841. detail::close_socket(client_sock);
  5842. return ret;
  5843. }
  5844. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5845. Server svr;
  5846. std::string header_value;
  5847. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5848. header_value = req.get_header_value("foo");
  5849. res.set_content("ok", "text/plain");
  5850. });
  5851. thread t = thread([&] { svr.listen(HOST, PORT); });
  5852. auto se = detail::scope_exit([&] {
  5853. svr.stop();
  5854. t.join();
  5855. ASSERT_FALSE(svr.is_running());
  5856. });
  5857. svr.wait_until_ready();
  5858. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5859. // like characters are not treated the same - use vertical tab and escape.
  5860. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5861. "foo: \t \v bar \x1B\t \r\n"
  5862. "Connection: close\r\n"
  5863. "\r\n";
  5864. std::string res;
  5865. ASSERT_TRUE(send_request(5, req, &res));
  5866. EXPECT_EQ(header_value, "");
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5868. }
  5869. // Sends a raw request and verifies that there isn't a crash or exception.
  5870. static void test_raw_request(const std::string &req,
  5871. std::string *out = nullptr) {
  5872. Server svr;
  5873. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5874. res.set_content("ok", "text/plain");
  5875. });
  5876. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5877. res.set_content("ok", "text/plain");
  5878. });
  5879. svr.Get("/header_field_value_check",
  5880. [&](const Request & /*req*/, Response &res) {
  5881. res.set_content("ok", "text/plain");
  5882. });
  5883. // Server read timeout must be longer than the client read timeout for the
  5884. // bug to reproduce, probably to force the server to process a request
  5885. // without a trailing blank line.
  5886. const time_t client_read_timeout_sec = 1;
  5887. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5888. bool listen_thread_ok = false;
  5889. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. ASSERT_FALSE(svr.is_running());
  5894. EXPECT_TRUE(listen_thread_ok);
  5895. });
  5896. svr.wait_until_ready();
  5897. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5898. }
  5899. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5900. // A certain header line causes an exception if the header property is parsed
  5901. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5902. test_raw_request(
  5903. "GET /hi HTTP/1.1\r\n"
  5904. " : "
  5905. " "
  5906. " ");
  5907. }
  5908. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5909. // A certain header line causes an exception if the header property *name* is
  5910. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5911. // greedy matcher and requires backtracking when there are a lot of ":"
  5912. // characters.
  5913. // This occurs with libc++ but not libstdc++.
  5914. test_raw_request(
  5915. "GET /hi HTTP/1.1\r\n"
  5916. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5917. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5918. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5919. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5920. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5921. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5922. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5923. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5924. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5925. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5926. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5927. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5928. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5929. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5930. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5931. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5932. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5933. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5934. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5935. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5936. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5937. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5938. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5939. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5940. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5941. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5942. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5943. "&&&%%%");
  5944. }
  5945. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5946. // Make sure this doesn't crash the server.
  5947. // In a previous version of the header line regex, the "\r" rendered the line
  5948. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5949. // a new position where the leading white space ended and the field value
  5950. // began.
  5951. // The crash occurs with libc++ but not libstdc++.
  5952. test_raw_request("GET /hi HTTP/1.1\r\n"
  5953. "a:" +
  5954. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5955. "\r\n"
  5956. "\r\n");
  5957. }
  5958. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5959. std::string out;
  5960. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5961. "Content-Type: text/plain\r\n"
  5962. "Transfer-Encoding: chunked\r\n"
  5963. "\r\n"
  5964. "nothex\r\n",
  5965. &out);
  5966. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5967. }
  5968. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5969. std::string out;
  5970. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5971. "Content-Type: text/plain\r\n"
  5972. "Transfer-Encoding: chunked\r\n"
  5973. "\r\n"
  5974. "3\r\n"
  5975. "xyz\r\n"
  5976. "NaN\r\n",
  5977. &out);
  5978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5979. }
  5980. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5981. std::string out;
  5982. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5983. "Content-Type: text/plain\r\n"
  5984. "Transfer-Encoding: chunked\r\n"
  5985. "\r\n"
  5986. // Length is too large for 64 bits.
  5987. "1ffffffffffffffff\r\n"
  5988. "xyz\r\n",
  5989. &out);
  5990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5991. }
  5992. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5993. test_raw_request("GET /hi HTTP/1.1\r\n"
  5994. "Content-Type: text/plain\r\n\r");
  5995. }
  5996. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5997. std::string out;
  5998. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5999. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6000. }
  6001. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6002. Server svr;
  6003. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6004. EXPECT_TRUE(!req.remote_addr.empty());
  6005. });
  6006. thread t = thread([&] { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. ASSERT_FALSE(svr.is_running());
  6011. });
  6012. svr.wait_until_ready();
  6013. // Send an invalid request line to trigger Bad Request
  6014. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6015. std::string out;
  6016. ASSERT_TRUE(send_request(5, bad_req, &out));
  6017. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6018. }
  6019. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6020. std::string out;
  6021. std::string request(
  6022. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6023. test_raw_request(request, &out);
  6024. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6025. }
  6026. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6027. std::string out;
  6028. std::string request(
  6029. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6030. test_raw_request(request, &out);
  6031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6032. }
  6033. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6034. std::string out;
  6035. std::string request(
  6036. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6037. test_raw_request(request, &out);
  6038. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6039. }
  6040. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6041. std::string out;
  6042. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6043. "Test: \r\n\r\n",
  6044. &out);
  6045. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6046. }
  6047. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6048. Server svr;
  6049. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6050. res.set_header("Cache-Control", "no-cache");
  6051. res.set_chunked_content_provider(
  6052. "text/event-stream", [](size_t offset, DataSink &sink) {
  6053. std::string s = "data:";
  6054. s += std::to_string(offset);
  6055. s += "\n\n";
  6056. auto ret = sink.write(s.data(), s.size());
  6057. EXPECT_TRUE(ret);
  6058. std::this_thread::sleep_for(std::chrono::seconds(1));
  6059. return true;
  6060. });
  6061. });
  6062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6063. svr.wait_until_ready();
  6064. Client client(HOST, PORT);
  6065. const Headers headers = {{"Accept", "text/event-stream"}};
  6066. auto get_thread = std::thread([&client, &headers]() {
  6067. auto res = client.Get(
  6068. "/events", headers,
  6069. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6070. });
  6071. auto se = detail::scope_exit([&] {
  6072. svr.stop();
  6073. get_thread.join();
  6074. listen_thread.join();
  6075. ASSERT_FALSE(svr.is_running());
  6076. });
  6077. // Give GET time to get a few messages.
  6078. std::this_thread::sleep_for(std::chrono::seconds(2));
  6079. }
  6080. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6081. httplib::Server svr;
  6082. svr.Post("/hi",
  6083. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6084. res.status = StatusCode::OK_200;
  6085. });
  6086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6087. svr.wait_until_ready();
  6088. Client cli(HOST, PORT);
  6089. auto res = cli.Post("/hi", "data", "text/plain");
  6090. ASSERT_TRUE(res);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. svr.stop();
  6093. thread.join();
  6094. ASSERT_FALSE(svr.is_running());
  6095. res = cli.Post("/hi", "data", "text/plain");
  6096. ASSERT_FALSE(res);
  6097. }
  6098. TEST(ServerStopTest, ListenFailure) {
  6099. Server svr;
  6100. auto t = thread([&]() {
  6101. auto ret = svr.listen("????", PORT);
  6102. EXPECT_FALSE(ret);
  6103. });
  6104. svr.wait_until_ready();
  6105. svr.stop();
  6106. t.join();
  6107. }
  6108. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6109. TEST(ServerStopTest, Decommision) {
  6110. Server svr;
  6111. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6112. for (int i = 0; i < 4; i++) {
  6113. auto is_even = !(i % 2);
  6114. std::thread t{[&] {
  6115. try {
  6116. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6117. if (is_even) {
  6118. throw std::runtime_error("Some thing that happens to go wrong.");
  6119. }
  6120. svr.listen(HOST, PORT);
  6121. } catch (...) { svr.decommission(); }
  6122. }};
  6123. svr.wait_until_ready();
  6124. // Server is up
  6125. {
  6126. Client cli(HOST, PORT);
  6127. auto res = cli.Get("/hi");
  6128. if (is_even) {
  6129. EXPECT_FALSE(res);
  6130. } else {
  6131. EXPECT_TRUE(res);
  6132. EXPECT_EQ("hi...", res->body);
  6133. }
  6134. }
  6135. svr.stop();
  6136. t.join();
  6137. // Server is down...
  6138. {
  6139. Client cli(HOST, PORT);
  6140. auto res = cli.Get("/hi");
  6141. EXPECT_FALSE(res);
  6142. }
  6143. }
  6144. }
  6145. #endif
  6146. // Helper function for string body upload progress tests
  6147. template <typename SetupHandler, typename ClientCall>
  6148. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6149. ClientCall &&client_call,
  6150. const string &body) {
  6151. Server svr;
  6152. setup_handler(svr);
  6153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6154. auto se = detail::scope_exit([&] {
  6155. svr.stop();
  6156. t.join();
  6157. });
  6158. svr.wait_until_ready();
  6159. Client cli(HOST, PORT);
  6160. vector<uint64_t> progress_values;
  6161. bool progress_called = false;
  6162. auto res =
  6163. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6164. progress_values.push_back(current);
  6165. progress_called = true;
  6166. return true;
  6167. });
  6168. ASSERT_TRUE(res);
  6169. EXPECT_EQ(200, res->status);
  6170. EXPECT_TRUE(progress_called);
  6171. }
  6172. TEST(UploadProgressTest, PostStringBodyBasic) {
  6173. TestStringBodyUploadProgress(
  6174. [](Server &svr) {
  6175. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6176. res.set_content("received", "text/plain");
  6177. });
  6178. },
  6179. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6180. return cli.Post("/test", body, "text/plain", progress_callback);
  6181. },
  6182. "test data for upload progress");
  6183. }
  6184. TEST(UploadProgressTest, PutStringBodyBasic) {
  6185. TestStringBodyUploadProgress(
  6186. [](Server &svr) {
  6187. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6188. res.set_content("put received", "text/plain");
  6189. });
  6190. },
  6191. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6192. return cli.Put("/test", body, "text/plain", progress_callback);
  6193. },
  6194. "put test data for upload progress");
  6195. }
  6196. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6197. TestStringBodyUploadProgress(
  6198. [](Server &svr) {
  6199. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6200. res.set_content("patch received", "text/plain");
  6201. });
  6202. },
  6203. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6204. return cli.Patch("/test", body, "text/plain", progress_callback);
  6205. },
  6206. "patch test data for upload progress");
  6207. }
  6208. // Helper function for content provider upload progress tests
  6209. template <typename SetupHandler, typename ClientCall>
  6210. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6211. ClientCall &&client_call) {
  6212. Server svr;
  6213. setup_handler(svr);
  6214. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6215. auto se = detail::scope_exit([&] {
  6216. svr.stop();
  6217. t.join();
  6218. });
  6219. svr.wait_until_ready();
  6220. Client cli(HOST, PORT);
  6221. vector<uint64_t> progress_values;
  6222. auto res =
  6223. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6224. progress_values.push_back(current);
  6225. return true;
  6226. });
  6227. ASSERT_TRUE(res);
  6228. EXPECT_EQ(200, res->status);
  6229. EXPECT_FALSE(progress_values.empty());
  6230. }
  6231. TEST(UploadProgressTest, PostContentProviderProgress) {
  6232. TestContentProviderUploadProgress(
  6233. [](Server &svr) {
  6234. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6235. res.set_content("provider received", "text/plain");
  6236. });
  6237. },
  6238. [](Client &cli, UploadProgress progress_callback) {
  6239. return cli.Post(
  6240. "/test", 10,
  6241. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6242. sink.os << "test data";
  6243. return true;
  6244. },
  6245. "text/plain", progress_callback);
  6246. });
  6247. }
  6248. // Helper function for multipart upload progress tests
  6249. template <typename SetupHandler, typename ClientCall>
  6250. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6251. ClientCall &&client_call,
  6252. const string &endpoint) {
  6253. Server svr;
  6254. setup_handler(svr);
  6255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6256. auto se = detail::scope_exit([&] {
  6257. svr.stop();
  6258. t.join();
  6259. });
  6260. svr.wait_until_ready();
  6261. Client cli(HOST, PORT);
  6262. vector<uint64_t> progress_values;
  6263. UploadFormDataItems items = {
  6264. {"field1", "value1", "", ""},
  6265. {"field2", "longer value for progress tracking test", "", ""},
  6266. {"file1", "file content data for upload progress", "test.txt",
  6267. "text/plain"}};
  6268. auto res = client_call(cli, endpoint, items,
  6269. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6270. progress_values.push_back(current);
  6271. return true;
  6272. });
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ(200, res->status);
  6275. EXPECT_FALSE(progress_values.empty());
  6276. }
  6277. TEST(UploadProgressTest, PostMultipartProgress) {
  6278. TestMultipartUploadProgress(
  6279. [](Server &svr) {
  6280. svr.Post("/multipart", [](const Request &req, Response &res) {
  6281. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6282. res.set_content("multipart received", "text/plain");
  6283. });
  6284. },
  6285. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6286. UploadProgress progress_callback) {
  6287. return cli.Post(endpoint, items, progress_callback);
  6288. },
  6289. "/multipart");
  6290. }
  6291. // Helper function for basic download progress tests
  6292. template <typename SetupHandler, typename ClientCall>
  6293. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6294. ClientCall &&client_call, const string &endpoint,
  6295. size_t expected_content_size) {
  6296. Server svr;
  6297. setup_handler(svr);
  6298. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6299. auto se = detail::scope_exit([&] {
  6300. svr.stop();
  6301. t.join();
  6302. });
  6303. svr.wait_until_ready();
  6304. Client cli(HOST, PORT);
  6305. vector<uint64_t> progress_values;
  6306. auto res = client_call(cli, endpoint,
  6307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6308. progress_values.push_back(current);
  6309. return true;
  6310. });
  6311. ASSERT_TRUE(res);
  6312. EXPECT_EQ(200, res->status);
  6313. EXPECT_FALSE(progress_values.empty());
  6314. EXPECT_EQ(expected_content_size, res->body.size());
  6315. }
  6316. TEST(DownloadProgressTest, GetBasic) {
  6317. TestBasicDownloadProgress(
  6318. [](Server &svr) {
  6319. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6320. string content(1000, 'D');
  6321. res.set_content(content, "text/plain");
  6322. });
  6323. },
  6324. [](Client &cli, const string &endpoint,
  6325. DownloadProgress progress_callback) {
  6326. return cli.Get(endpoint, progress_callback);
  6327. },
  6328. "/download", 1000u);
  6329. }
  6330. // Helper function for content receiver download progress tests
  6331. template <typename SetupHandler, typename ClientCall>
  6332. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6333. ClientCall &&client_call,
  6334. const string &endpoint,
  6335. size_t expected_content_size) {
  6336. Server svr;
  6337. setup_handler(svr);
  6338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6339. auto se = detail::scope_exit([&] {
  6340. svr.stop();
  6341. t.join();
  6342. });
  6343. svr.wait_until_ready();
  6344. Client cli(HOST, PORT);
  6345. vector<uint64_t> progress_values;
  6346. string received_body;
  6347. auto res = client_call(
  6348. cli, endpoint,
  6349. [&](const char *data, size_t data_length) -> bool {
  6350. received_body.append(data, data_length);
  6351. return true;
  6352. },
  6353. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6354. progress_values.push_back(current);
  6355. return true;
  6356. });
  6357. ASSERT_TRUE(res);
  6358. EXPECT_EQ(200, res->status);
  6359. EXPECT_FALSE(progress_values.empty());
  6360. EXPECT_EQ(expected_content_size, received_body.size());
  6361. EXPECT_TRUE(res->body.empty());
  6362. }
  6363. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6364. TestContentReceiverDownloadProgress(
  6365. [](Server &svr) {
  6366. svr.Get("/download-receiver",
  6367. [](const Request & /*req*/, Response &res) {
  6368. string content(2000, 'R');
  6369. res.set_content(content, "text/plain");
  6370. });
  6371. },
  6372. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6373. DownloadProgress progress_callback) {
  6374. return cli.Get(endpoint, content_receiver, progress_callback);
  6375. },
  6376. "/download-receiver", 2000u);
  6377. }
  6378. TEST(StreamingTest, NoContentLengthStreaming) {
  6379. Server svr;
  6380. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6381. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6382. if (offset < 6) {
  6383. sink.os << (offset < 3 ? "a" : "b");
  6384. } else {
  6385. sink.done();
  6386. }
  6387. return true;
  6388. });
  6389. });
  6390. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6391. auto listen_se = detail::scope_exit([&] {
  6392. svr.stop();
  6393. listen_thread.join();
  6394. ASSERT_FALSE(svr.is_running());
  6395. });
  6396. svr.wait_until_ready();
  6397. Client client(HOST, PORT);
  6398. auto get_thread = std::thread([&client]() {
  6399. std::string s;
  6400. auto res =
  6401. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6402. s += std::string(data, len);
  6403. return true;
  6404. });
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("aaabbb", s);
  6408. });
  6409. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6410. // Give GET time to get a few messages.
  6411. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6412. }
  6413. TEST(MountTest, Unmount) {
  6414. Server svr;
  6415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6416. auto se = detail::scope_exit([&] {
  6417. svr.stop();
  6418. listen_thread.join();
  6419. ASSERT_FALSE(svr.is_running());
  6420. });
  6421. svr.wait_until_ready();
  6422. Client cli("localhost", PORT);
  6423. svr.set_mount_point("/mount2", "./www2");
  6424. auto res = cli.Get("/");
  6425. ASSERT_TRUE(res);
  6426. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6427. res = cli.Get("/mount2/dir/test.html");
  6428. ASSERT_TRUE(res);
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. svr.set_mount_point("/", "./www");
  6431. res = cli.Get("/dir/");
  6432. ASSERT_TRUE(res);
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. svr.remove_mount_point("/");
  6435. res = cli.Get("/dir/");
  6436. ASSERT_TRUE(res);
  6437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6438. svr.remove_mount_point("/mount2");
  6439. res = cli.Get("/mount2/dir/test.html");
  6440. ASSERT_TRUE(res);
  6441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6442. }
  6443. TEST(MountTest, Redicect) {
  6444. Server svr;
  6445. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6446. auto se = detail::scope_exit([&] {
  6447. svr.stop();
  6448. listen_thread.join();
  6449. ASSERT_FALSE(svr.is_running());
  6450. });
  6451. svr.set_mount_point("/", "./www");
  6452. svr.wait_until_ready();
  6453. Client cli("localhost", PORT);
  6454. auto res = cli.Get("/dir/");
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. res = cli.Get("/dir");
  6458. ASSERT_TRUE(res);
  6459. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6460. res = cli.Get("/file");
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. res = cli.Get("/file/");
  6464. ASSERT_TRUE(res);
  6465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6466. cli.set_follow_location(true);
  6467. res = cli.Get("/dir");
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. }
  6471. TEST(MountTest, MultibytesPathName) {
  6472. Server svr;
  6473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6474. auto se = detail::scope_exit([&] {
  6475. svr.stop();
  6476. listen_thread.join();
  6477. ASSERT_FALSE(svr.is_running());
  6478. });
  6479. svr.set_mount_point("/", "./www");
  6480. svr.wait_until_ready();
  6481. Client cli("localhost", PORT);
  6482. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6483. ASSERT_TRUE(res);
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6486. }
  6487. TEST(KeepAliveTest, ReadTimeout) {
  6488. Server svr;
  6489. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6490. std::this_thread::sleep_for(std::chrono::seconds(2));
  6491. res.set_content("a", "text/plain");
  6492. });
  6493. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6494. res.set_content("b", "text/plain");
  6495. });
  6496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6497. auto se = detail::scope_exit([&] {
  6498. svr.stop();
  6499. listen_thread.join();
  6500. ASSERT_FALSE(svr.is_running());
  6501. });
  6502. svr.wait_until_ready();
  6503. Client cli("localhost", PORT);
  6504. cli.set_keep_alive(true);
  6505. cli.set_read_timeout(std::chrono::seconds(1));
  6506. auto resa = cli.Get("/a");
  6507. ASSERT_FALSE(resa);
  6508. EXPECT_EQ(Error::Read, resa.error());
  6509. auto resb = cli.Get("/b");
  6510. ASSERT_TRUE(resb);
  6511. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6512. EXPECT_EQ("b", resb->body);
  6513. }
  6514. TEST(KeepAliveTest, MaxCount) {
  6515. size_t keep_alive_max_count = 3;
  6516. Server svr;
  6517. svr.set_keep_alive_max_count(keep_alive_max_count);
  6518. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6519. res.set_content("Hello World!", "text/plain");
  6520. });
  6521. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6522. auto se = detail::scope_exit([&] {
  6523. svr.stop();
  6524. listen_thread.join();
  6525. ASSERT_FALSE(svr.is_running());
  6526. });
  6527. svr.wait_until_ready();
  6528. Client cli(HOST, PORT);
  6529. cli.set_keep_alive(true);
  6530. for (size_t i = 0; i < 5; i++) {
  6531. auto result = cli.Get("/hi");
  6532. ASSERT_TRUE(result);
  6533. EXPECT_EQ(StatusCode::OK_200, result->status);
  6534. if (i == keep_alive_max_count - 1) {
  6535. EXPECT_EQ("close", result->get_header_value("Connection"));
  6536. } else {
  6537. EXPECT_FALSE(result->has_header("Connection"));
  6538. }
  6539. }
  6540. }
  6541. TEST(KeepAliveTest, Issue1041) {
  6542. Server svr;
  6543. svr.set_keep_alive_timeout(3);
  6544. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6545. res.set_content("Hello World!", "text/plain");
  6546. });
  6547. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6548. auto se = detail::scope_exit([&] {
  6549. svr.stop();
  6550. listen_thread.join();
  6551. ASSERT_FALSE(svr.is_running());
  6552. });
  6553. svr.wait_until_ready();
  6554. Client cli(HOST, PORT);
  6555. cli.set_keep_alive(true);
  6556. auto result = cli.Get("/hi");
  6557. ASSERT_TRUE(result);
  6558. EXPECT_EQ(StatusCode::OK_200, result->status);
  6559. std::this_thread::sleep_for(std::chrono::seconds(5));
  6560. result = cli.Get("/hi");
  6561. ASSERT_TRUE(result);
  6562. EXPECT_EQ(StatusCode::OK_200, result->status);
  6563. }
  6564. TEST(KeepAliveTest, Issue1959) {
  6565. Server svr;
  6566. svr.set_keep_alive_timeout(5);
  6567. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6568. res.set_content("a", "text/plain");
  6569. });
  6570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6571. auto se = detail::scope_exit([&] {
  6572. if (!svr.is_running()) return;
  6573. svr.stop();
  6574. listen_thread.join();
  6575. ASSERT_FALSE(svr.is_running());
  6576. });
  6577. svr.wait_until_ready();
  6578. Client cli("localhost", PORT);
  6579. cli.set_keep_alive(true);
  6580. using namespace std::chrono;
  6581. auto start = steady_clock::now();
  6582. cli.Get("/a");
  6583. svr.stop();
  6584. listen_thread.join();
  6585. auto end = steady_clock::now();
  6586. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6587. EXPECT_LT(elapsed, 5000);
  6588. }
  6589. #ifdef CPPHTTPLIB_SSL_ENABLED
  6590. TEST(KeepAliveTest, SSLClientReconnection) {
  6591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6592. ASSERT_TRUE(svr.is_valid());
  6593. svr.set_keep_alive_timeout(1);
  6594. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6595. res.set_content("Hello World!", "text/plain");
  6596. });
  6597. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6598. auto se = detail::scope_exit([&] {
  6599. svr.stop();
  6600. listen_thread.join();
  6601. ASSERT_FALSE(svr.is_running());
  6602. });
  6603. svr.wait_until_ready();
  6604. SSLClient cli(HOST, PORT);
  6605. cli.enable_server_certificate_verification(false);
  6606. cli.set_keep_alive(true);
  6607. auto result = cli.Get("/hi");
  6608. ASSERT_TRUE(result);
  6609. EXPECT_EQ(StatusCode::OK_200, result->status);
  6610. result = cli.Get("/hi");
  6611. ASSERT_TRUE(result);
  6612. EXPECT_EQ(StatusCode::OK_200, result->status);
  6613. std::this_thread::sleep_for(std::chrono::seconds(2));
  6614. // Recoonect
  6615. result = cli.Get("/hi");
  6616. ASSERT_TRUE(result);
  6617. EXPECT_EQ(StatusCode::OK_200, result->status);
  6618. result = cli.Get("/hi");
  6619. ASSERT_TRUE(result);
  6620. EXPECT_EQ(StatusCode::OK_200, result->status);
  6621. }
  6622. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6624. ASSERT_TRUE(svr.is_valid());
  6625. svr.set_keep_alive_timeout(1);
  6626. std::string content = "reconnect";
  6627. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6628. res.set_content("Hello World!", "text/plain");
  6629. });
  6630. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6631. auto se = detail::scope_exit([&] {
  6632. svr.stop();
  6633. listen_thread.join();
  6634. ASSERT_FALSE(svr.is_running());
  6635. });
  6636. svr.wait_until_ready();
  6637. SSLClient cli(HOST, PORT);
  6638. cli.enable_server_certificate_verification(false);
  6639. cli.set_keep_alive(true);
  6640. auto result = cli.Post(
  6641. "/hi", content.size(),
  6642. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6643. sink.write(content.c_str(), content.size());
  6644. return true;
  6645. },
  6646. "text/plain");
  6647. ASSERT_TRUE(result);
  6648. EXPECT_EQ(200, result->status);
  6649. std::this_thread::sleep_for(std::chrono::seconds(2));
  6650. // Recoonect
  6651. result = cli.Post(
  6652. "/hi", content.size(),
  6653. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6654. sink.write(content.c_str(), content.size());
  6655. return true;
  6656. },
  6657. "text/plain");
  6658. ASSERT_TRUE(result);
  6659. EXPECT_EQ(200, result->status);
  6660. result = cli.Post(
  6661. "/hi", content.size(),
  6662. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6663. sink.write(content.c_str(), content.size());
  6664. return true;
  6665. },
  6666. "text/plain");
  6667. ASSERT_TRUE(result);
  6668. EXPECT_EQ(200, result->status);
  6669. }
  6670. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6671. using namespace httplib::tls;
  6672. {
  6673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6674. ASSERT_TRUE(svr.is_valid());
  6675. svr.Get("/sni", [&](const Request &req, Response &res) {
  6676. std::string expected = req.sni();
  6677. EXPECT_EQ(expected, req.get_param_value("expected"));
  6678. res.set_content("ok", "text/plain");
  6679. });
  6680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6681. auto se = detail::scope_exit([&] {
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. {
  6688. SSLClient cli("localhost", PORT);
  6689. cli.enable_server_certificate_verification(false);
  6690. auto res = cli.Get("/sni?expected=localhost");
  6691. ASSERT_TRUE(res);
  6692. }
  6693. {
  6694. SSLClient cli("::1", PORT);
  6695. cli.enable_server_certificate_verification(false);
  6696. auto res = cli.Get("/sni?expected=");
  6697. // NOTE: This may fail if the server is listening on IPv4 only
  6698. // (e.g., when localhost resolves to 127.0.0.1 only)
  6699. if (res) {
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. } else {
  6702. EXPECT_EQ(Error::Connection, res.error());
  6703. }
  6704. }
  6705. }
  6706. }
  6707. #endif
  6708. TEST(ClientProblemDetectionTest, ContentProvider) {
  6709. Server svr;
  6710. size_t content_length = 1024 * 1024;
  6711. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6712. res.set_content_provider(
  6713. content_length, "text/plain",
  6714. [&](size_t offset, size_t length, DataSink &sink) {
  6715. auto out_len = std::min(length, static_cast<size_t>(1024));
  6716. std::string out(out_len, '@');
  6717. sink.write(out.data(), out_len);
  6718. return offset < 4096;
  6719. },
  6720. [](bool success) { ASSERT_FALSE(success); });
  6721. });
  6722. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6723. res.set_content_provider(
  6724. 0, "text/plain",
  6725. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6726. EXPECT_TRUE(false);
  6727. return true;
  6728. },
  6729. [](bool success) { ASSERT_FALSE(success); });
  6730. });
  6731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6732. auto se = detail::scope_exit([&] {
  6733. svr.stop();
  6734. listen_thread.join();
  6735. ASSERT_FALSE(svr.is_running());
  6736. });
  6737. svr.wait_until_ready();
  6738. Client cli("localhost", PORT);
  6739. {
  6740. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6741. size_t /*data_length*/) { return false; });
  6742. ASSERT_FALSE(res);
  6743. }
  6744. {
  6745. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6746. size_t /*data_length*/) { return false; });
  6747. ASSERT_TRUE(res);
  6748. }
  6749. }
  6750. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6751. Server svr;
  6752. svr.set_error_handler([](Request const &, Response &res) -> void {
  6753. res.set_chunked_content_provider(
  6754. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6755. sink.os << "hello";
  6756. sink.os << "world";
  6757. sink.done();
  6758. return true;
  6759. });
  6760. });
  6761. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6762. auto se = detail::scope_exit([&] {
  6763. svr.stop();
  6764. listen_thread.join();
  6765. ASSERT_FALSE(svr.is_running());
  6766. });
  6767. svr.wait_until_ready();
  6768. Client cli("localhost", PORT);
  6769. auto res = cli.Get("/");
  6770. ASSERT_TRUE(res);
  6771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6772. EXPECT_EQ("helloworld", res->body);
  6773. }
  6774. TEST(LongPollingTest, ClientCloseDetection) {
  6775. Server svr;
  6776. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6777. res.set_chunked_content_provider(
  6778. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6779. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6780. sink.os << "hello";
  6781. auto count = 10;
  6782. while (count > 0 && sink.is_writable()) {
  6783. this_thread::sleep_for(chrono::milliseconds(10));
  6784. count--;
  6785. }
  6786. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6787. return true;
  6788. });
  6789. });
  6790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6791. auto se = detail::scope_exit([&] {
  6792. svr.stop();
  6793. listen_thread.join();
  6794. ASSERT_FALSE(svr.is_running());
  6795. });
  6796. svr.wait_until_ready();
  6797. Client cli("localhost", PORT);
  6798. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6799. EXPECT_EQ("hello", string(data, data_length));
  6800. return false; // close the socket immediately.
  6801. });
  6802. ASSERT_FALSE(res);
  6803. }
  6804. TEST(GetWithParametersTest, GetWithParameters) {
  6805. Server svr;
  6806. svr.Get("/", [&](const Request &req, Response &) {
  6807. EXPECT_EQ("world", req.get_param_value("hello"));
  6808. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6809. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6810. });
  6811. svr.Get("/params", [&](const Request &req, Response &) {
  6812. EXPECT_EQ("world", req.get_param_value("hello"));
  6813. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6814. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6815. });
  6816. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6817. EXPECT_EQ("resource-id", req.matches[1]);
  6818. EXPECT_EQ("foo", req.get_param_value("param1"));
  6819. EXPECT_EQ("bar", req.get_param_value("param2"));
  6820. });
  6821. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6822. EXPECT_EQ("user-id", req.path_params.at("id"));
  6823. EXPECT_EQ("foo", req.get_param_value("param1"));
  6824. EXPECT_EQ("bar", req.get_param_value("param2"));
  6825. });
  6826. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6827. auto se = detail::scope_exit([&] {
  6828. svr.stop();
  6829. listen_thread.join();
  6830. ASSERT_FALSE(svr.is_running());
  6831. });
  6832. svr.wait_until_ready();
  6833. {
  6834. Client cli(HOST, PORT);
  6835. Params params;
  6836. params.emplace("hello", "world");
  6837. params.emplace("hello2", "world2");
  6838. params.emplace("hello3", "world3");
  6839. auto res = cli.Get("/", params, Headers{});
  6840. ASSERT_TRUE(res);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. {
  6844. Client cli(HOST, PORT);
  6845. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6846. ASSERT_TRUE(res);
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. {
  6850. Client cli(HOST, PORT);
  6851. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6852. ASSERT_TRUE(res);
  6853. EXPECT_EQ(StatusCode::OK_200, res->status);
  6854. }
  6855. {
  6856. Client cli(HOST, PORT);
  6857. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6858. ASSERT_TRUE(res);
  6859. EXPECT_EQ(StatusCode::OK_200, res->status);
  6860. }
  6861. }
  6862. TEST(GetWithParametersTest, GetWithParameters2) {
  6863. Server svr;
  6864. svr.Get("/", [&](const Request &req, Response &res) {
  6865. auto text = req.get_param_value("hello");
  6866. res.set_content(text, "text/plain");
  6867. });
  6868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6869. auto se = detail::scope_exit([&] {
  6870. svr.stop();
  6871. listen_thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli("localhost", PORT);
  6876. Params params;
  6877. params.emplace("hello", "world");
  6878. std::string body;
  6879. auto res = cli.Get("/", params, Headers{},
  6880. [&](const char *data, size_t data_length) {
  6881. body.append(data, data_length);
  6882. return true;
  6883. });
  6884. ASSERT_TRUE(res);
  6885. EXPECT_EQ(StatusCode::OK_200, res->status);
  6886. EXPECT_EQ("world", body);
  6887. }
  6888. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6889. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6890. auto host = "httpcan.org";
  6891. auto path = std::string{"/range/32"};
  6892. #else
  6893. auto host = "nghttp2.org";
  6894. auto path = std::string{"/httpbin/range/32"};
  6895. #endif
  6896. #ifdef CPPHTTPLIB_SSL_ENABLED
  6897. SSLClient cli(host);
  6898. #else
  6899. Client cli(host);
  6900. #endif
  6901. cli.set_default_headers({make_range_header({{1, 10}})});
  6902. cli.set_connection_timeout(5);
  6903. {
  6904. auto res = cli.Get(path);
  6905. ASSERT_TRUE(res);
  6906. EXPECT_EQ("bcdefghijk", res->body);
  6907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6908. }
  6909. {
  6910. auto res = cli.Get(path);
  6911. ASSERT_TRUE(res);
  6912. EXPECT_EQ("bcdefghijk", res->body);
  6913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6914. }
  6915. }
  6916. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6917. Server svr;
  6918. svr.set_default_headers({{"Hello", "World"}});
  6919. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6920. res.set_content("ok", "text/plain");
  6921. });
  6922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6923. auto se = detail::scope_exit([&] {
  6924. svr.stop();
  6925. listen_thread.join();
  6926. ASSERT_FALSE(svr.is_running());
  6927. });
  6928. svr.wait_until_ready();
  6929. Client cli("localhost", PORT);
  6930. auto res = cli.Get("/");
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. EXPECT_EQ("ok", res->body);
  6934. EXPECT_EQ("World", res->get_header_value("Hello"));
  6935. }
  6936. #ifdef CPPHTTPLIB_SSL_ENABLED
  6937. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6939. ASSERT_TRUE(svr.is_valid());
  6940. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6941. std::this_thread::sleep_for(std::chrono::seconds(2));
  6942. res.set_content("a", "text/plain");
  6943. });
  6944. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6945. res.set_content("b", "text/plain");
  6946. });
  6947. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6948. auto se = detail::scope_exit([&] {
  6949. svr.stop();
  6950. listen_thread.join();
  6951. ASSERT_FALSE(svr.is_running());
  6952. });
  6953. svr.wait_until_ready();
  6954. SSLClient cli("localhost", PORT);
  6955. cli.enable_server_certificate_verification(false);
  6956. cli.set_keep_alive(true);
  6957. cli.set_read_timeout(std::chrono::seconds(1));
  6958. auto resa = cli.Get("/a");
  6959. ASSERT_TRUE(!resa);
  6960. EXPECT_EQ(Error::Read, resa.error());
  6961. auto resb = cli.Get("/b");
  6962. ASSERT_TRUE(resb);
  6963. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6964. EXPECT_EQ("b", resb->body);
  6965. }
  6966. #endif
  6967. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6968. protected:
  6969. ServerTestWithAI_PASSIVE()
  6970. : cli_(HOST, PORT)
  6971. #ifdef CPPHTTPLIB_SSL_ENABLED
  6972. ,
  6973. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6974. #endif
  6975. {
  6976. #ifdef CPPHTTPLIB_SSL_ENABLED
  6977. cli_.enable_server_certificate_verification(false);
  6978. #endif
  6979. }
  6980. virtual void SetUp() {
  6981. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6982. res.set_content("Hello World!", "text/plain");
  6983. });
  6984. t_ = thread(
  6985. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6986. svr_.wait_until_ready();
  6987. }
  6988. virtual void TearDown() {
  6989. svr_.stop();
  6990. t_.join();
  6991. }
  6992. #ifdef CPPHTTPLIB_SSL_ENABLED
  6993. SSLClient cli_;
  6994. SSLServer svr_;
  6995. #else
  6996. Client cli_;
  6997. Server svr_;
  6998. #endif
  6999. thread t_;
  7000. };
  7001. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7002. auto res = cli_.Get("/hi");
  7003. ASSERT_TRUE(res);
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7006. EXPECT_EQ("Hello World!", res->body);
  7007. }
  7008. class ServerUpDownTest : public ::testing::Test {
  7009. protected:
  7010. ServerUpDownTest() : cli_(HOST, PORT) {}
  7011. virtual void SetUp() {
  7012. t_ = thread([&]() {
  7013. svr_.bind_to_any_port(HOST);
  7014. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7015. ASSERT_TRUE(svr_.listen_after_bind());
  7016. });
  7017. svr_.wait_until_ready();
  7018. }
  7019. virtual void TearDown() {
  7020. svr_.stop();
  7021. t_.join();
  7022. }
  7023. Client cli_;
  7024. Server svr_;
  7025. thread t_;
  7026. };
  7027. TEST_F(ServerUpDownTest, QuickStartStop) {
  7028. // Should not crash, especially when run with
  7029. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7030. }
  7031. class PayloadMaxLengthTest : public ::testing::Test {
  7032. protected:
  7033. PayloadMaxLengthTest()
  7034. : cli_(HOST, PORT)
  7035. #ifdef CPPHTTPLIB_SSL_ENABLED
  7036. ,
  7037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7038. #endif
  7039. {
  7040. #ifdef CPPHTTPLIB_SSL_ENABLED
  7041. cli_.enable_server_certificate_verification(false);
  7042. #endif
  7043. }
  7044. virtual void SetUp() {
  7045. svr_.set_payload_max_length(8);
  7046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7047. res.set_content("test", "text/plain");
  7048. });
  7049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7050. svr_.wait_until_ready();
  7051. }
  7052. virtual void TearDown() {
  7053. svr_.stop();
  7054. t_.join();
  7055. }
  7056. #ifdef CPPHTTPLIB_SSL_ENABLED
  7057. SSLClient cli_;
  7058. SSLServer svr_;
  7059. #else
  7060. Client cli_;
  7061. Server svr_;
  7062. #endif
  7063. thread t_;
  7064. };
  7065. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7066. auto res = cli_.Post("/test", "123456789", "text/plain");
  7067. ASSERT_TRUE(res);
  7068. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7069. res = cli_.Post("/test", "12345678", "text/plain");
  7070. ASSERT_TRUE(res);
  7071. EXPECT_EQ(StatusCode::OK_200, res->status);
  7072. }
  7073. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7074. // Test chunked encoding with payload exceeding the 8-byte limit
  7075. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7076. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7077. ASSERT_TRUE(res);
  7078. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7079. }
  7080. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7081. // Test chunked encoding with payload within the 8-byte limit
  7082. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7083. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7084. ASSERT_TRUE(res);
  7085. EXPECT_EQ(StatusCode::OK_200, res->status);
  7086. }
  7087. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7088. // Test using send_request to send chunked data exceeding payload limit
  7089. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7090. "Host: " +
  7091. std::string(HOST) + ":" + std::to_string(PORT) +
  7092. "\r\n"
  7093. "Transfer-Encoding: chunked\r\n"
  7094. "Connection: close\r\n"
  7095. "\r\n"
  7096. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7097. "0123456789\r\n"
  7098. "0\r\n" // End chunk
  7099. "\r\n";
  7100. std::string response;
  7101. bool result = send_request(1, chunked_request, &response);
  7102. if (!result) {
  7103. // If send_request fails, it might be because the server closed the
  7104. // connection due to payload limit enforcement, which is acceptable
  7105. SUCCEED()
  7106. << "Server rejected oversized chunked request (connection closed)";
  7107. } else {
  7108. // If we got a response, check if it's an error response or connection was
  7109. // closed early Short response length indicates connection was closed due to
  7110. // payload limit
  7111. if (response.length() <= 10) {
  7112. SUCCEED() << "Server closed connection for oversized chunked request";
  7113. } else {
  7114. // Check for error status codes
  7115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7116. response.find("Payload Too Large") != std::string::npos ||
  7117. response.find("400") != std::string::npos);
  7118. }
  7119. }
  7120. }
  7121. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7122. // Test request without Content-Length header exceeding payload limit
  7123. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7124. "Host: " +
  7125. std::string(HOST) + ":" +
  7126. std::to_string(PORT) +
  7127. "\r\n"
  7128. "Connection: close\r\n"
  7129. "\r\n";
  7130. // Add payload exceeding the 8-byte limit
  7131. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7132. request_without_content_length += large_payload;
  7133. std::string response;
  7134. bool result = send_request(1, request_without_content_length, &response);
  7135. if (!result) {
  7136. // If send_request fails, server likely closed connection due to payload
  7137. // limit
  7138. SUCCEED() << "Server rejected oversized request without Content-Length "
  7139. "(connection closed)";
  7140. } else {
  7141. // Check if server responded with error or closed connection early
  7142. if (response.length() <= 10) {
  7143. SUCCEED() << "Server closed connection for oversized request without "
  7144. "Content-Length";
  7145. } else {
  7146. // Check for error status codes
  7147. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7148. response.find("Payload Too Large") != std::string::npos ||
  7149. response.find("400") != std::string::npos);
  7150. }
  7151. }
  7152. }
  7153. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7154. // Test request without Content-Length header within payload limit
  7155. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7156. "Host: " +
  7157. std::string(HOST) + ":" +
  7158. std::to_string(PORT) +
  7159. "\r\n"
  7160. "Connection: close\r\n"
  7161. "\r\n";
  7162. // Add payload within the 8-byte limit
  7163. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7164. request_without_content_length += small_payload;
  7165. std::string response;
  7166. bool result = send_request(1, request_without_content_length, &response);
  7167. // For requests without Content-Length, the server may have different behavior
  7168. // The key is that it should not reject due to payload limit for small
  7169. // payloads
  7170. if (result) {
  7171. // Check for any HTTP response (success or error, but not connection closed)
  7172. if (response.length() > 10) {
  7173. SUCCEED()
  7174. << "Server processed request without Content-Length within limit";
  7175. } else {
  7176. // Short response might indicate connection closed, which is acceptable
  7177. SUCCEED() << "Server closed connection for request without "
  7178. "Content-Length (acceptable behavior)";
  7179. }
  7180. } else {
  7181. // Connection failure might be due to protocol requirements
  7182. SUCCEED() << "Connection issue with request without Content-Length "
  7183. "(environment-specific)";
  7184. }
  7185. }
  7186. class LargePayloadMaxLengthTest : public ::testing::Test {
  7187. protected:
  7188. LargePayloadMaxLengthTest()
  7189. : cli_(HOST, PORT)
  7190. #ifdef CPPHTTPLIB_SSL_ENABLED
  7191. ,
  7192. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7193. #endif
  7194. {
  7195. #ifdef CPPHTTPLIB_SSL_ENABLED
  7196. cli_.enable_server_certificate_verification(false);
  7197. #endif
  7198. }
  7199. virtual void SetUp() {
  7200. // Set 10MB payload limit
  7201. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7202. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7203. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7204. res.set_content("Large payload test", "text/plain");
  7205. });
  7206. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7207. svr_.wait_until_ready();
  7208. }
  7209. virtual void TearDown() {
  7210. svr_.stop();
  7211. t_.join();
  7212. }
  7213. #ifdef CPPHTTPLIB_SSL_ENABLED
  7214. SSLClient cli_;
  7215. SSLServer svr_;
  7216. #else
  7217. Client cli_;
  7218. Server svr_;
  7219. #endif
  7220. thread t_;
  7221. };
  7222. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7223. // Test chunked encoding with payload within 10MB limit
  7224. std::string medium_payload(5 * 1024 * 1024,
  7225. 'A'); // 5MB payload, within 10MB limit
  7226. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7227. ASSERT_TRUE(res);
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. }
  7230. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7231. // Test chunked encoding with payload exceeding 10MB limit
  7232. std::string large_payload(12 * 1024 * 1024,
  7233. 'B'); // 12MB payload, exceeds 10MB limit
  7234. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7235. // Server may either return 413 or close the connection
  7236. if (res) {
  7237. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7238. } else {
  7239. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7240. }
  7241. }
  7242. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7243. // Test request without Content-Length header within 10MB limit
  7244. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7245. "Host: " +
  7246. std::string(HOST) + ":" +
  7247. std::to_string(PORT) +
  7248. "\r\n"
  7249. "Connection: close\r\n"
  7250. "\r\n";
  7251. // Add 1MB payload (within 10MB limit)
  7252. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7253. request_without_content_length += medium_payload;
  7254. std::string response;
  7255. bool result = send_request(5, request_without_content_length, &response);
  7256. if (result) {
  7257. // Should get a proper HTTP response for payloads within limit
  7258. if (response.length() > 10) {
  7259. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7260. "10MB limit";
  7261. } else {
  7262. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7263. "Content-Length)";
  7264. }
  7265. } else {
  7266. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7267. }
  7268. }
  7269. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7270. // Test request without Content-Length header exceeding 10MB limit
  7271. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7272. "Host: " +
  7273. std::string(HOST) + ":" +
  7274. std::to_string(PORT) +
  7275. "\r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. // Add 12MB payload (exceeds 10MB limit)
  7279. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7280. request_without_content_length += large_payload;
  7281. std::string response;
  7282. bool result = send_request(10, request_without_content_length, &response);
  7283. if (!result) {
  7284. // Server should close connection due to payload limit
  7285. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7286. "(connection closed)";
  7287. } else {
  7288. // Check for error response
  7289. if (response.length() <= 10) {
  7290. SUCCEED()
  7291. << "Server closed connection for 12MB request exceeding 10MB limit";
  7292. } else {
  7293. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7294. response.find("Payload Too Large") != std::string::npos ||
  7295. response.find("400") != std::string::npos);
  7296. }
  7297. }
  7298. }
  7299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7300. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7301. // path.
  7302. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7303. Server svr;
  7304. const size_t LIMIT = 64 * 1024; // 64KB
  7305. svr.set_payload_max_length(LIMIT);
  7306. size_t total = 0;
  7307. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7308. const ContentReader &content_reader) {
  7309. content_reader([&](const char * /*data*/, size_t len) {
  7310. total += len;
  7311. return true;
  7312. });
  7313. res.status = 200;
  7314. res.set_content("stream_ok", "text/plain");
  7315. });
  7316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7317. auto se = detail::scope_exit([&] {
  7318. svr.stop();
  7319. thread.join();
  7320. ASSERT_FALSE(svr.is_running());
  7321. });
  7322. svr.wait_until_ready();
  7323. // Prepare 256KB raw data and gzip-compress it
  7324. std::string raw(256 * 1024, 'A');
  7325. std::string gz;
  7326. {
  7327. z_stream zs{};
  7328. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7329. Z_DEFAULT_STRATEGY);
  7330. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7331. zs.avail_in = static_cast<uInt>(raw.size());
  7332. char outbuf[4096];
  7333. int ret;
  7334. do {
  7335. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7336. zs.avail_out = sizeof(outbuf);
  7337. ret = deflate(&zs, Z_FINISH);
  7338. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7339. } while (ret != Z_STREAM_END);
  7340. deflateEnd(&zs);
  7341. }
  7342. Client cli(HOST, PORT);
  7343. cli.set_connection_timeout(std::chrono::seconds(5));
  7344. Headers headers = {{"Content-Encoding", "gzip"}};
  7345. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7346. "application/octet-stream");
  7347. ASSERT_TRUE(res);
  7348. // Server must reject oversized decompressed payloads with 413.
  7349. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7350. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7351. EXPECT_LE(total, LIMIT);
  7352. }
  7353. #endif
  7354. // Regression test for DoS vulnerability: a malicious server sending a response
  7355. // without Content-Length header must not cause unbounded memory consumption on
  7356. // the client side. The client should stop reading after a reasonable limit,
  7357. // similar to the server-side set_payload_max_length protection.
  7358. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7359. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7360. #ifndef _WIN32
  7361. signal(SIGPIPE, SIG_IGN);
  7362. #endif
  7363. auto server_thread = std::thread([] {
  7364. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7365. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7366. default_socket_options(srv);
  7367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7368. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7369. sockaddr_in addr{};
  7370. addr.sin_family = AF_INET;
  7371. addr.sin_port = htons(PORT + 2);
  7372. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7373. int opt = 1;
  7374. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7375. #ifdef _WIN32
  7376. reinterpret_cast<const char *>(&opt),
  7377. #else
  7378. &opt,
  7379. #endif
  7380. sizeof(opt));
  7381. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7382. ::listen(srv, 1);
  7383. sockaddr_in cli_addr{};
  7384. socklen_t cli_len = sizeof(cli_addr);
  7385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7386. if (cli != INVALID_SOCKET) {
  7387. char buf[4096];
  7388. ::recv(cli, buf, sizeof(buf), 0);
  7389. // Malicious response: no Content-Length, no chunked encoding
  7390. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7391. "Connection: close\r\n"
  7392. "\r\n";
  7393. ::send(cli,
  7394. #ifdef _WIN32
  7395. static_cast<const char *>(response_header.c_str()),
  7396. static_cast<int>(response_header.size()),
  7397. #else
  7398. response_header.c_str(), response_header.size(),
  7399. #endif
  7400. 0);
  7401. // Send 10MB of data
  7402. std::string chunk(64 * 1024, 'A');
  7403. size_t total_sent = 0;
  7404. while (total_sent < MALICIOUS_DATA_SIZE) {
  7405. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7406. auto sent = ::send(cli,
  7407. #ifdef _WIN32
  7408. static_cast<const char *>(chunk.c_str()),
  7409. static_cast<int>(to_send),
  7410. #else
  7411. chunk.c_str(), to_send,
  7412. #endif
  7413. 0);
  7414. if (sent <= 0) break;
  7415. total_sent += static_cast<size_t>(sent);
  7416. }
  7417. detail::close_socket(cli);
  7418. }
  7419. detail::close_socket(srv);
  7420. });
  7421. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7422. size_t total_read = 0;
  7423. {
  7424. Client cli("127.0.0.1", PORT + 2);
  7425. cli.set_read_timeout(5, 0);
  7426. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7427. auto stream = cli.open_stream("GET", "/malicious");
  7428. ASSERT_TRUE(stream.is_valid());
  7429. char buffer[64 * 1024];
  7430. ssize_t n;
  7431. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7432. total_read += static_cast<size_t>(n);
  7433. }
  7434. } // StreamHandle and Client destroyed here, closing the socket
  7435. server_thread.join();
  7436. // With set_payload_max_length, the client must stop reading before consuming
  7437. // all 10MB. The read loop should be cut off at or near the configured limit.
  7438. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7439. << "Client read " << total_read << " bytes, exceeding the configured "
  7440. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7441. }
  7442. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7443. // the entire response body without truncation.
  7444. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7445. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7446. #ifndef _WIN32
  7447. signal(SIGPIPE, SIG_IGN);
  7448. #endif
  7449. auto server_thread = std::thread([] {
  7450. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7451. default_socket_options(srv);
  7452. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7453. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7454. sockaddr_in addr{};
  7455. addr.sin_family = AF_INET;
  7456. addr.sin_port = htons(PORT + 2);
  7457. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7458. int opt = 1;
  7459. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7460. #ifdef _WIN32
  7461. reinterpret_cast<const char *>(&opt),
  7462. #else
  7463. &opt,
  7464. #endif
  7465. sizeof(opt));
  7466. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7467. ::listen(srv, 1);
  7468. sockaddr_in cli_addr{};
  7469. socklen_t cli_len = sizeof(cli_addr);
  7470. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7471. if (cli != INVALID_SOCKET) {
  7472. char buf[4096];
  7473. ::recv(cli, buf, sizeof(buf), 0);
  7474. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7475. "Connection: close\r\n"
  7476. "\r\n";
  7477. ::send(cli,
  7478. #ifdef _WIN32
  7479. static_cast<const char *>(response_header.c_str()),
  7480. static_cast<int>(response_header.size()),
  7481. #else
  7482. response_header.c_str(), response_header.size(),
  7483. #endif
  7484. 0);
  7485. std::string chunk(64 * 1024, 'A');
  7486. size_t total_sent = 0;
  7487. while (total_sent < DATA_SIZE) {
  7488. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7489. auto sent = ::send(cli,
  7490. #ifdef _WIN32
  7491. static_cast<const char *>(chunk.c_str()),
  7492. static_cast<int>(to_send),
  7493. #else
  7494. chunk.c_str(), to_send,
  7495. #endif
  7496. 0);
  7497. if (sent <= 0) break;
  7498. total_sent += static_cast<size_t>(sent);
  7499. }
  7500. #ifdef _WIN32
  7501. ::shutdown(cli, SD_SEND);
  7502. #else
  7503. ::shutdown(cli, SHUT_WR);
  7504. #endif
  7505. // Drain until the client closes its end, ensuring all data is delivered
  7506. char drain[1024];
  7507. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7508. detail::close_socket(cli);
  7509. }
  7510. detail::close_socket(srv);
  7511. });
  7512. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7513. size_t total_read = 0;
  7514. {
  7515. Client cli("127.0.0.1", PORT + 2);
  7516. cli.set_read_timeout(5, 0);
  7517. cli.set_payload_max_length(0); // 0 means no limit
  7518. auto stream = cli.open_stream("GET", "/data");
  7519. ASSERT_TRUE(stream.is_valid());
  7520. char buffer[64 * 1024];
  7521. ssize_t n;
  7522. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7523. total_read += static_cast<size_t>(n);
  7524. }
  7525. }
  7526. server_thread.join();
  7527. EXPECT_EQ(total_read, DATA_SIZE)
  7528. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7529. << " bytes without truncation, but only read " << total_read << " bytes.";
  7530. }
  7531. // Verify that content_receiver bypasses the default payload_max_length,
  7532. // allowing streaming downloads larger than 100MB without requiring an explicit
  7533. // set_payload_max_length call.
  7534. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7535. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7536. #ifndef _WIN32
  7537. signal(SIGPIPE, SIG_IGN);
  7538. #endif
  7539. auto server_thread = std::thread([] {
  7540. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7541. default_socket_options(srv);
  7542. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7543. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7544. sockaddr_in addr{};
  7545. addr.sin_family = AF_INET;
  7546. addr.sin_port = htons(PORT + 2);
  7547. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7548. int opt = 1;
  7549. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7550. #ifdef _WIN32
  7551. reinterpret_cast<const char *>(&opt),
  7552. #else
  7553. &opt,
  7554. #endif
  7555. sizeof(opt));
  7556. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7557. ::listen(srv, 1);
  7558. sockaddr_in cli_addr{};
  7559. socklen_t cli_len = sizeof(cli_addr);
  7560. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7561. if (cli != INVALID_SOCKET) {
  7562. char buf[4096];
  7563. ::recv(cli, buf, sizeof(buf), 0);
  7564. // Response with Content-Length larger than default 100MB limit
  7565. auto content_length = std::to_string(DATA_SIZE);
  7566. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7567. "Content-Length: " +
  7568. content_length +
  7569. "\r\n"
  7570. "Connection: close\r\n"
  7571. "\r\n";
  7572. ::send(cli,
  7573. #ifdef _WIN32
  7574. static_cast<const char *>(response_header.c_str()),
  7575. static_cast<int>(response_header.size()),
  7576. #else
  7577. response_header.c_str(), response_header.size(),
  7578. #endif
  7579. 0);
  7580. std::string chunk(64 * 1024, 'A');
  7581. size_t total_sent = 0;
  7582. while (total_sent < DATA_SIZE) {
  7583. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7584. auto sent = ::send(cli,
  7585. #ifdef _WIN32
  7586. static_cast<const char *>(chunk.c_str()),
  7587. static_cast<int>(to_send),
  7588. #else
  7589. chunk.c_str(), to_send,
  7590. #endif
  7591. 0);
  7592. if (sent <= 0) break;
  7593. total_sent += static_cast<size_t>(sent);
  7594. }
  7595. detail::close_socket(cli);
  7596. }
  7597. detail::close_socket(srv);
  7598. });
  7599. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7600. size_t total_received = 0;
  7601. {
  7602. Client cli("127.0.0.1", PORT + 2);
  7603. cli.set_read_timeout(10, 0);
  7604. // Do NOT call set_payload_max_length — use the default 100MB limit
  7605. auto res =
  7606. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7607. total_received += data_length;
  7608. return true;
  7609. });
  7610. ASSERT_TRUE(res);
  7611. EXPECT_EQ(StatusCode::OK_200, res->status);
  7612. }
  7613. server_thread.join();
  7614. EXPECT_EQ(total_received, DATA_SIZE)
  7615. << "With content_receiver, the client should read all " << DATA_SIZE
  7616. << " bytes despite the default 100MB payload_max_length, but only read "
  7617. << total_received << " bytes.";
  7618. }
  7619. // Verify that an explicit set_payload_max_length smaller than the response is
  7620. // enforced even when a content_receiver is used.
  7621. TEST(ClientVulnerabilityTest,
  7622. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7623. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7624. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7625. #ifndef _WIN32
  7626. signal(SIGPIPE, SIG_IGN);
  7627. #endif
  7628. auto server_thread = std::thread([] {
  7629. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7630. default_socket_options(srv);
  7631. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7632. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7633. sockaddr_in addr{};
  7634. addr.sin_family = AF_INET;
  7635. addr.sin_port = htons(PORT + 2);
  7636. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7637. int opt = 1;
  7638. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7639. #ifdef _WIN32
  7640. reinterpret_cast<const char *>(&opt),
  7641. #else
  7642. &opt,
  7643. #endif
  7644. sizeof(opt));
  7645. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7646. ::listen(srv, 1);
  7647. sockaddr_in cli_addr{};
  7648. socklen_t cli_len = sizeof(cli_addr);
  7649. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7650. if (cli != INVALID_SOCKET) {
  7651. char buf[4096];
  7652. ::recv(cli, buf, sizeof(buf), 0);
  7653. auto content_length = std::to_string(DATA_SIZE);
  7654. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7655. "Content-Length: " +
  7656. content_length +
  7657. "\r\n"
  7658. "Connection: close\r\n"
  7659. "\r\n";
  7660. ::send(cli,
  7661. #ifdef _WIN32
  7662. static_cast<const char *>(response_header.c_str()),
  7663. static_cast<int>(response_header.size()),
  7664. #else
  7665. response_header.c_str(), response_header.size(),
  7666. #endif
  7667. 0);
  7668. std::string chunk(64 * 1024, 'A');
  7669. size_t total_sent = 0;
  7670. while (total_sent < DATA_SIZE) {
  7671. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7672. auto sent = ::send(cli,
  7673. #ifdef _WIN32
  7674. static_cast<const char *>(chunk.c_str()),
  7675. static_cast<int>(to_send),
  7676. #else
  7677. chunk.c_str(), to_send,
  7678. #endif
  7679. 0);
  7680. if (sent <= 0) break;
  7681. total_sent += static_cast<size_t>(sent);
  7682. }
  7683. detail::close_socket(cli);
  7684. }
  7685. detail::close_socket(srv);
  7686. });
  7687. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7688. size_t total_received = 0;
  7689. {
  7690. Client cli("127.0.0.1", PORT + 2);
  7691. cli.set_read_timeout(10, 0);
  7692. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7693. auto res =
  7694. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7695. total_received += data_length;
  7696. return true;
  7697. });
  7698. // Should fail because 200MB exceeds the explicit 150MB limit
  7699. EXPECT_FALSE(res);
  7700. }
  7701. server_thread.join();
  7702. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7703. << "Client with content_receiver should respect the explicit "
  7704. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7705. << total_received << " bytes.";
  7706. }
  7707. // Verify that an explicit set_payload_max_length larger than the response
  7708. // allows the content_receiver to read all data successfully.
  7709. TEST(ClientVulnerabilityTest,
  7710. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7711. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7712. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7713. #ifndef _WIN32
  7714. signal(SIGPIPE, SIG_IGN);
  7715. #endif
  7716. auto server_thread = std::thread([] {
  7717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7718. default_socket_options(srv);
  7719. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7720. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7721. sockaddr_in addr{};
  7722. addr.sin_family = AF_INET;
  7723. addr.sin_port = htons(PORT + 2);
  7724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7725. int opt = 1;
  7726. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7727. #ifdef _WIN32
  7728. reinterpret_cast<const char *>(&opt),
  7729. #else
  7730. &opt,
  7731. #endif
  7732. sizeof(opt));
  7733. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7734. ::listen(srv, 1);
  7735. sockaddr_in cli_addr{};
  7736. socklen_t cli_len = sizeof(cli_addr);
  7737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7738. if (cli != INVALID_SOCKET) {
  7739. char buf[4096];
  7740. ::recv(cli, buf, sizeof(buf), 0);
  7741. auto content_length = std::to_string(DATA_SIZE);
  7742. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7743. "Content-Length: " +
  7744. content_length +
  7745. "\r\n"
  7746. "Connection: close\r\n"
  7747. "\r\n";
  7748. ::send(cli,
  7749. #ifdef _WIN32
  7750. static_cast<const char *>(response_header.c_str()),
  7751. static_cast<int>(response_header.size()),
  7752. #else
  7753. response_header.c_str(), response_header.size(),
  7754. #endif
  7755. 0);
  7756. std::string chunk(64 * 1024, 'A');
  7757. size_t total_sent = 0;
  7758. while (total_sent < DATA_SIZE) {
  7759. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7760. auto sent = ::send(cli,
  7761. #ifdef _WIN32
  7762. static_cast<const char *>(chunk.c_str()),
  7763. static_cast<int>(to_send),
  7764. #else
  7765. chunk.c_str(), to_send,
  7766. #endif
  7767. 0);
  7768. if (sent <= 0) break;
  7769. total_sent += static_cast<size_t>(sent);
  7770. }
  7771. #ifdef _WIN32
  7772. ::shutdown(cli, SD_SEND);
  7773. #else
  7774. ::shutdown(cli, SHUT_WR);
  7775. #endif
  7776. char drain[1024];
  7777. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7778. detail::close_socket(cli);
  7779. }
  7780. detail::close_socket(srv);
  7781. });
  7782. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7783. size_t total_received = 0;
  7784. {
  7785. Client cli("127.0.0.1", PORT + 2);
  7786. cli.set_read_timeout(10, 0);
  7787. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7788. auto res =
  7789. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7790. total_received += data_length;
  7791. return true;
  7792. });
  7793. ASSERT_TRUE(res);
  7794. EXPECT_EQ(StatusCode::OK_200, res->status);
  7795. }
  7796. server_thread.join();
  7797. EXPECT_EQ(total_received, DATA_SIZE)
  7798. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7799. << " bytes (larger than " << DATA_SIZE
  7800. << " bytes response), content_receiver should read all data, but only "
  7801. "read "
  7802. << total_received << " bytes.";
  7803. }
  7804. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7805. // Regression test for "zip bomb" attack on the client side: a malicious server
  7806. // sends a small gzip-compressed response that decompresses to a huge payload.
  7807. // The client must enforce payload_max_length on the decompressed size.
  7808. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7809. constexpr size_t DECOMPRESSED_SIZE =
  7810. 10 * 1024 * 1024; // 10MB after decompression
  7811. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7812. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7813. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7814. std::string compressed;
  7815. {
  7816. httplib::detail::gzip_compressor compressor;
  7817. bool ok =
  7818. compressor.compress(uncompressed.data(), uncompressed.size(),
  7819. /*last=*/true, [&](const char *buf, size_t len) {
  7820. compressed.append(buf, len);
  7821. return true;
  7822. });
  7823. ASSERT_TRUE(ok);
  7824. }
  7825. // Sanity: compressed data should be much smaller than the decompressed size
  7826. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7827. #ifndef _WIN32
  7828. signal(SIGPIPE, SIG_IGN);
  7829. #endif
  7830. // Set up the listening socket in the main thread so the server is guaranteed
  7831. // to be ready before the client connects (eliminates race condition).
  7832. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7833. default_socket_options(srv);
  7834. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7836. sockaddr_in addr{};
  7837. addr.sin_family = AF_INET;
  7838. addr.sin_port = htons(PORT + 3);
  7839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7840. int opt = 1;
  7841. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7842. #ifdef _WIN32
  7843. reinterpret_cast<const char *>(&opt),
  7844. #else
  7845. &opt,
  7846. #endif
  7847. sizeof(opt));
  7848. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7849. ASSERT_EQ(0, ::listen(srv, 1));
  7850. auto server_thread = std::thread([&compressed, srv] {
  7851. sockaddr_in cli_addr{};
  7852. socklen_t cli_len = sizeof(cli_addr);
  7853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7854. if (cli != INVALID_SOCKET) {
  7855. // Read the full HTTP request (until \r\n\r\n)
  7856. char buf[4096];
  7857. size_t total = 0;
  7858. while (total < sizeof(buf)) {
  7859. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7860. if (n <= 0) break;
  7861. total += static_cast<size_t>(n);
  7862. // Check for end of headers
  7863. if (total >= 4) {
  7864. std::string req(buf, total);
  7865. if (req.find("\r\n\r\n") != std::string::npos) break;
  7866. }
  7867. }
  7868. // Malicious response: gzip-compressed body, no Content-Length
  7869. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7870. "Content-Encoding: gzip\r\n"
  7871. "Connection: close\r\n"
  7872. "\r\n";
  7873. ::send(cli,
  7874. #ifdef _WIN32
  7875. static_cast<const char *>(response_header.c_str()),
  7876. static_cast<int>(response_header.size()),
  7877. #else
  7878. response_header.c_str(), response_header.size(),
  7879. #endif
  7880. 0);
  7881. // Send the compressed payload (small on the wire, huge when decompressed)
  7882. size_t total_sent = 0;
  7883. while (total_sent < compressed.size()) {
  7884. auto to_send = std::min(compressed.size() - total_sent,
  7885. static_cast<size_t>(64 * 1024));
  7886. auto sent =
  7887. ::send(cli,
  7888. #ifdef _WIN32
  7889. static_cast<const char *>(compressed.c_str() + total_sent),
  7890. static_cast<int>(to_send),
  7891. #else
  7892. compressed.c_str() + total_sent, to_send,
  7893. #endif
  7894. 0);
  7895. if (sent <= 0) break;
  7896. total_sent += static_cast<size_t>(sent);
  7897. }
  7898. detail::close_socket(cli);
  7899. }
  7900. });
  7901. auto se = detail::scope_exit([&] {
  7902. detail::close_socket(srv);
  7903. server_thread.join();
  7904. });
  7905. size_t total_decompressed = 0;
  7906. {
  7907. Client cli("127.0.0.1", PORT + 3);
  7908. cli.set_read_timeout(5, 0);
  7909. cli.set_decompress(true);
  7910. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7911. auto stream = cli.open_stream("GET", "/zipbomb");
  7912. ASSERT_TRUE(stream.is_valid());
  7913. char buffer[64 * 1024];
  7914. ssize_t n;
  7915. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7916. total_decompressed += static_cast<size_t>(n);
  7917. }
  7918. }
  7919. // The decompressed size must be capped by payload_max_length. Without
  7920. // protection, the client would decompress the full 10MB from a tiny
  7921. // compressed payload, enabling a zip bomb DoS attack.
  7922. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  7923. << "Client decompressed " << total_decompressed
  7924. << " bytes from a gzip response. The decompressed size should be "
  7925. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  7926. }
  7927. #endif
  7928. TEST(HostAndPortPropertiesTest, NoSSL) {
  7929. httplib::Client cli("www.google.com", 1234);
  7930. ASSERT_EQ("www.google.com", cli.host());
  7931. ASSERT_EQ(1234, cli.port());
  7932. }
  7933. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7934. httplib::Client cli("www.google.com:1234");
  7935. ASSERT_EQ("www.google.com", cli.host());
  7936. ASSERT_EQ(1234, cli.port());
  7937. }
  7938. #ifdef CPPHTTPLIB_SSL_ENABLED
  7939. TEST(HostAndPortPropertiesTest, SSL) {
  7940. httplib::SSLClient cli("www.google.com");
  7941. ASSERT_EQ("www.google.com", cli.host());
  7942. ASSERT_EQ(443, cli.port());
  7943. }
  7944. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  7945. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7946. std::string cert;
  7947. read_file(CA_CERT_FILE, cert);
  7948. httplib::SSLClient httplib_client("www.google.com");
  7949. // Load CA store first time
  7950. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7951. // Load CA store second time (update)
  7952. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7953. // Verify client is still valid and can make connections
  7954. httplib_client.enable_server_certificate_verification(true);
  7955. auto res = httplib_client.Get("/");
  7956. ASSERT_TRUE(res);
  7957. // Google may return 200 or 301 depending on various factors
  7958. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7959. res->status == StatusCode::MovedPermanently_301);
  7960. }
  7961. TEST(SSLClientTest, ServerNameIndication_Online) {
  7962. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7963. auto host = "httpcan.org";
  7964. auto path = std::string{"/get"};
  7965. #else
  7966. auto host = "nghttp2.org";
  7967. auto path = std::string{"/httpbin/get"};
  7968. #endif
  7969. SSLClient cli(host, 443);
  7970. auto res = cli.Get(path);
  7971. ASSERT_TRUE(res);
  7972. ASSERT_EQ(StatusCode::OK_200, res->status);
  7973. }
  7974. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7975. // Use a site that will cause SSL verification failure due to self-signed cert
  7976. SSLClient cli("self-signed.badssl.com", 443);
  7977. cli.enable_server_certificate_verification(true);
  7978. auto res = cli.Get("/");
  7979. ASSERT_TRUE(!res);
  7980. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7981. // Verify backend error is captured for SSLServerVerification
  7982. // This occurs when certificate verification fails
  7983. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7984. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7985. EXPECT_NE(0UL, res.ssl_backend_error());
  7986. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7987. // For OpenSSL, ssl_error is 0 for verification errors
  7988. EXPECT_EQ(0, res.ssl_error());
  7989. #if !defined(_WIN32) || \
  7990. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  7991. // On non-Windows or when Windows Schannel is disabled, the error comes
  7992. // from OpenSSL's verification
  7993. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7994. res.ssl_backend_error());
  7995. #endif
  7996. #endif
  7997. }
  7998. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7999. // Use a site where hostname doesn't match the certificate
  8000. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8001. SSLClient cli("wrong.host.badssl.com", 443);
  8002. cli.enable_server_certificate_verification(true);
  8003. cli.enable_server_hostname_verification(true);
  8004. auto res = cli.Get("/");
  8005. ASSERT_TRUE(!res);
  8006. // The error type depends on when hostname verification occurs:
  8007. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8008. // - Mbed TLS: SSLServerVerification (during handshake)
  8009. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8010. res.error() == Error::SSLServerVerification);
  8011. // Verify backend error is captured for hostname verification failure
  8012. EXPECT_NE(0UL, res.ssl_backend_error());
  8013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8014. // For OpenSSL, ssl_error is 0 for verification errors
  8015. EXPECT_EQ(0, res.ssl_error());
  8016. #if !defined(_WIN32) || \
  8017. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8018. // On non-Windows or when Windows Schannel is disabled, the error comes
  8019. // from OpenSSL's hostname verification
  8020. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8021. res.ssl_backend_error());
  8022. #endif
  8023. #endif
  8024. }
  8025. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8026. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8027. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8028. SSLClient cli("www.google.com", 443);
  8029. cli.enable_server_certificate_verification(true);
  8030. auto res = cli.Get("/");
  8031. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8032. }
  8033. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8034. SSLClient cli("www.google.com", 443);
  8035. cli.enable_server_certificate_verification(true);
  8036. cli.enable_windows_certificate_verification(false);
  8037. auto res = cli.Get("/");
  8038. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8039. }
  8040. #endif
  8041. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8042. Client cli("https://google.com");
  8043. auto res = cli.Get("/");
  8044. ASSERT_TRUE(res);
  8045. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8046. }
  8047. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8048. SSLClient cli("google.com");
  8049. cli.set_ca_cert_path(CA_CERT_FILE);
  8050. auto res = cli.Get("/");
  8051. ASSERT_TRUE(res);
  8052. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8053. }
  8054. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8055. SSLClient cli("google.com");
  8056. cli.enable_server_certificate_verification(true);
  8057. cli.set_ca_cert_path("hello");
  8058. auto res = cli.Get("/");
  8059. ASSERT_TRUE(!res);
  8060. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8061. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8062. // should be set
  8063. EXPECT_EQ(0, res.ssl_error());
  8064. // Verify backend error is captured for SSLLoadingCerts
  8065. // This error occurs when loading CA certificates fails
  8066. EXPECT_NE(0UL, res.ssl_backend_error());
  8067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8068. // OpenSSL specific error codes:
  8069. // > openssl errstr 0x80000002
  8070. // error:80000002:system library::No such file or directory
  8071. // > openssl errstr 0xA000126
  8072. // error:0A000126:SSL routines::unexpected eof while reading
  8073. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8074. res.ssl_backend_error() == 0xA000126);
  8075. #endif
  8076. }
  8077. TEST(SSLClientTest, ServerCertificateVerification4) {
  8078. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8079. ASSERT_TRUE(svr.is_valid());
  8080. svr.Get("/test", [&](const Request &, Response &res) {
  8081. res.set_content("test", "text/plain");
  8082. svr.stop();
  8083. ASSERT_TRUE(true);
  8084. });
  8085. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8086. auto se = detail::scope_exit([&] {
  8087. t.join();
  8088. ASSERT_FALSE(svr.is_running());
  8089. });
  8090. svr.wait_until_ready();
  8091. SSLClient cli("127.0.0.1", PORT);
  8092. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8093. cli.enable_server_certificate_verification(true);
  8094. cli.set_connection_timeout(30);
  8095. auto res = cli.Get("/test");
  8096. ASSERT_TRUE(res);
  8097. ASSERT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8100. std::string cert;
  8101. read_file(CA_CERT_FILE, cert);
  8102. SSLClient cli("google.com");
  8103. cli.load_ca_cert_store(cert.data(), cert.size());
  8104. const auto res = cli.Get("/");
  8105. ASSERT_TRUE(res);
  8106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8107. }
  8108. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8109. // clang-format off
  8110. static constexpr char cert[] =
  8111. "GlobalSign Root CA\n"
  8112. "==================\n"
  8113. "-----BEGIN CERTIFICATE-----\n"
  8114. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8115. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8116. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8117. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8118. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8119. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8120. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8121. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8122. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8123. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8124. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8125. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8126. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8127. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8128. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8129. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8130. "-----END CERTIFICATE-----\n";
  8131. // clang-format on
  8132. SSLClient cli("google.com");
  8133. cli.load_ca_cert_store(cert, sizeof(cert));
  8134. const auto res = cli.Get("/");
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8137. }
  8138. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8139. SSLClient cli("www.youtube.com");
  8140. cli.set_ca_cert_path(CA_CERT_FILE);
  8141. cli.enable_server_certificate_verification(true);
  8142. cli.set_follow_location(true);
  8143. auto res = cli.Get("/");
  8144. ASSERT_TRUE(res);
  8145. ASSERT_EQ(StatusCode::OK_200, res->status);
  8146. }
  8147. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8148. SSLClient cli("wWw.YouTube.Com");
  8149. cli.set_ca_cert_path(CA_CERT_FILE);
  8150. cli.enable_server_certificate_verification(true);
  8151. cli.enable_server_hostname_verification(true);
  8152. cli.set_follow_location(true);
  8153. auto res = cli.Get("/");
  8154. ASSERT_TRUE(res);
  8155. ASSERT_EQ(StatusCode::OK_200, res->status);
  8156. }
  8157. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8158. SSLClient cli("gOoGlE.COm");
  8159. cli.enable_server_certificate_verification(true);
  8160. cli.enable_server_hostname_verification(true);
  8161. cli.set_follow_location(true);
  8162. auto res = cli.Get("/");
  8163. ASSERT_TRUE(res);
  8164. ASSERT_EQ(StatusCode::OK_200, res->status);
  8165. }
  8166. TEST(SSLClientTest, Issue2004_Online) {
  8167. Client client("https://google.com");
  8168. client.set_follow_location(true);
  8169. auto res = client.Get("/");
  8170. ASSERT_TRUE(res);
  8171. ASSERT_EQ(StatusCode::OK_200, res->status);
  8172. auto body = res->body;
  8173. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8174. }
  8175. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8176. // Create SSLClient with invalid cert/key to make is_valid() return false
  8177. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8178. "nonexistent_key.pem");
  8179. // is_valid() should be false due to cert loading failure
  8180. ASSERT_FALSE(cli.is_valid());
  8181. auto res = cli.Get("/");
  8182. ASSERT_FALSE(res);
  8183. EXPECT_EQ(Error::SSLConnection, res.error());
  8184. }
  8185. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8186. // Test for Issue #2251: SSL error not properly reported when client cert
  8187. // and key paths are swapped or mismatched
  8188. // This simulates the scenario where user accidentally swaps the cert and key
  8189. // files
  8190. // Using client cert file as private key and vice versa (completely wrong)
  8191. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8192. // Should fail validation due to cert/key mismatch
  8193. ASSERT_FALSE(cli.is_valid());
  8194. // Attempt to make a request should fail with proper error
  8195. auto res = cli.Get("/");
  8196. ASSERT_FALSE(res);
  8197. EXPECT_EQ(Error::SSLConnection, res.error());
  8198. // SSL error should be recorded in the Result object (this is the key fix for
  8199. // Issue #2251)
  8200. auto backend_error = res.ssl_backend_error();
  8201. EXPECT_NE(0u, backend_error);
  8202. }
  8203. // Tests cert/key mismatch detection at the TLS context level
  8204. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8205. // Test that using mismatched cert/key causes connection failure.
  8206. // We verify this at the SSLClient level rather than through internal
  8207. // TLS API functions.
  8208. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8209. cli.enable_server_certificate_verification(false);
  8210. cli.set_connection_timeout(2);
  8211. // The mismatch should cause a connection or handshake error
  8212. auto res = cli.Get("/test");
  8213. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8214. // Either way, the request should fail
  8215. EXPECT_FALSE(res);
  8216. }
  8217. #endif
  8218. #if 0
  8219. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8220. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8221. ASSERT_TRUE(cli != nullptr);
  8222. cli->set_address_family(AF_INET6);
  8223. cli->set_interface("en0");
  8224. auto res = cli->Get("/get");
  8225. ASSERT_TRUE(res);
  8226. ASSERT_EQ(StatusCode::OK_200, res->status);
  8227. }
  8228. #endif
  8229. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8230. #ifdef CPPHTTPLIB_SSL_ENABLED
  8231. void ClientCertPresent(
  8232. const std::string &client_cert_file,
  8233. const std::string &client_private_key_file,
  8234. const std::string &client_encrypted_private_key_pass = std::string()) {
  8235. using namespace httplib::tls;
  8236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8237. CLIENT_CA_CERT_DIR);
  8238. ASSERT_TRUE(svr.is_valid());
  8239. svr.Get("/test", [&](const Request &req, Response &res) {
  8240. res.set_content("test", "text/plain");
  8241. auto cert = req.peer_cert();
  8242. ASSERT_TRUE(static_cast<bool>(cert));
  8243. std::string common_name = cert.subject_cn();
  8244. EXPECT_EQ("Common Name", common_name);
  8245. });
  8246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8247. auto se = detail::scope_exit([&] {
  8248. svr.stop();
  8249. t.join();
  8250. ASSERT_FALSE(svr.is_running());
  8251. });
  8252. svr.wait_until_ready();
  8253. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8254. client_encrypted_private_key_pass);
  8255. cli.enable_server_certificate_verification(false);
  8256. cli.set_connection_timeout(30);
  8257. auto res = cli.Get("/test");
  8258. ASSERT_TRUE(res);
  8259. ASSERT_EQ(StatusCode::OK_200, res->status);
  8260. }
  8261. TEST(SSLClientServerTest, ClientCertPresent) {
  8262. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8263. }
  8264. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8265. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8266. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8267. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8268. }
  8269. // PEM memory-based constructor tests (works with all TLS backends)
  8270. void PemMemoryClientCertPresent(
  8271. const std::string &client_cert_file,
  8272. const std::string &client_private_key_file,
  8273. const std::string &client_encrypted_private_key_pass = std::string()) {
  8274. // Read PEM files into memory
  8275. std::string server_cert_pem, server_key_pem;
  8276. std::string client_ca_pem;
  8277. std::string client_cert_pem, client_key_pem;
  8278. read_file(SERVER_CERT_FILE, server_cert_pem);
  8279. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8280. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8281. read_file(client_cert_file, client_cert_pem);
  8282. read_file(client_private_key_file, client_key_pem);
  8283. // Create server with PEM memory
  8284. SSLServer::PemMemory server_pem = {
  8285. server_cert_pem.c_str(),
  8286. server_cert_pem.size(),
  8287. server_key_pem.c_str(),
  8288. server_key_pem.size(),
  8289. client_ca_pem.c_str(),
  8290. client_ca_pem.size(),
  8291. nullptr // no password for server key
  8292. };
  8293. SSLServer svr(server_pem);
  8294. ASSERT_TRUE(svr.is_valid());
  8295. svr.Get("/test", [&](const Request &, Response &res) {
  8296. res.set_content("test", "text/plain");
  8297. });
  8298. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8299. auto se = detail::scope_exit([&] {
  8300. svr.stop();
  8301. t.join();
  8302. ASSERT_FALSE(svr.is_running());
  8303. });
  8304. svr.wait_until_ready();
  8305. // Create client with PEM memory
  8306. const char *password = client_encrypted_private_key_pass.empty()
  8307. ? nullptr
  8308. : client_encrypted_private_key_pass.c_str();
  8309. SSLClient::PemMemory client_pem = {
  8310. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8311. client_key_pem.size(), password};
  8312. SSLClient cli(HOST, PORT, client_pem);
  8313. cli.enable_server_certificate_verification(false);
  8314. cli.set_connection_timeout(30);
  8315. auto res = cli.Get("/test");
  8316. ASSERT_TRUE(res);
  8317. ASSERT_EQ(StatusCode::OK_200, res->status);
  8318. }
  8319. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8320. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8321. }
  8322. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8323. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8324. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8325. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8326. }
  8327. TEST(SSLClientServerTest, ClientCertMissing) {
  8328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8329. CLIENT_CA_CERT_DIR);
  8330. ASSERT_TRUE(svr.is_valid());
  8331. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8332. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8333. auto se = detail::scope_exit([&] {
  8334. svr.stop();
  8335. t.join();
  8336. ASSERT_FALSE(svr.is_running());
  8337. });
  8338. svr.wait_until_ready();
  8339. SSLClient cli(HOST, PORT);
  8340. cli.set_connection_timeout(30);
  8341. auto res = cli.Get("/test");
  8342. ASSERT_TRUE(!res);
  8343. // When client cert is missing and server requires it, connection fails
  8344. // Error type depends on backend implementation
  8345. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8346. res.error() == Error::SSLConnection);
  8347. // Verify backend error is captured
  8348. // Note: This test may have different error codes depending on the exact
  8349. // verification failure
  8350. EXPECT_NE(0UL, res.ssl_backend_error());
  8351. }
  8352. TEST(SSLClientServerTest, TrustDirOptional) {
  8353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8354. ASSERT_TRUE(svr.is_valid());
  8355. svr.Get("/test", [&](const Request &, Response &res) {
  8356. res.set_content("test", "text/plain");
  8357. });
  8358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8366. cli.enable_server_certificate_verification(false);
  8367. cli.set_connection_timeout(30);
  8368. auto res = cli.Get("/test");
  8369. ASSERT_TRUE(res);
  8370. ASSERT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8373. class NoListenSSLServer : public SSLServer {
  8374. public:
  8375. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8376. const char *client_ca_cert_file_path,
  8377. const char *client_ca_cert_dir_path = nullptr)
  8378. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8379. client_ca_cert_dir_path),
  8380. stop_(false) {}
  8381. std::atomic_bool stop_;
  8382. private:
  8383. bool process_and_close_socket(socket_t /*sock*/) override {
  8384. // Don't create SSL context
  8385. while (!stop_.load()) {
  8386. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8387. }
  8388. return true;
  8389. }
  8390. };
  8391. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8392. CLIENT_CA_CERT_FILE);
  8393. ASSERT_TRUE(svr.is_valid());
  8394. svr.Get("/test", [&](const Request &, Response &res) {
  8395. res.set_content("test", "text/plain");
  8396. });
  8397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8398. auto se = detail::scope_exit([&] {
  8399. svr.stop_ = true;
  8400. svr.stop();
  8401. t.join();
  8402. ASSERT_FALSE(svr.is_running());
  8403. });
  8404. svr.wait_until_ready();
  8405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8406. cli.enable_server_certificate_verification(false);
  8407. cli.set_connection_timeout(1);
  8408. auto res = cli.Get("/test");
  8409. ASSERT_TRUE(!res);
  8410. EXPECT_EQ(Error::SSLConnection, res.error());
  8411. // Timeout results in WantRead error code (maps to backend-specific value)
  8412. EXPECT_NE(0, res.ssl_error());
  8413. }
  8414. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8415. // Test SSLServer with client certificate verification using the standard
  8416. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8418. CLIENT_CA_CERT_DIR);
  8419. ASSERT_TRUE(svr.is_valid());
  8420. svr.Get("/test", [&](const Request &req, Response &res) {
  8421. res.set_content("test", "text/plain");
  8422. auto cert = req.peer_cert();
  8423. ASSERT_TRUE(static_cast<bool>(cert));
  8424. auto common_name = cert.subject_cn();
  8425. EXPECT_EQ("Common Name", common_name);
  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. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8435. cli.enable_server_certificate_verification(false);
  8436. cli.set_connection_timeout(30);
  8437. auto res = cli.Get("/test");
  8438. ASSERT_TRUE(res);
  8439. ASSERT_EQ(StatusCode::OK_200, res->status);
  8440. }
  8441. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8442. // Verifies that wildcard matching and exact matching work consistently
  8443. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8444. using namespace httplib::tls;
  8445. // We need a running server to test against
  8446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8447. ASSERT_TRUE(svr.is_valid());
  8448. svr.Get("/test", [](const Request &, Response &res) {
  8449. res.set_content("ok", "text/plain");
  8450. });
  8451. thread t([&]() { svr.listen(HOST, PORT); });
  8452. auto se = detail::scope_exit([&] {
  8453. svr.stop();
  8454. t.join();
  8455. });
  8456. svr.wait_until_ready();
  8457. bool verify_callback_called = false;
  8458. bool verify_result_wrong = false;
  8459. SSLClient cli(HOST, PORT);
  8460. cli.enable_server_certificate_verification(true);
  8461. cli.set_ca_cert_path(CA_CERT_FILE);
  8462. cli.set_connection_timeout(5);
  8463. // Note: Test certificate has CN="Common Name", not "localhost"
  8464. bool verify_result_cn = false;
  8465. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8466. verify_callback_called = true;
  8467. if (!ctx.cert) return false;
  8468. // Test 1: "Common Name" should match (our test server cert CN)
  8469. verify_result_cn = ctx.check_hostname("Common Name");
  8470. // Test 2: wrong hostname should not match
  8471. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8472. return true; // Accept for the purpose of this test
  8473. });
  8474. auto res = cli.Get("/test");
  8475. // The request may succeed or fail depending on cert configuration
  8476. // but the callback should have been called
  8477. ASSERT_TRUE(verify_callback_called)
  8478. << "Verify callback should have been called";
  8479. // CN="Common Name" should match our test certificate
  8480. EXPECT_TRUE(verify_result_cn)
  8481. << "verify_hostname should match 'Common Name' (certificate CN)";
  8482. // Wrong hostname should not match
  8483. EXPECT_FALSE(verify_result_wrong)
  8484. << "verify_hostname should not match 'wronghost.example.com'";
  8485. }
  8486. #endif
  8487. // mbedTLS-specific callback constructor test
  8488. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8489. #ifdef CPPHTTPLIB_SSL_ENABLED
  8490. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8492. ASSERT_TRUE(svr.is_valid());
  8493. // Set up a handler to verify client certificate is present
  8494. bool client_cert_verified = false;
  8495. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8496. // Verify that client certificate was provided
  8497. client_cert_verified = true;
  8498. res.set_content("success", "text/plain");
  8499. });
  8500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8501. auto se = detail::scope_exit([&] {
  8502. svr.stop();
  8503. t.join();
  8504. ASSERT_FALSE(svr.is_running());
  8505. });
  8506. svr.wait_until_ready();
  8507. // Client with certificate
  8508. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8509. cli.enable_server_certificate_verification(false);
  8510. cli.set_connection_timeout(30);
  8511. auto res = cli.Get("/test");
  8512. ASSERT_TRUE(res);
  8513. ASSERT_EQ(StatusCode::OK_200, res->status);
  8514. ASSERT_TRUE(client_cert_verified);
  8515. EXPECT_EQ("success", res->body);
  8516. }
  8517. #endif
  8518. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8519. // backends
  8520. #ifdef CPPHTTPLIB_SSL_ENABLED
  8521. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8522. using namespace httplib::tls;
  8523. // Test that when client CA cert file is provided,
  8524. // the server properly requests and validates client certificates
  8525. // Create a server with client authentication
  8526. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8527. ASSERT_TRUE(svr.is_valid());
  8528. bool handler_called = false;
  8529. svr.Get("/test", [&](const Request &req, Response &res) {
  8530. handler_called = true;
  8531. // Verify that a client certificate was provided
  8532. auto cert = req.peer_cert();
  8533. ASSERT_TRUE(static_cast<bool>(cert));
  8534. // Get the issuer name
  8535. std::string issuer_str = cert.issuer_name();
  8536. ASSERT_FALSE(issuer_str.empty());
  8537. // The client certificate should be issued by our test CA
  8538. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8539. res.set_content("authenticated", "text/plain");
  8540. });
  8541. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8542. auto se = detail::scope_exit([&] {
  8543. svr.stop();
  8544. t.join();
  8545. ASSERT_FALSE(svr.is_running());
  8546. });
  8547. svr.wait_until_ready();
  8548. // Connect with a client certificate issued by the CA
  8549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8550. cli.enable_server_certificate_verification(false);
  8551. cli.set_connection_timeout(30);
  8552. auto res = cli.Get("/test");
  8553. ASSERT_TRUE(res);
  8554. ASSERT_EQ(StatusCode::OK_200, res->status);
  8555. ASSERT_TRUE(handler_called);
  8556. EXPECT_EQ("authenticated", res->body);
  8557. }
  8558. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8559. using namespace httplib::tls;
  8560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8561. ASSERT_TRUE(svr.is_valid());
  8562. svr.Get("/test", [](const Request &, Response &res) {
  8563. res.set_content("ok", "text/plain");
  8564. });
  8565. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8566. auto se = detail::scope_exit([&] {
  8567. svr.stop();
  8568. t.join();
  8569. });
  8570. svr.wait_until_ready();
  8571. SSLClient cli(HOST, PORT);
  8572. cli.enable_server_certificate_verification(false);
  8573. cli.set_connection_timeout(30);
  8574. bool cert_checked = false;
  8575. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8576. if (ctx.cert) {
  8577. auto sans = ctx.sans();
  8578. // Test certificate may or may not have SANs - just verify the API
  8579. // works If SANs exist, verify the types are valid
  8580. for (const auto &san : sans) {
  8581. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8582. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8583. san.type == SanType::OTHER);
  8584. EXPECT_FALSE(san.value.empty());
  8585. }
  8586. cert_checked = true;
  8587. }
  8588. return true;
  8589. });
  8590. auto res = cli.Get("/test");
  8591. ASSERT_TRUE(res);
  8592. EXPECT_TRUE(cert_checked);
  8593. }
  8594. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8595. using namespace httplib::tls;
  8596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8597. ASSERT_TRUE(svr.is_valid());
  8598. svr.Get("/test", [](const Request &, Response &res) {
  8599. res.set_content("ok", "text/plain");
  8600. });
  8601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8602. auto se = detail::scope_exit([&] {
  8603. svr.stop();
  8604. t.join();
  8605. });
  8606. svr.wait_until_ready();
  8607. SSLClient cli(HOST, PORT);
  8608. cli.enable_server_certificate_verification(false);
  8609. cli.set_connection_timeout(30);
  8610. bool validity_checked = false;
  8611. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8612. if (ctx.cert) {
  8613. time_t not_before = 0, not_after = 0;
  8614. bool result = ctx.validity(not_before, not_after);
  8615. EXPECT_TRUE(result);
  8616. // Verify that not_before < now < not_after for a valid cert
  8617. time_t now = time(nullptr);
  8618. EXPECT_LT(not_before, now);
  8619. EXPECT_GT(not_after, now);
  8620. validity_checked = true;
  8621. }
  8622. return true;
  8623. });
  8624. auto res = cli.Get("/test");
  8625. ASSERT_TRUE(res);
  8626. EXPECT_TRUE(validity_checked);
  8627. }
  8628. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8629. using namespace httplib::tls;
  8630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8631. ASSERT_TRUE(svr.is_valid());
  8632. svr.Get("/test", [](const Request &, Response &res) {
  8633. res.set_content("ok", "text/plain");
  8634. });
  8635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8636. auto se = detail::scope_exit([&] {
  8637. svr.stop();
  8638. t.join();
  8639. });
  8640. svr.wait_until_ready();
  8641. SSLClient cli(HOST, PORT);
  8642. cli.enable_server_certificate_verification(false);
  8643. cli.set_connection_timeout(30);
  8644. bool serial_checked = false;
  8645. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8646. if (ctx.cert) {
  8647. std::string serial = ctx.serial();
  8648. EXPECT_FALSE(serial.empty());
  8649. // Serial should be a hex string
  8650. for (char c : serial) {
  8651. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8652. (c >= 'a' && c <= 'f'));
  8653. }
  8654. serial_checked = true;
  8655. }
  8656. return true;
  8657. });
  8658. auto res = cli.Get("/test");
  8659. ASSERT_TRUE(res);
  8660. EXPECT_TRUE(serial_checked);
  8661. }
  8662. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8663. // Test 1: Valid CA file - no error should be recorded
  8664. {
  8665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8666. CLIENT_CA_CERT_FILE);
  8667. ASSERT_TRUE(svr.is_valid());
  8668. // With valid setup, last_ssl_error should be 0
  8669. EXPECT_EQ(0, svr.ssl_last_error());
  8670. }
  8671. // Test 2: Invalid CA file content
  8672. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8673. {
  8674. // Create a temporary file with completely invalid content
  8675. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8676. {
  8677. std::ofstream ofs(temp_invalid_ca);
  8678. ofs << "This is not a certificate file at all\n";
  8679. ofs << "Just plain text content\n";
  8680. }
  8681. // Create server with invalid CA file
  8682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8683. // Clean up temporary file
  8684. std::remove(temp_invalid_ca);
  8685. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8686. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8687. // Note: SSL_CTX_load_verify_locations typically fails first,
  8688. // but our error handling code path is still exercised
  8689. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8690. }
  8691. }
  8692. TEST(VerifyCallbackTest, VerifyContextFields) {
  8693. using namespace httplib::tls;
  8694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8695. ASSERT_TRUE(svr.is_valid());
  8696. svr.Get("/test", [](const Request &, Response &res) {
  8697. res.set_content("ok", "text/plain");
  8698. });
  8699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8700. auto se = detail::scope_exit([&] {
  8701. svr.stop();
  8702. t.join();
  8703. });
  8704. svr.wait_until_ready();
  8705. SSLClient cli(HOST, PORT);
  8706. cli.enable_server_certificate_verification(false);
  8707. cli.set_connection_timeout(30);
  8708. int callback_count = 0;
  8709. bool saw_leaf_cert = false;
  8710. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8711. if (ctx.cert) {
  8712. callback_count++;
  8713. // We should see at least one certificate (the leaf)
  8714. std::string cn = ctx.subject_cn();
  8715. if (!cn.empty()) { saw_leaf_cert = true; }
  8716. // Verify context fields are populated
  8717. EXPECT_NE(ctx.session, nullptr);
  8718. EXPECT_GE(ctx.depth, 0);
  8719. }
  8720. return true;
  8721. });
  8722. auto res = cli.Get("/test");
  8723. ASSERT_TRUE(res);
  8724. EXPECT_GT(callback_count, 0);
  8725. EXPECT_TRUE(saw_leaf_cert);
  8726. }
  8727. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8728. using httplib::tls::TlsError;
  8729. // Test that verify_error_to_string returns empty for success
  8730. std::string success_str = TlsError::verify_error_to_string(0);
  8731. EXPECT_TRUE(success_str.empty());
  8732. // Test that verify_error_to_string returns non-empty for error codes
  8733. // Using a common error code (certificate expired)
  8734. std::string error_str =
  8735. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8736. EXPECT_FALSE(error_str.empty());
  8737. }
  8738. TEST(SessionVerifierTest, CertificateAccepted) {
  8739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8740. ASSERT_TRUE(svr.is_valid());
  8741. svr.Get("/test", [](const Request &, Response &res) {
  8742. res.set_content("ok", "text/plain");
  8743. });
  8744. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8745. auto se = detail::scope_exit([&] {
  8746. svr.stop();
  8747. t.join();
  8748. });
  8749. svr.wait_until_ready();
  8750. SSLClient cli(HOST, PORT);
  8751. cli.enable_server_certificate_verification(false);
  8752. cli.set_connection_timeout(30);
  8753. bool callback_called = false;
  8754. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8755. EXPECT_NE(session, nullptr);
  8756. callback_called = true;
  8757. return SSLVerifierResponse::CertificateAccepted;
  8758. });
  8759. auto res = cli.Get("/test");
  8760. ASSERT_TRUE(res);
  8761. EXPECT_EQ(200, res->status);
  8762. EXPECT_TRUE(callback_called);
  8763. }
  8764. TEST(SessionVerifierTest, CertificateRejected) {
  8765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8766. ASSERT_TRUE(svr.is_valid());
  8767. svr.Get("/test", [](const Request &, Response &res) {
  8768. res.set_content("ok", "text/plain");
  8769. });
  8770. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8771. auto se = detail::scope_exit([&] {
  8772. svr.stop();
  8773. t.join();
  8774. });
  8775. svr.wait_until_ready();
  8776. SSLClient cli(HOST, PORT);
  8777. cli.enable_server_certificate_verification(false);
  8778. cli.set_connection_timeout(30);
  8779. bool callback_called = false;
  8780. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8781. EXPECT_NE(session, nullptr);
  8782. callback_called = true;
  8783. return SSLVerifierResponse::CertificateRejected;
  8784. });
  8785. auto res = cli.Get("/test");
  8786. EXPECT_FALSE(res);
  8787. EXPECT_TRUE(callback_called);
  8788. }
  8789. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8791. ASSERT_TRUE(svr.is_valid());
  8792. svr.Get("/test", [](const Request &, Response &res) {
  8793. res.set_content("ok", "text/plain");
  8794. });
  8795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. t.join();
  8799. });
  8800. svr.wait_until_ready();
  8801. // NoDecisionMade with verification disabled should succeed (no default check)
  8802. SSLClient cli(HOST, PORT);
  8803. cli.enable_server_certificate_verification(false);
  8804. cli.set_connection_timeout(30);
  8805. bool callback_called = false;
  8806. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8807. EXPECT_NE(session, nullptr);
  8808. callback_called = true;
  8809. return SSLVerifierResponse::NoDecisionMade;
  8810. });
  8811. auto res = cli.Get("/test");
  8812. ASSERT_TRUE(res);
  8813. EXPECT_EQ(200, res->status);
  8814. EXPECT_TRUE(callback_called);
  8815. }
  8816. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8818. ASSERT_TRUE(svr.is_valid());
  8819. svr.Get("/test", [](const Request &, Response &res) {
  8820. res.set_content("ok", "text/plain");
  8821. });
  8822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8823. auto se = detail::scope_exit([&] {
  8824. svr.stop();
  8825. t.join();
  8826. });
  8827. svr.wait_until_ready();
  8828. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8829. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8830. // so we only check that the request fails, not whether the callback was
  8831. // called.
  8832. SSLClient cli(HOST, PORT);
  8833. cli.enable_server_certificate_verification(true);
  8834. cli.set_connection_timeout(30);
  8835. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8836. EXPECT_NE(session, nullptr);
  8837. return SSLVerifierResponse::NoDecisionMade;
  8838. });
  8839. auto res = cli.Get("/test");
  8840. EXPECT_FALSE(res);
  8841. }
  8842. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8843. // Test SSL server using PemMemory constructor with client CA certificates
  8844. // Read PEM files
  8845. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8846. read_file(SERVER_CERT_FILE, server_cert_pem);
  8847. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8848. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8849. // Create SSLServer with PemMemory constructor including client CA
  8850. SSLServer::PemMemory server_pem = {
  8851. server_cert_pem.c_str(),
  8852. server_cert_pem.size(),
  8853. server_key_pem.c_str(),
  8854. server_key_pem.size(),
  8855. client_ca_pem.c_str(),
  8856. client_ca_pem.size(),
  8857. nullptr // no password for server key
  8858. };
  8859. SSLServer svr(server_pem);
  8860. ASSERT_TRUE(svr.is_valid());
  8861. // No SSL error should be recorded for valid setup
  8862. EXPECT_EQ(0, svr.ssl_last_error());
  8863. // Set up server endpoints
  8864. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8865. res.set_content("ok", "text/plain");
  8866. });
  8867. // Start server in a thread
  8868. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8869. svr.wait_until_ready();
  8870. // Connect with client certificate (using constructor with paths)
  8871. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8872. cli.enable_server_certificate_verification(false);
  8873. auto res = cli.Get("/test-pem-ca");
  8874. ASSERT_TRUE(res);
  8875. EXPECT_EQ(200, res->status);
  8876. EXPECT_EQ("ok", res->body);
  8877. svr.stop();
  8878. server_thread.join();
  8879. }
  8880. #endif
  8881. #ifdef _WIN32
  8882. TEST(CleanupTest, WSACleanup) {
  8883. int ret = WSACleanup();
  8884. ASSERT_EQ(0, ret);
  8885. }
  8886. #endif
  8887. #ifndef CPPHTTPLIB_SSL_ENABLED
  8888. TEST(NoSSLSupport, SimpleInterface) {
  8889. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8890. }
  8891. #endif
  8892. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8893. TEST(InvalidScheme, SimpleInterface) {
  8894. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8895. }
  8896. #endif
  8897. TEST(NoScheme, SimpleInterface) {
  8898. Client cli("yahoo.com:80");
  8899. ASSERT_TRUE(cli.is_valid());
  8900. }
  8901. TEST(SendAPI, SimpleInterface_Online) {
  8902. Client cli("http://yahoo.com");
  8903. Request req;
  8904. req.method = "GET";
  8905. req.path = "/";
  8906. auto res = cli.send(req);
  8907. ASSERT_TRUE(res);
  8908. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8909. }
  8910. TEST(SendAPI, WithParamsInRequest) {
  8911. Server svr;
  8912. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8913. EXPECT_TRUE(req.has_param("test"));
  8914. EXPECT_EQ("test_value", req.get_param_value("test"));
  8915. });
  8916. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. Client cli(HOST, PORT);
  8924. {
  8925. Request req;
  8926. req.method = "GET";
  8927. req.path = "/";
  8928. req.params.emplace("test", "test_value");
  8929. auto res = cli.send(req);
  8930. ASSERT_TRUE(res);
  8931. }
  8932. {
  8933. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8934. ASSERT_TRUE(res);
  8935. }
  8936. }
  8937. TEST(ClientImplMethods, GetSocketTest) {
  8938. httplib::Server svr;
  8939. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8940. res.status = StatusCode::OK_200;
  8941. });
  8942. auto port = svr.bind_to_any_port("127.0.0.1");
  8943. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8944. auto se = detail::scope_exit([&] {
  8945. svr.stop();
  8946. thread.join();
  8947. ASSERT_FALSE(svr.is_running());
  8948. });
  8949. svr.wait_until_ready();
  8950. {
  8951. httplib::Client cli("127.0.0.1", port);
  8952. cli.set_keep_alive(true);
  8953. // Use the behavior of cpp-httplib of opening the connection
  8954. // only when the first request happens. If that changes,
  8955. // this test would be obsolete.
  8956. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8957. // This also implicitly tests the server. But other tests would fail much
  8958. // earlier than this one to be considered.
  8959. auto res = cli.Get("/");
  8960. ASSERT_TRUE(res);
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8963. }
  8964. }
  8965. // Disabled due to out-of-memory problem on GitHub Actions
  8966. #ifdef _WIN64
  8967. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8968. // allocate content size larger than 2GB in memory
  8969. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8970. char *content = (char *)malloc(content_size);
  8971. ASSERT_TRUE(content);
  8972. Server svr;
  8973. svr.Get("/foo",
  8974. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8975. res.set_content(content, content_size, "application/octet-stream");
  8976. });
  8977. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8978. auto se = detail::scope_exit([&] {
  8979. svr.stop();
  8980. listen_thread.join();
  8981. if (content) free(content);
  8982. ASSERT_FALSE(svr.is_running());
  8983. });
  8984. svr.wait_until_ready();
  8985. Client cli(HOST, PORT);
  8986. auto res = cli.Get("/foo");
  8987. ASSERT_TRUE(res);
  8988. EXPECT_EQ(StatusCode::OK_200, res->status);
  8989. EXPECT_EQ(content_size, res->body.length());
  8990. }
  8991. #endif
  8992. #ifdef CPPHTTPLIB_SSL_ENABLED
  8993. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8994. Client cli("http://yahoo.com");
  8995. auto res = cli.Get("/");
  8996. ASSERT_TRUE(res);
  8997. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8998. cli.set_follow_location(true);
  8999. res = cli.Get("/");
  9000. ASSERT_TRUE(res);
  9001. EXPECT_EQ(StatusCode::OK_200, res->status);
  9002. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9003. }
  9004. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9005. Client cli("https://yahoo.com");
  9006. auto res = cli.Get("/");
  9007. ASSERT_TRUE(res);
  9008. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9009. cli.set_follow_location(true);
  9010. res = cli.Get("/");
  9011. ASSERT_TRUE(res);
  9012. EXPECT_EQ(StatusCode::OK_200, res->status);
  9013. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9014. }
  9015. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9016. Client cli("https://yahoo.com");
  9017. auto res = cli.Get("/");
  9018. ASSERT_TRUE(res);
  9019. ASSERT_FALSE(!res);
  9020. ASSERT_TRUE(res);
  9021. ASSERT_FALSE(res == nullptr);
  9022. ASSERT_TRUE(res != nullptr);
  9023. EXPECT_EQ(Error::Success, res.error());
  9024. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9025. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9026. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9027. cli.set_follow_location(true);
  9028. res = cli.Get("/");
  9029. ASSERT_TRUE(res);
  9030. EXPECT_EQ(Error::Success, res.error());
  9031. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9032. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9033. EXPECT_EQ(StatusCode::OK_200, res->status);
  9034. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9035. }
  9036. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9037. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9038. Client cli("https://cdnjs.cloudflare.com");
  9039. auto res =
  9040. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9041. ASSERT_TRUE(res);
  9042. EXPECT_EQ(StatusCode::OK_200, res->status);
  9043. EXPECT_EQ(287630U, res->body.size());
  9044. EXPECT_EQ("application/javascript; charset=utf-8",
  9045. res->get_header_value("Content-Type"));
  9046. }
  9047. #endif
  9048. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9049. #undef REDIR_HOST // Silence compiler warning
  9050. #define REDIR_HOST "https://httpbingo.org"
  9051. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9052. Client cli(REDIR_HOST);
  9053. cli.set_follow_location(true);
  9054. auto res =
  9055. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::OK_200, res->status);
  9058. }
  9059. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9060. Client cli(REDIR_HOST);
  9061. cli.set_follow_location(true);
  9062. Params params;
  9063. params.emplace("url", "http://example.com");
  9064. params.emplace("status_code", "302");
  9065. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9066. ASSERT_TRUE(res);
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. }
  9069. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9070. Client cli(REDIR_HOST);
  9071. cli.set_follow_location(true);
  9072. Params params;
  9073. params.emplace("url", "http://example.com");
  9074. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9075. ASSERT_TRUE(res);
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. }
  9078. TEST(HttpToHttpsRedirectTest, CertFile) {
  9079. auto ssl_port = PORT + 1;
  9080. Server svr;
  9081. ASSERT_TRUE(svr.is_valid());
  9082. svr.Get("/index", [&](const Request &, Response &res) {
  9083. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9084. "/index");
  9085. svr.stop();
  9086. });
  9087. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9088. ASSERT_TRUE(ssl_svr.is_valid());
  9089. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9090. res.set_content("test", "text/plain");
  9091. ssl_svr.stop();
  9092. });
  9093. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9094. thread t2 =
  9095. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9096. auto se = detail::scope_exit([&] {
  9097. t2.join();
  9098. t.join();
  9099. ASSERT_FALSE(svr.is_running());
  9100. });
  9101. svr.wait_until_ready();
  9102. ssl_svr.wait_until_ready();
  9103. Client cli("127.0.0.1", PORT);
  9104. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9105. cli.enable_server_certificate_verification(true);
  9106. cli.set_follow_location(true);
  9107. cli.set_connection_timeout(30);
  9108. auto res = cli.Get("/index");
  9109. ASSERT_TRUE(res);
  9110. ASSERT_EQ(StatusCode::OK_200, res->status);
  9111. }
  9112. TEST(SSLClientRedirectTest, CertFile) {
  9113. auto ssl_port = PORT + 1;
  9114. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9115. ASSERT_TRUE(ssl_svr1.is_valid());
  9116. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9117. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9118. "/index");
  9119. ssl_svr1.stop();
  9120. });
  9121. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9122. ASSERT_TRUE(ssl_svr2.is_valid());
  9123. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9124. res.set_content("test", "text/plain");
  9125. ssl_svr2.stop();
  9126. });
  9127. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9128. thread t2 =
  9129. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9130. auto se = detail::scope_exit([&] {
  9131. t2.join();
  9132. t.join();
  9133. ASSERT_FALSE(ssl_svr1.is_running());
  9134. });
  9135. ssl_svr1.wait_until_ready();
  9136. ssl_svr2.wait_until_ready();
  9137. SSLClient cli("127.0.0.1", PORT);
  9138. std::string cert;
  9139. read_file(SERVER_CERT2_FILE, cert);
  9140. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9141. cli.enable_server_certificate_verification(true);
  9142. cli.set_follow_location(true);
  9143. cli.set_connection_timeout(30);
  9144. auto res = cli.Get("/index");
  9145. ASSERT_TRUE(res);
  9146. ASSERT_EQ(StatusCode::OK_200, res->status);
  9147. }
  9148. #endif
  9149. #ifdef CPPHTTPLIB_SSL_ENABLED
  9150. // Test that set_ca_cert_store() skips system certs (consistent with
  9151. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9152. // should be trusted - system certs should NOT be loaded.
  9153. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9154. // Load a specific cert that is NOT a system CA cert
  9155. std::string cert;
  9156. read_file(SERVER_CERT2_FILE, cert);
  9157. SSLClient cli("google.com");
  9158. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9159. cli.enable_server_certificate_verification(true);
  9160. // This should FAIL because:
  9161. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9162. // 2. System certs should NOT be loaded when custom store is set
  9163. // If system certs WERE loaded, this would succeed
  9164. auto res = cli.Get("/");
  9165. ASSERT_FALSE(res);
  9166. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9167. }
  9168. TEST(MultipartFormDataTest, LargeData) {
  9169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9170. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9171. const ContentReader &content_reader) {
  9172. if (req.is_multipart_form_data()) {
  9173. std::vector<FormData> items;
  9174. content_reader(
  9175. [&](const FormData &file) {
  9176. items.push_back(file);
  9177. return true;
  9178. },
  9179. [&](const char *data, size_t data_length) {
  9180. items.back().content.append(data, data_length);
  9181. return true;
  9182. });
  9183. EXPECT_TRUE(std::string(items[0].name) == "document");
  9184. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9185. EXPECT_TRUE(items[0].filename == "2MB_data");
  9186. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9187. EXPECT_TRUE(items[1].name == "hello");
  9188. EXPECT_TRUE(items[1].content == "world");
  9189. EXPECT_TRUE(items[1].filename == "");
  9190. EXPECT_TRUE(items[1].content_type == "");
  9191. } else {
  9192. std::string body;
  9193. content_reader([&](const char *data, size_t data_length) {
  9194. body.append(data, data_length);
  9195. return true;
  9196. });
  9197. }
  9198. });
  9199. auto port = svr.bind_to_any_port(HOST);
  9200. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9201. auto se = detail::scope_exit([&] {
  9202. svr.stop();
  9203. t.join();
  9204. ASSERT_FALSE(svr.is_running());
  9205. });
  9206. svr.wait_until_ready();
  9207. {
  9208. std::string data(1024 * 1024 * 2, '.');
  9209. std::stringstream buffer;
  9210. buffer << data;
  9211. SSLClient cli(HOST, port);
  9212. cli.enable_server_certificate_verification(false);
  9213. UploadFormDataItems items{
  9214. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9215. {"hello", "world", "", ""},
  9216. };
  9217. auto res = cli.Post("/post", items);
  9218. ASSERT_TRUE(res);
  9219. ASSERT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. }
  9222. TEST(MultipartFormDataTest, DataProviderItems) {
  9223. std::random_device seed_gen;
  9224. std::mt19937 random(seed_gen());
  9225. std::string rand1;
  9226. rand1.resize(1000);
  9227. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9228. std::string rand2;
  9229. rand2.resize(3000);
  9230. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9232. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9233. const ContentReader &content_reader) {
  9234. ASSERT_FALSE(req.is_multipart_form_data());
  9235. std::string body;
  9236. content_reader([&](const char *data, size_t data_length) {
  9237. body.append(data, data_length);
  9238. return true;
  9239. });
  9240. EXPECT_EQ(body, "");
  9241. });
  9242. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9243. const ContentReader &content_reader) {
  9244. ASSERT_TRUE(req.is_multipart_form_data());
  9245. std::vector<FormData> items;
  9246. content_reader(
  9247. [&](const FormData &file) {
  9248. items.push_back(file);
  9249. return true;
  9250. },
  9251. [&](const char *data, size_t data_length) {
  9252. items.back().content.append(data, data_length);
  9253. return true;
  9254. });
  9255. ASSERT_TRUE(items.size() == 2);
  9256. EXPECT_EQ(std::string(items[0].name), "name1");
  9257. EXPECT_EQ(items[0].content, "Testing123");
  9258. EXPECT_EQ(items[0].filename, "filename1");
  9259. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9260. EXPECT_EQ(items[1].name, "name2");
  9261. EXPECT_EQ(items[1].content, "Testing456");
  9262. EXPECT_EQ(items[1].filename, "");
  9263. EXPECT_EQ(items[1].content_type, "");
  9264. });
  9265. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9266. const ContentReader &content_reader) {
  9267. ASSERT_TRUE(req.is_multipart_form_data());
  9268. std::vector<FormData> items;
  9269. content_reader(
  9270. [&](const FormData &file) {
  9271. items.push_back(file);
  9272. return true;
  9273. },
  9274. [&](const char *data, size_t data_length) {
  9275. items.back().content.append(data, data_length);
  9276. return true;
  9277. });
  9278. ASSERT_TRUE(items.size() == 2);
  9279. EXPECT_EQ(items[0].name, "name3");
  9280. EXPECT_EQ(items[0].content, rand1);
  9281. EXPECT_EQ(items[0].filename, "filename3");
  9282. EXPECT_EQ(items[0].content_type, "");
  9283. EXPECT_EQ(items[1].name, "name4");
  9284. EXPECT_EQ(items[1].content, rand2);
  9285. EXPECT_EQ(items[1].filename, "filename4");
  9286. EXPECT_EQ(items[1].content_type, "");
  9287. });
  9288. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9289. const ContentReader &content_reader) {
  9290. ASSERT_TRUE(req.is_multipart_form_data());
  9291. std::vector<FormData> items;
  9292. content_reader(
  9293. [&](const FormData &file) {
  9294. items.push_back(file);
  9295. return true;
  9296. },
  9297. [&](const char *data, size_t data_length) {
  9298. items.back().content.append(data, data_length);
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(items.size() == 4);
  9302. EXPECT_EQ(std::string(items[0].name), "name1");
  9303. EXPECT_EQ(items[0].content, "Testing123");
  9304. EXPECT_EQ(items[0].filename, "filename1");
  9305. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9306. EXPECT_EQ(items[1].name, "name2");
  9307. EXPECT_EQ(items[1].content, "Testing456");
  9308. EXPECT_EQ(items[1].filename, "");
  9309. EXPECT_EQ(items[1].content_type, "");
  9310. EXPECT_EQ(items[2].name, "name3");
  9311. EXPECT_EQ(items[2].content, rand1);
  9312. EXPECT_EQ(items[2].filename, "filename3");
  9313. EXPECT_EQ(items[2].content_type, "");
  9314. EXPECT_EQ(items[3].name, "name4");
  9315. EXPECT_EQ(items[3].content, rand2);
  9316. EXPECT_EQ(items[3].filename, "filename4");
  9317. EXPECT_EQ(items[3].content_type, "");
  9318. });
  9319. auto port = svr.bind_to_any_port("localhost");
  9320. auto t = std::thread([&]() { svr.listen_after_bind(); });
  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. {
  9328. SSLClient cli("localhost", port);
  9329. cli.enable_server_certificate_verification(false);
  9330. UploadFormDataItems items{
  9331. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9332. {"name2", "Testing456", "", ""}, // not a file
  9333. };
  9334. {
  9335. auto res = cli.Post("/post-none", {}, {}, {});
  9336. ASSERT_TRUE(res);
  9337. ASSERT_EQ(StatusCode::OK_200, res->status);
  9338. }
  9339. FormDataProviderItems providers;
  9340. {
  9341. auto res =
  9342. cli.Post("/post-items", {}, items, providers); // empty providers
  9343. ASSERT_TRUE(res);
  9344. ASSERT_EQ(StatusCode::OK_200, res->status);
  9345. }
  9346. providers.push_back({"name3",
  9347. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9348. // test the offset is given correctly at each step
  9349. if (!offset)
  9350. sink.os.write(rand1.data(), 30);
  9351. else if (offset == 30)
  9352. sink.os.write(rand1.data() + 30, 300);
  9353. else if (offset == 330)
  9354. sink.os.write(rand1.data() + 330, 670);
  9355. else if (offset == rand1.size())
  9356. sink.done();
  9357. return true;
  9358. },
  9359. "filename3",
  9360. {}});
  9361. providers.push_back({"name4",
  9362. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9363. // test the offset is given correctly at each step
  9364. if (!offset)
  9365. sink.os.write(rand2.data(), 2000);
  9366. else if (offset == 2000)
  9367. sink.os.write(rand2.data() + 2000, 1);
  9368. else if (offset == 2001)
  9369. sink.os.write(rand2.data() + 2001, 999);
  9370. else if (offset == rand2.size())
  9371. sink.done();
  9372. return true;
  9373. },
  9374. "filename4",
  9375. {}});
  9376. {
  9377. auto res = cli.Post("/post-providers", {}, {}, providers);
  9378. ASSERT_TRUE(res);
  9379. ASSERT_EQ(StatusCode::OK_200, res->status);
  9380. }
  9381. {
  9382. auto res = cli.Post("/post-both", {}, items, providers);
  9383. ASSERT_TRUE(res);
  9384. ASSERT_EQ(StatusCode::OK_200, res->status);
  9385. }
  9386. }
  9387. }
  9388. TEST(MultipartFormDataTest, BadHeader) {
  9389. Server svr;
  9390. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9391. res.set_content("ok", "text/plain");
  9392. });
  9393. thread t = thread([&] { svr.listen(HOST, PORT); });
  9394. auto se = detail::scope_exit([&] {
  9395. svr.stop();
  9396. t.join();
  9397. ASSERT_FALSE(svr.is_running());
  9398. });
  9399. svr.wait_until_ready();
  9400. const std::string body =
  9401. "This is the preamble. It is to be ignored, though it\r\n"
  9402. "is a handy place for composition agents to include an\r\n"
  9403. "explanatory note to non-MIME conformant readers.\r\n"
  9404. "\r\n"
  9405. "\r\n"
  9406. "--simple boundary\r\n"
  9407. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9408. ": BAD...\r\n"
  9409. "\r\n"
  9410. "value1\r\n"
  9411. "--simple boundary\r\n"
  9412. "Content-Disposition: form-data; name=\"field2\"; "
  9413. "filename=\"example.txt\"\r\n"
  9414. "\r\n"
  9415. "value2\r\n"
  9416. "--simple boundary--\r\n"
  9417. "This is the epilogue. It is also to be ignored.\r\n";
  9418. std::string content_type =
  9419. R"(multipart/form-data; boundary="simple boundary")";
  9420. Client cli(HOST, PORT);
  9421. auto res = cli.Post("/post", body, content_type.c_str());
  9422. ASSERT_TRUE(res);
  9423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9424. }
  9425. TEST(MultipartFormDataTest, WithPreamble) {
  9426. Server svr;
  9427. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9428. res.set_content("ok", "text/plain");
  9429. });
  9430. thread t = thread([&] { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. t.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. const std::string body =
  9438. "This is the preamble. It is to be ignored, though it\r\n"
  9439. "is a handy place for composition agents to include an\r\n"
  9440. "explanatory note to non-MIME conformant readers.\r\n"
  9441. "\r\n"
  9442. "\r\n"
  9443. "--simple boundary\r\n"
  9444. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9445. "\r\n"
  9446. "value1\r\n"
  9447. "--simple boundary\r\n"
  9448. "Content-Disposition: form-data; name=\"field2\"; "
  9449. "filename=\"example.txt\"\r\n"
  9450. "\r\n"
  9451. "value2\r\n"
  9452. "--simple boundary--\r\n"
  9453. "This is the epilogue. It is also to be ignored.\r\n";
  9454. std::string content_type =
  9455. R"(multipart/form-data; boundary="simple boundary")";
  9456. Client cli(HOST, PORT);
  9457. auto res = cli.Post("/post", body, content_type.c_str());
  9458. ASSERT_TRUE(res);
  9459. EXPECT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9463. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9464. const ContentReader &content_reader) {
  9465. if (req.is_multipart_form_data()) {
  9466. std::vector<FormData> items;
  9467. content_reader(
  9468. [&](const FormData &file) {
  9469. items.push_back(file);
  9470. return true;
  9471. },
  9472. [&](const char *data, size_t data_length) {
  9473. items.back().content.append(data, data_length);
  9474. return true;
  9475. });
  9476. EXPECT_TRUE(std::string(items[0].name) == "document");
  9477. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9478. EXPECT_TRUE(items[0].filename == "2MB_data");
  9479. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9480. EXPECT_TRUE(items[1].name == "hello");
  9481. EXPECT_TRUE(items[1].content == "world");
  9482. EXPECT_TRUE(items[1].filename == "");
  9483. EXPECT_TRUE(items[1].content_type == "");
  9484. } else {
  9485. std::string body;
  9486. content_reader([&](const char *data, size_t data_length) {
  9487. body.append(data, data_length);
  9488. return true;
  9489. });
  9490. }
  9491. });
  9492. auto port = svr.bind_to_any_port("localhost");
  9493. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9494. auto se = detail::scope_exit([&] {
  9495. svr.stop();
  9496. t.join();
  9497. ASSERT_FALSE(svr.is_running());
  9498. });
  9499. svr.wait_until_ready();
  9500. {
  9501. std::string data(1024 * 1024 * 2, '.');
  9502. std::stringstream buffer;
  9503. buffer << data;
  9504. SSLClient cli("localhost", port);
  9505. cli.enable_server_certificate_verification(false);
  9506. UploadFormDataItems items{
  9507. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9508. {"hello", "world", "", ""},
  9509. };
  9510. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9511. ASSERT_TRUE(res);
  9512. ASSERT_EQ(StatusCode::OK_200, res->status);
  9513. }
  9514. }
  9515. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9516. std::string data(1024 * 1024 * 2, '&');
  9517. std::stringstream buffer;
  9518. buffer << data;
  9519. Client cli("https://localhost:8080");
  9520. UploadFormDataItems items{
  9521. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9522. {"hello", "world", "", ""},
  9523. };
  9524. for (const char &c : " \t\r\n") {
  9525. auto res =
  9526. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9527. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9528. ASSERT_FALSE(res);
  9529. }
  9530. }
  9531. TEST(MultipartFormDataTest, PutFormData) {
  9532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9533. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9534. const ContentReader &content_reader) {
  9535. if (req.is_multipart_form_data()) {
  9536. std::vector<FormData> items;
  9537. content_reader(
  9538. [&](const FormData &file) {
  9539. items.push_back(file);
  9540. return true;
  9541. },
  9542. [&](const char *data, size_t data_length) {
  9543. items.back().content.append(data, data_length);
  9544. return true;
  9545. });
  9546. EXPECT_TRUE(std::string(items[0].name) == "document");
  9547. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9548. EXPECT_TRUE(items[0].filename == "2MB_data");
  9549. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9550. EXPECT_TRUE(items[1].name == "hello");
  9551. EXPECT_TRUE(items[1].content == "world");
  9552. EXPECT_TRUE(items[1].filename == "");
  9553. EXPECT_TRUE(items[1].content_type == "");
  9554. } else {
  9555. std::string body;
  9556. content_reader([&](const char *data, size_t data_length) {
  9557. body.append(data, data_length);
  9558. return true;
  9559. });
  9560. }
  9561. });
  9562. auto port = svr.bind_to_any_port("localhost");
  9563. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. t.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. {
  9571. std::string data(1024 * 1024 * 2, '&');
  9572. std::stringstream buffer;
  9573. buffer << data;
  9574. SSLClient cli("localhost", port);
  9575. cli.enable_server_certificate_verification(false);
  9576. UploadFormDataItems items{
  9577. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9578. {"hello", "world", "", ""},
  9579. };
  9580. auto res = cli.Put("/put", items);
  9581. ASSERT_TRUE(res);
  9582. ASSERT_EQ(StatusCode::OK_200, res->status);
  9583. }
  9584. }
  9585. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9587. svr.Put("/put_customboundary",
  9588. [&](const Request &req, const Response & /*res*/,
  9589. const ContentReader &content_reader) {
  9590. if (req.is_multipart_form_data()) {
  9591. std::vector<FormData> items;
  9592. content_reader(
  9593. [&](const FormData &file) {
  9594. items.push_back(file);
  9595. return true;
  9596. },
  9597. [&](const char *data, size_t data_length) {
  9598. items.back().content.append(data, data_length);
  9599. return true;
  9600. });
  9601. EXPECT_TRUE(std::string(items[0].name) == "document");
  9602. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9603. EXPECT_TRUE(items[0].filename == "2MB_data");
  9604. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9605. EXPECT_TRUE(items[1].name == "hello");
  9606. EXPECT_TRUE(items[1].content == "world");
  9607. EXPECT_TRUE(items[1].filename == "");
  9608. EXPECT_TRUE(items[1].content_type == "");
  9609. } else {
  9610. std::string body;
  9611. content_reader([&](const char *data, size_t data_length) {
  9612. body.append(data, data_length);
  9613. return true;
  9614. });
  9615. }
  9616. });
  9617. auto port = svr.bind_to_any_port("localhost");
  9618. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. {
  9626. std::string data(1024 * 1024 * 2, '&');
  9627. std::stringstream buffer;
  9628. buffer << data;
  9629. SSLClient cli("localhost", port);
  9630. cli.enable_server_certificate_verification(false);
  9631. UploadFormDataItems items{
  9632. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9633. {"hello", "world", "", ""},
  9634. };
  9635. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9636. ASSERT_TRUE(res);
  9637. ASSERT_EQ(StatusCode::OK_200, res->status);
  9638. }
  9639. }
  9640. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9641. std::string data(1024 * 1024 * 2, '&');
  9642. std::stringstream buffer;
  9643. buffer << data;
  9644. Client cli("https://localhost:8080");
  9645. cli.enable_server_certificate_verification(false);
  9646. UploadFormDataItems items{
  9647. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9648. {"hello", "world", "", ""},
  9649. };
  9650. for (const char &c : " \t\r\n") {
  9651. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9652. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9653. ASSERT_FALSE(res);
  9654. }
  9655. }
  9656. TEST(MultipartFormDataTest, AlternateFilename) {
  9657. auto handled = false;
  9658. Server svr;
  9659. svr.Post("/test", [&](const Request &req, Response &res) {
  9660. ASSERT_EQ(2u, req.form.files.size());
  9661. ASSERT_EQ(1u, req.form.fields.size());
  9662. // Test files
  9663. const auto &file1 = req.form.get_file("file1");
  9664. ASSERT_EQ("file1", file1.name);
  9665. ASSERT_EQ("A.txt", file1.filename);
  9666. ASSERT_EQ("text/plain", file1.content_type);
  9667. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9668. const auto &file2 = req.form.get_file("file2");
  9669. ASSERT_EQ("file2", file2.name);
  9670. ASSERT_EQ("a.html", file2.filename);
  9671. ASSERT_EQ("text/html", file2.content_type);
  9672. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9673. file2.content);
  9674. // Test text field
  9675. const auto &text = req.form.get_field("text");
  9676. ASSERT_EQ("text default", text);
  9677. res.set_content("ok", "text/plain");
  9678. handled = true;
  9679. });
  9680. thread t = thread([&] { svr.listen(HOST, PORT); });
  9681. auto se = detail::scope_exit([&] {
  9682. svr.stop();
  9683. t.join();
  9684. ASSERT_FALSE(svr.is_running());
  9685. ASSERT_TRUE(handled);
  9686. });
  9687. svr.wait_until_ready();
  9688. auto req = "POST /test HTTP/1.1\r\n"
  9689. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9690. "Content-Length: 399\r\n"
  9691. "\r\n"
  9692. "----------\r\n"
  9693. "Content-Disposition: form-data; name=\"text\"\r\n"
  9694. "\r\n"
  9695. "text default\r\n"
  9696. "----------\r\n"
  9697. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9698. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9699. "Content-Type: text/plain\r\n"
  9700. "\r\n"
  9701. "Content of a.txt.\r\n"
  9702. "\r\n"
  9703. "----------\r\n"
  9704. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9705. "\"a.html\"\r\n"
  9706. "Content-Type: text/html\r\n"
  9707. "\r\n"
  9708. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9709. "\r\n"
  9710. "------------\r\n";
  9711. ASSERT_TRUE(send_request(1, req));
  9712. }
  9713. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9714. auto handled = false;
  9715. Server svr;
  9716. svr.Post("/test", [&](const Request &req, Response &res) {
  9717. // Case-insensitive "utf-8''" prefix with a long value
  9718. const auto &file = req.form.get_file("file1");
  9719. ASSERT_EQ("file1", file.name);
  9720. // 8000 chars exercises both the Content-Disposition parser and the
  9721. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9722. // Prior to the fix, std::regex_match on this header would cause O(N)
  9723. // stack recursion in libstdc++, leading to SIGSEGV.
  9724. std::string expected_filename(8000, 'A');
  9725. ASSERT_EQ(expected_filename, file.filename);
  9726. res.set_content("ok", "text/plain");
  9727. handled = true;
  9728. });
  9729. thread t = thread([&] { svr.listen(HOST, PORT); });
  9730. auto se = detail::scope_exit([&] {
  9731. svr.stop();
  9732. t.join();
  9733. ASSERT_FALSE(svr.is_running());
  9734. ASSERT_TRUE(handled);
  9735. });
  9736. svr.wait_until_ready();
  9737. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9738. // Regression test for GHSA-qq6v-r583-3h69
  9739. std::string long_filename(8000, 'A');
  9740. std::string body = "----------\r\n"
  9741. "Content-Disposition: form-data; name=\"file1\"; "
  9742. "filename*=\"Utf-8''" +
  9743. long_filename +
  9744. "\"\r\n"
  9745. "\r\n"
  9746. "hello\r\n"
  9747. "------------\r\n";
  9748. auto req = "POST /test HTTP/1.1\r\n"
  9749. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9750. "Content-Length: " +
  9751. std::to_string(body.size()) + "\r\n\r\n" + body;
  9752. ASSERT_TRUE(send_request(1, req));
  9753. }
  9754. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9755. auto handled = false;
  9756. Server svr;
  9757. svr.Post("/test", [&](const Request &req, Response &) {
  9758. ASSERT_EQ(2u, req.form.fields.size());
  9759. const auto &text1 = req.form.get_field("text1");
  9760. ASSERT_EQ("text1", text1);
  9761. const auto &text2 = req.form.get_field("text2");
  9762. ASSERT_EQ("text2", text2);
  9763. handled = true;
  9764. });
  9765. thread t = thread([&] { svr.listen(HOST, PORT); });
  9766. auto se = detail::scope_exit([&] {
  9767. svr.stop();
  9768. t.join();
  9769. ASSERT_FALSE(svr.is_running());
  9770. ASSERT_TRUE(handled);
  9771. });
  9772. svr.wait_until_ready();
  9773. auto req = "POST /test HTTP/1.1\r\n"
  9774. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9775. "Content-Length: 146\r\n"
  9776. "\r\n----------\r\n"
  9777. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9778. "\r\n"
  9779. "text1"
  9780. "\r\n----------\r\n"
  9781. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9782. "\r\n"
  9783. "text2"
  9784. "\r\n------------";
  9785. std::string response;
  9786. ASSERT_TRUE(send_request(1, req, &response));
  9787. ASSERT_EQ("200", response.substr(9, 3));
  9788. }
  9789. TEST(MultipartFormDataTest, ContentLength) {
  9790. auto handled = false;
  9791. Server svr;
  9792. svr.Post("/test", [&](const Request &req, Response &) {
  9793. ASSERT_EQ(2u, req.form.fields.size());
  9794. const auto &text1 = req.form.get_field("text1");
  9795. ASSERT_EQ("text1", text1);
  9796. const auto &text2 = req.form.get_field("text2");
  9797. ASSERT_EQ("text2", text2);
  9798. handled = true;
  9799. });
  9800. thread t = thread([&] { svr.listen(HOST, PORT); });
  9801. auto se = detail::scope_exit([&] {
  9802. svr.stop();
  9803. t.join();
  9804. ASSERT_FALSE(svr.is_running());
  9805. ASSERT_TRUE(handled);
  9806. });
  9807. svr.wait_until_ready();
  9808. auto req = "POST /test HTTP/1.1\r\n"
  9809. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9810. "Content-Length: 167\r\n"
  9811. "\r\n----------\r\n"
  9812. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9813. "Content-Length: 5\r\n"
  9814. "\r\n"
  9815. "text1"
  9816. "\r\n----------\r\n"
  9817. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9818. "\r\n"
  9819. "text2"
  9820. "\r\n------------\r\n";
  9821. std::string response;
  9822. ASSERT_TRUE(send_request(1, req, &response));
  9823. ASSERT_EQ("200", response.substr(9, 3));
  9824. }
  9825. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9826. auto handled = false;
  9827. Server svr;
  9828. svr.Post("/test", [&](const Request &req, Response &) {
  9829. ASSERT_EQ(2u, req.form.fields.size());
  9830. const auto &text1 = req.form.get_field("text1");
  9831. ASSERT_EQ("text1", text1);
  9832. // TODO: Add header access for text fields if needed
  9833. const auto &text2 = req.form.get_field("text2");
  9834. ASSERT_EQ("text2", text2);
  9835. // TODO: Header access for text fields needs to be implemented
  9836. // auto &headers = it->second.headers;
  9837. // ASSERT_EQ(3U, headers.size());
  9838. // auto custom_header = headers.find("x-whatever");
  9839. // ASSERT_TRUE(custom_header != headers.end());
  9840. // ASSERT_NE("customvalue", custom_header->second);
  9841. // ASSERT_EQ("CustomValue", custom_header->second);
  9842. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9843. handled = true;
  9844. });
  9845. thread t = thread([&] { svr.listen(HOST, PORT); });
  9846. auto se = detail::scope_exit([&] {
  9847. svr.stop();
  9848. t.join();
  9849. ASSERT_FALSE(svr.is_running());
  9850. ASSERT_TRUE(handled);
  9851. });
  9852. svr.wait_until_ready();
  9853. auto req = "POST /test HTTP/1.1\r\n"
  9854. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9855. "Content-Length: 232\r\n"
  9856. "\r\n----------\r\n"
  9857. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9858. "Content-Length: 5\r\n"
  9859. "X-Test: 1\r\n"
  9860. "\r\n"
  9861. "text1"
  9862. "\r\n----------\r\n"
  9863. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9864. "Content-Type: text/plain\r\n"
  9865. "X-Whatever: CustomValue\r\n"
  9866. "\r\n"
  9867. "text2"
  9868. "\r\n------------\r\n"
  9869. "That should be disregarded. Not even read";
  9870. std::string response;
  9871. ASSERT_TRUE(send_request(1, req, &response));
  9872. ASSERT_EQ("200", response.substr(9, 3));
  9873. }
  9874. TEST(MultipartFormDataTest, LargeHeader) {
  9875. auto handled = false;
  9876. Server svr;
  9877. svr.Post("/test", [&](const Request &req, Response &) {
  9878. ASSERT_EQ(1u, req.form.fields.size());
  9879. const auto &text = req.form.get_field("name1");
  9880. ASSERT_EQ("text1", text);
  9881. handled = true;
  9882. });
  9883. thread t = thread([&] { svr.listen(HOST, PORT); });
  9884. auto se = detail::scope_exit([&] {
  9885. svr.stop();
  9886. t.join();
  9887. ASSERT_FALSE(svr.is_running());
  9888. ASSERT_TRUE(handled);
  9889. });
  9890. svr.wait_until_ready();
  9891. auto boundary = std::string("cpp-httplib-multipart-data");
  9892. std::string content = "--" + boundary +
  9893. "\r\n"
  9894. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9895. "\r\n"
  9896. "text1\r\n"
  9897. "--" +
  9898. boundary + "--\r\n";
  9899. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9900. "Content-Type: multipart/form-data;boundary=" +
  9901. boundary +
  9902. "\r\n"
  9903. "Content-Length: " +
  9904. std::to_string(content.size()) +
  9905. "\r\n"
  9906. "Dummy-Header: ";
  9907. std::string header_suffix = "\r\n"
  9908. "\r\n";
  9909. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9910. size_t header_dummy_size =
  9911. read_buff_size -
  9912. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9913. auto header_dummy = std::string(header_dummy_size, '@');
  9914. auto req = header_prefix + header_dummy + header_suffix + content;
  9915. std::string response;
  9916. ASSERT_TRUE(send_request(1, req, &response));
  9917. ASSERT_EQ("200", response.substr(9, 3));
  9918. }
  9919. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  9920. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  9921. // (not chunked Transfer-Encoding) after the streaming refactor.
  9922. auto handled = false;
  9923. Server svr;
  9924. svr.Post("/upload", [&](const Request &req, Response &res) {
  9925. auto cl_it = req.headers.find("Content-Length");
  9926. EXPECT_TRUE(cl_it != req.headers.end());
  9927. auto te_it = req.headers.find("Transfer-Encoding");
  9928. EXPECT_TRUE(te_it == req.headers.end());
  9929. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  9930. res.set_content("ok", "text/plain");
  9931. handled = true;
  9932. });
  9933. auto port = svr.bind_to_any_port(HOST);
  9934. auto t = thread([&] { svr.listen_after_bind(); });
  9935. auto se = detail::scope_exit([&] {
  9936. svr.stop();
  9937. t.join();
  9938. ASSERT_FALSE(svr.is_running());
  9939. ASSERT_TRUE(handled);
  9940. });
  9941. svr.wait_until_ready();
  9942. UploadFormDataItems items = {
  9943. {"field1", "hello", "", "text/plain"},
  9944. {"file1", "world", "test.txt", "application/octet-stream"},
  9945. };
  9946. Client cli(HOST, port);
  9947. auto res = cli.Post("/upload", {}, items);
  9948. ASSERT_TRUE(res);
  9949. EXPECT_EQ(StatusCode::OK_200, res->status);
  9950. }
  9951. TEST(MultipartFormDataTest, MakeFileProvider) {
  9952. // Verify make_file_provider sends a file's contents correctly.
  9953. const std::string file_content(4096, 'Z');
  9954. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  9955. {
  9956. std::ofstream ofs(tmp_path, std::ios::binary);
  9957. ofs.write(file_content.data(),
  9958. static_cast<std::streamsize>(file_content.size()));
  9959. }
  9960. auto handled = false;
  9961. Server svr;
  9962. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  9963. const ContentReader &content_reader) {
  9964. ASSERT_TRUE(req.is_multipart_form_data());
  9965. std::vector<FormData> items;
  9966. content_reader(
  9967. [&](const FormData &file) {
  9968. items.push_back(file);
  9969. return true;
  9970. },
  9971. [&](const char *data, size_t data_length) {
  9972. items.back().content.append(data, data_length);
  9973. return true;
  9974. });
  9975. ASSERT_EQ(1u, items.size());
  9976. EXPECT_EQ("myfile", items[0].name);
  9977. EXPECT_EQ("data.bin", items[0].filename);
  9978. EXPECT_EQ("application/octet-stream", items[0].content_type);
  9979. EXPECT_EQ(file_content, items[0].content);
  9980. handled = true;
  9981. });
  9982. auto port = svr.bind_to_any_port(HOST);
  9983. auto t = thread([&] { svr.listen_after_bind(); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. t.join();
  9987. ASSERT_FALSE(svr.is_running());
  9988. ASSERT_TRUE(handled);
  9989. std::remove(tmp_path.c_str());
  9990. });
  9991. svr.wait_until_ready();
  9992. FormDataProviderItems providers;
  9993. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  9994. "application/octet-stream"));
  9995. Client cli(HOST, port);
  9996. auto res = cli.Post("/upload", {}, {}, providers);
  9997. ASSERT_TRUE(res);
  9998. EXPECT_EQ(StatusCode::OK_200, res->status);
  9999. }
  10000. TEST(MakeFileBodyTest, Basic) {
  10001. const std::string file_content(4096, 'Z');
  10002. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10003. {
  10004. std::ofstream ofs(tmp_path, std::ios::binary);
  10005. ofs.write(file_content.data(),
  10006. static_cast<std::streamsize>(file_content.size()));
  10007. }
  10008. auto handled = false;
  10009. Server svr;
  10010. svr.Post("/upload", [&](const Request &req, Response &res) {
  10011. EXPECT_EQ(file_content, req.body);
  10012. handled = true;
  10013. res.status = StatusCode::OK_200;
  10014. });
  10015. auto port = svr.bind_to_any_port(HOST);
  10016. auto t = thread([&] { svr.listen_after_bind(); });
  10017. auto se = detail::scope_exit([&] {
  10018. svr.stop();
  10019. t.join();
  10020. ASSERT_FALSE(svr.is_running());
  10021. ASSERT_TRUE(handled);
  10022. std::remove(tmp_path.c_str());
  10023. });
  10024. svr.wait_until_ready();
  10025. auto fb = make_file_body(tmp_path);
  10026. ASSERT_GT(fb.first, 0u);
  10027. Client cli(HOST, port);
  10028. auto res =
  10029. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10030. ASSERT_TRUE(res);
  10031. EXPECT_EQ(StatusCode::OK_200, res->status);
  10032. }
  10033. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10034. static constexpr unsigned int number_of_tasks{1000000};
  10035. std::atomic_uint count{0};
  10036. std::unique_ptr<TaskQueue> task_queue{
  10037. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10038. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10039. auto queued = task_queue->enqueue(
  10040. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10041. EXPECT_TRUE(queued);
  10042. }
  10043. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10044. task_queue->shutdown();
  10045. #else
  10046. EXPECT_NO_THROW(task_queue->shutdown());
  10047. #endif
  10048. EXPECT_EQ(number_of_tasks, count.load());
  10049. }
  10050. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10051. static constexpr unsigned int number_of_tasks{1000000};
  10052. static constexpr unsigned int qlimit{2};
  10053. unsigned int queued_count{0};
  10054. std::atomic_uint count{0};
  10055. std::unique_ptr<TaskQueue> task_queue{
  10056. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10057. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10058. if (task_queue->enqueue(
  10059. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10060. queued_count++;
  10061. }
  10062. }
  10063. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10064. task_queue->shutdown();
  10065. #else
  10066. EXPECT_NO_THROW(task_queue->shutdown());
  10067. #endif
  10068. EXPECT_EQ(queued_count, count.load());
  10069. EXPECT_TRUE(queued_count <= number_of_tasks);
  10070. EXPECT_TRUE(queued_count >= qlimit);
  10071. }
  10072. TEST(TaskQueueTest, MaxQueuedRequests) {
  10073. static constexpr unsigned int qlimit{3};
  10074. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10075. std::condition_variable sem_cv;
  10076. std::mutex sem_mtx;
  10077. int credits = 0;
  10078. bool queued;
  10079. /* Fill up the queue with tasks that will block until we give them credits to
  10080. * complete. */
  10081. for (unsigned int n = 0; n <= qlimit;) {
  10082. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10083. std::unique_lock<std::mutex> lock(sem_mtx);
  10084. while (credits <= 0) {
  10085. sem_cv.wait(lock);
  10086. }
  10087. /* Consume the credit and signal the test code if they are all gone. */
  10088. if (--credits == 0) { sem_cv.notify_one(); }
  10089. });
  10090. if (n < qlimit) {
  10091. /* The first qlimit enqueues must succeed. */
  10092. EXPECT_TRUE(queued);
  10093. } else {
  10094. /* The last one will succeed only when the worker thread
  10095. * starts and dequeues the first blocking task. Although
  10096. * not necessary for the correctness of this test, we sleep for
  10097. * a short while to avoid busy waiting. */
  10098. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10099. }
  10100. if (queued) { n++; }
  10101. }
  10102. /* Further enqueues must fail since the queue is full. */
  10103. for (auto i = 0; i < 4; i++) {
  10104. queued = task_queue->enqueue([] {});
  10105. EXPECT_FALSE(queued);
  10106. }
  10107. /* Give the credits to allow the previous tasks to complete. */
  10108. {
  10109. std::unique_lock<std::mutex> lock(sem_mtx);
  10110. credits += qlimit + 1;
  10111. }
  10112. sem_cv.notify_all();
  10113. /* Wait for all the credits to be consumed. */
  10114. {
  10115. std::unique_lock<std::mutex> lock(sem_mtx);
  10116. while (credits > 0) {
  10117. sem_cv.wait(lock);
  10118. }
  10119. }
  10120. /* Check that we are able again to enqueue at least qlimit tasks. */
  10121. for (unsigned int i = 0; i < qlimit; i++) {
  10122. queued = task_queue->enqueue([] {});
  10123. EXPECT_TRUE(queued);
  10124. }
  10125. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10126. task_queue->shutdown();
  10127. #else
  10128. EXPECT_NO_THROW(task_queue->shutdown());
  10129. #endif
  10130. }
  10131. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10132. Server svr;
  10133. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10134. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10135. });
  10136. svr.Get("/hello", [](const Request &req, Response &res) {
  10137. res.set_content(req.get_param_value("key"), "text/plain");
  10138. });
  10139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10140. auto se = detail::scope_exit([&] {
  10141. svr.stop();
  10142. thread.join();
  10143. ASSERT_FALSE(svr.is_running());
  10144. });
  10145. svr.wait_until_ready();
  10146. {
  10147. Client cli(HOST, PORT);
  10148. cli.set_follow_location(true);
  10149. auto res = cli.Get("/");
  10150. ASSERT_TRUE(res);
  10151. EXPECT_EQ(StatusCode::OK_200, res->status);
  10152. EXPECT_EQ("val&key2=val2", res->body);
  10153. }
  10154. }
  10155. #endif
  10156. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10157. Server svr;
  10158. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10159. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10160. });
  10161. svr.Get("/hello", [](const Request &req, Response &res) {
  10162. res.set_content(req.get_param_value("key"), "text/plain");
  10163. });
  10164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10165. auto se = detail::scope_exit([&] {
  10166. svr.stop();
  10167. thread.join();
  10168. ASSERT_FALSE(svr.is_running());
  10169. });
  10170. svr.wait_until_ready();
  10171. {
  10172. Client cli(HOST, PORT);
  10173. cli.set_follow_location(true);
  10174. auto res = cli.Get("/");
  10175. ASSERT_TRUE(res);
  10176. EXPECT_EQ(StatusCode::OK_200, res->status);
  10177. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10178. }
  10179. }
  10180. #ifdef CPPHTTPLIB_SSL_ENABLED
  10181. TEST(RedirectTest, Issue2185_Online) {
  10182. SSLClient client("github.com");
  10183. client.set_follow_location(true);
  10184. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10185. "Coollab-Windows.zip");
  10186. ASSERT_TRUE(res);
  10187. EXPECT_EQ(StatusCode::OK_200, res->status);
  10188. EXPECT_EQ(9920427U, res->body.size());
  10189. }
  10190. #endif
  10191. TEST(VulnerabilityTest, CRLFInjection) {
  10192. Server svr;
  10193. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10194. res.set_content("Hello 1", "text/plain");
  10195. });
  10196. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10197. res.set_content("Hello 2", "text/plain");
  10198. });
  10199. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10200. res.set_content("Hello 3", "text/plain");
  10201. });
  10202. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10203. res.set_content("Hello 4", "text/plain");
  10204. });
  10205. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10206. for (const auto &x : req.headers) {
  10207. auto key = x.first;
  10208. EXPECT_STRNE("evil", key.c_str());
  10209. }
  10210. });
  10211. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10212. auto se = detail::scope_exit([&] {
  10213. svr.stop();
  10214. thread.join();
  10215. ASSERT_FALSE(svr.is_running());
  10216. });
  10217. svr.wait_until_ready();
  10218. {
  10219. Client cli(HOST, PORT);
  10220. cli.Post("/test1", "A=B",
  10221. "application/x-www-form-urlencoded\r\nevil: hello1");
  10222. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10223. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10224. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10225. }
  10226. }
  10227. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10228. auto server_thread = std::thread([] {
  10229. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10230. default_socket_options(srv);
  10231. sockaddr_in addr{};
  10232. addr.sin_family = AF_INET;
  10233. addr.sin_port = htons(PORT + 1);
  10234. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10235. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10236. ::listen(srv, 1);
  10237. sockaddr_in cli_addr{};
  10238. socklen_t cli_len = sizeof(cli_addr);
  10239. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10240. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10241. std::string buf_all;
  10242. char buf[2048];
  10243. ssize_t n;
  10244. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10245. buf_all.append(buf, static_cast<size_t>(n));
  10246. size_t pos;
  10247. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10248. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10249. auto e = request_block.find("\r\n");
  10250. if (e != std::string::npos) {
  10251. auto request_line = request_block.substr(0, e);
  10252. std::string msg =
  10253. "CRLF injection detected in request line: '" + request_line + "'";
  10254. EXPECT_FALSE(true) << msg;
  10255. }
  10256. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10257. ::send(cli,
  10258. #ifdef _WIN32
  10259. static_cast<const char *>(resp.c_str()),
  10260. static_cast<int>(resp.size()),
  10261. #else
  10262. resp.c_str(), resp.size(),
  10263. #endif
  10264. 0);
  10265. buf_all.erase(0, pos + 4);
  10266. }
  10267. }
  10268. detail::close_socket(cli);
  10269. detail::close_socket(srv);
  10270. });
  10271. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10272. auto cli = Client("127.0.0.1", PORT + 1);
  10273. auto headers = Headers{
  10274. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10275. {"Connection", "keep-alive"}};
  10276. auto res = cli.Get("/hi", headers);
  10277. EXPECT_FALSE(res);
  10278. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10279. server_thread.join();
  10280. }
  10281. TEST(PathParamsTest, StaticMatch) {
  10282. const auto pattern = "/users/all";
  10283. detail::PathParamsMatcher matcher(pattern);
  10284. Request request;
  10285. request.path = "/users/all";
  10286. ASSERT_TRUE(matcher.match(request));
  10287. std::unordered_map<std::string, std::string> expected_params = {};
  10288. EXPECT_EQ(request.path_params, expected_params);
  10289. }
  10290. TEST(PathParamsTest, StaticMismatch) {
  10291. const auto pattern = "/users/all";
  10292. detail::PathParamsMatcher matcher(pattern);
  10293. Request request;
  10294. request.path = "/users/1";
  10295. ASSERT_FALSE(matcher.match(request));
  10296. }
  10297. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10298. const auto pattern = "/users/:id/subscriptions";
  10299. detail::PathParamsMatcher matcher(pattern);
  10300. Request request;
  10301. request.path = "/users/42/subscriptions";
  10302. ASSERT_TRUE(matcher.match(request));
  10303. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10304. EXPECT_EQ(request.path_params, expected_params);
  10305. }
  10306. TEST(PathParamsTest, SingleParamInTheEnd) {
  10307. const auto pattern = "/users/:id";
  10308. detail::PathParamsMatcher matcher(pattern);
  10309. Request request;
  10310. request.path = "/users/24";
  10311. ASSERT_TRUE(matcher.match(request));
  10312. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10313. EXPECT_EQ(request.path_params, expected_params);
  10314. }
  10315. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10316. const auto pattern = "/users/:id/";
  10317. detail::PathParamsMatcher matcher(pattern);
  10318. Request request;
  10319. request.path = "/users/42/";
  10320. ASSERT_TRUE(matcher.match(request));
  10321. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10322. EXPECT_EQ(request.path_params, expected_params);
  10323. }
  10324. TEST(PathParamsTest, EmptyParam) {
  10325. const auto pattern = "/users/:id/";
  10326. detail::PathParamsMatcher matcher(pattern);
  10327. Request request;
  10328. request.path = "/users//";
  10329. ASSERT_TRUE(matcher.match(request));
  10330. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10331. EXPECT_EQ(request.path_params, expected_params);
  10332. }
  10333. TEST(PathParamsTest, FragmentMismatch) {
  10334. const auto pattern = "/users/:id/";
  10335. detail::PathParamsMatcher matcher(pattern);
  10336. Request request;
  10337. request.path = "/admins/24/";
  10338. ASSERT_FALSE(matcher.match(request));
  10339. }
  10340. TEST(PathParamsTest, ExtraFragments) {
  10341. const auto pattern = "/users/:id";
  10342. detail::PathParamsMatcher matcher(pattern);
  10343. Request request;
  10344. request.path = "/users/42/subscriptions";
  10345. ASSERT_FALSE(matcher.match(request));
  10346. }
  10347. TEST(PathParamsTest, MissingTrailingParam) {
  10348. const auto pattern = "/users/:id";
  10349. detail::PathParamsMatcher matcher(pattern);
  10350. Request request;
  10351. request.path = "/users";
  10352. ASSERT_FALSE(matcher.match(request));
  10353. }
  10354. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10355. const auto pattern = "/users/:id/subscriptions";
  10356. detail::PathParamsMatcher matcher(pattern);
  10357. Request request;
  10358. request.path = "/users/subscriptions";
  10359. ASSERT_FALSE(matcher.match(request));
  10360. }
  10361. TEST(PathParamsTest, MultipleParams) {
  10362. const auto pattern = "/users/:userid/subscriptions/:subid";
  10363. detail::PathParamsMatcher matcher(pattern);
  10364. Request request;
  10365. request.path = "/users/42/subscriptions/2";
  10366. ASSERT_TRUE(matcher.match(request));
  10367. std::unordered_map<std::string, std::string> expected_params = {
  10368. {"userid", "42"}, {"subid", "2"}};
  10369. EXPECT_EQ(request.path_params, expected_params);
  10370. }
  10371. TEST(PathParamsTest, SequenceOfParams) {
  10372. const auto pattern = "/values/:x/:y/:z";
  10373. detail::PathParamsMatcher matcher(pattern);
  10374. Request request;
  10375. request.path = "/values/1/2/3";
  10376. ASSERT_TRUE(matcher.match(request));
  10377. std::unordered_map<std::string, std::string> expected_params = {
  10378. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10379. EXPECT_EQ(request.path_params, expected_params);
  10380. }
  10381. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10382. const auto pattern = "/prefix:suffix";
  10383. detail::PathParamsMatcher matcher(pattern);
  10384. Request request;
  10385. request.path = "/prefix:suffix";
  10386. ASSERT_TRUE(matcher.match(request));
  10387. const std::unordered_map<std::string, std::string> expected_params = {};
  10388. EXPECT_EQ(request.path_params, expected_params);
  10389. }
  10390. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10391. // If ipv6 regex working, regex match codepath is taken.
  10392. // else port will default to 80 in Client impl
  10393. int clientImplMagicPort = 80;
  10394. int port = 4321;
  10395. // above ports must be different to avoid false negative
  10396. EXPECT_NE(clientImplMagicPort, port);
  10397. std::string ipV6TestURL = "http://[ff06::c3]";
  10398. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10399. CLIENT_PRIVATE_KEY_FILE);
  10400. EXPECT_EQ(cli.port(), port);
  10401. }
  10402. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10403. auto file_path = "./www/dir/index.html";
  10404. auto dir_path = "./www/dir";
  10405. detail::FileStat stat_file(file_path);
  10406. EXPECT_TRUE(stat_file.is_file());
  10407. EXPECT_FALSE(stat_file.is_dir());
  10408. detail::FileStat stat_dir(dir_path);
  10409. EXPECT_FALSE(stat_dir.is_file());
  10410. EXPECT_TRUE(stat_dir.is_dir());
  10411. }
  10412. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10413. // IPv4 with default HTTP port (80)
  10414. EXPECT_EQ("example.com",
  10415. detail::make_host_and_port_string("example.com", 80, false));
  10416. // IPv4 with default HTTPS port (443)
  10417. EXPECT_EQ("example.com",
  10418. detail::make_host_and_port_string("example.com", 443, true));
  10419. // IPv4 with non-default HTTP port
  10420. EXPECT_EQ("example.com:8080",
  10421. detail::make_host_and_port_string("example.com", 8080, false));
  10422. // IPv4 with non-default HTTPS port
  10423. EXPECT_EQ("example.com:8443",
  10424. detail::make_host_and_port_string("example.com", 8443, true));
  10425. // IPv6 with default HTTP port (80)
  10426. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10427. // IPv6 with default HTTPS port (443)
  10428. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10429. // IPv6 with non-default HTTP port
  10430. EXPECT_EQ("[::1]:8080",
  10431. detail::make_host_and_port_string("::1", 8080, false));
  10432. // IPv6 with non-default HTTPS port
  10433. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10434. // IPv6 full address with default port
  10435. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10436. detail::make_host_and_port_string(
  10437. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10438. // IPv6 full address with non-default port
  10439. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10440. detail::make_host_and_port_string(
  10441. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10442. // IPv6 localhost with non-default port
  10443. EXPECT_EQ("[::1]:3000",
  10444. detail::make_host_and_port_string("::1", 3000, false));
  10445. // IPv6 with zone ID (link-local address) with default port
  10446. EXPECT_EQ("[fe80::1%eth0]",
  10447. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10448. // IPv6 with zone ID (link-local address) with non-default port
  10449. EXPECT_EQ("[fe80::1%eth0]:8080",
  10450. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10451. // Edge case: Port 443 with is_ssl=false (should add port)
  10452. EXPECT_EQ("example.com:443",
  10453. detail::make_host_and_port_string("example.com", 443, false));
  10454. // Edge case: Port 80 with is_ssl=true (should add port)
  10455. EXPECT_EQ("example.com:80",
  10456. detail::make_host_and_port_string("example.com", 80, true));
  10457. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10458. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10459. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10460. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10461. // Security fix: Already bracketed IPv6 should not get double brackets
  10462. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10463. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10464. EXPECT_EQ("[::1]:8080",
  10465. detail::make_host_and_port_string("[::1]", 8080, false));
  10466. EXPECT_EQ("[2001:db8::1]:8080",
  10467. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10468. EXPECT_EQ("[fe80::1%eth0]",
  10469. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10470. EXPECT_EQ("[fe80::1%eth0]:8080",
  10471. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10472. // Edge case: Empty host (should return as-is)
  10473. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10474. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10475. // This is a known limitation but shouldn't crash
  10476. EXPECT_EQ("[host:name]",
  10477. detail::make_host_and_port_string("host:name", 80, false));
  10478. // Port number edge cases (no validation, but should not crash)
  10479. EXPECT_EQ("example.com:0",
  10480. detail::make_host_and_port_string("example.com", 0, false));
  10481. EXPECT_EQ("example.com:-1",
  10482. detail::make_host_and_port_string("example.com", -1, false));
  10483. EXPECT_EQ("example.com:65535",
  10484. detail::make_host_and_port_string("example.com", 65535, false));
  10485. EXPECT_EQ("example.com:65536",
  10486. detail::make_host_and_port_string("example.com", 65536, false));
  10487. }
  10488. #ifdef CPPHTTPLIB_SSL_ENABLED
  10489. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10490. httplib::SSLClient cli("roblox.com", 443);
  10491. cli.set_follow_location(true);
  10492. auto res = cli.Get("/");
  10493. ASSERT_TRUE(res);
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. }
  10496. #endif
  10497. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10498. Server svr;
  10499. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10500. EXPECT_EQ(res.status, 400);
  10501. });
  10502. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10503. auto se = detail::scope_exit([&] {
  10504. svr.stop();
  10505. thread.join();
  10506. ASSERT_FALSE(svr.is_running());
  10507. });
  10508. svr.wait_until_ready();
  10509. Client cli(HOST, PORT);
  10510. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10511. }
  10512. TEST(InvalidHeaderCharsTest, is_field_name) {
  10513. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10514. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10515. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10516. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10517. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10518. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10519. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10520. EXPECT_FALSE(detail::fields::is_field_name(""));
  10521. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10522. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10523. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10524. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10525. }
  10526. TEST(InvalidHeaderCharsTest, is_field_value) {
  10527. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10528. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10529. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10530. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10531. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10532. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10533. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10534. EXPECT_TRUE(detail::fields::is_field_value(""));
  10535. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10536. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10537. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10538. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10539. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10540. }
  10541. TEST(InvalidHeaderCharsTest, OnServer) {
  10542. Server svr;
  10543. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10544. std::string header = "Not Set";
  10545. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10546. res.set_header(header, "value");
  10547. res.set_content("Page Content Page Content", "text/plain");
  10548. });
  10549. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10550. std::string header = "Not Set";
  10551. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10552. res.set_header("X-Test", header);
  10553. res.set_content("Page Content Page Content", "text/plain");
  10554. });
  10555. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10556. auto se = detail::scope_exit([&] {
  10557. svr.stop();
  10558. thread.join();
  10559. ASSERT_FALSE(svr.is_running());
  10560. });
  10561. svr.wait_until_ready();
  10562. Client cli(HOST, PORT);
  10563. {
  10564. auto res = cli.Get(
  10565. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10566. ASSERT_TRUE(res);
  10567. EXPECT_EQ("Page Content Page Content", res->body);
  10568. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10569. }
  10570. {
  10571. auto res = cli.Get(
  10572. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10573. ASSERT_TRUE(res);
  10574. EXPECT_EQ("Page Content Page Content", res->body);
  10575. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10576. }
  10577. }
  10578. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10579. auto handled = false;
  10580. Server svr;
  10581. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10582. thread t = thread([&] { svr.listen(HOST, PORT); });
  10583. auto se = detail::scope_exit([&] {
  10584. svr.stop();
  10585. t.join();
  10586. ASSERT_FALSE(svr.is_running());
  10587. ASSERT_FALSE(handled);
  10588. });
  10589. svr.wait_until_ready();
  10590. auto req = "POST /test HTTP/1.1\r\n"
  10591. "Content-Length: x\r\n"
  10592. "\r\n";
  10593. std::string response;
  10594. ASSERT_TRUE(send_request(1, req, &response));
  10595. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10596. response.substr(0, response.find("\r\n")));
  10597. }
  10598. #ifndef _WIN32
  10599. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10600. static constexpr char reject[] = "Unauthorized";
  10601. static constexpr char accept[] = "Upload accepted";
  10602. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10603. Server svr;
  10604. svr.set_expect_100_continue_handler(
  10605. [](const Request & /*req*/, Response &res) {
  10606. res.status = StatusCode::Unauthorized_401;
  10607. res.set_content(reject, "text/plain");
  10608. return res.status;
  10609. });
  10610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10611. res.set_content(accept, "text/plain");
  10612. });
  10613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10614. auto se = detail::scope_exit([&] {
  10615. svr.stop();
  10616. thread.join();
  10617. ASSERT_FALSE(svr.is_running());
  10618. });
  10619. svr.wait_until_ready();
  10620. {
  10621. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  10622. curl_easy_init(), &curl_easy_cleanup};
  10623. ASSERT_NE(curl, nullptr);
  10624. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  10625. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  10626. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  10627. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  10628. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  10629. &curl_slist_free_all};
  10630. ASSERT_NE(list, nullptr);
  10631. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  10632. struct read_data {
  10633. size_t read_size;
  10634. size_t total_size;
  10635. } data = {0, total_size};
  10636. using read_callback_t =
  10637. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10638. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  10639. void *userdata) -> size_t {
  10640. read_data *data = (read_data *)userdata;
  10641. if (!userdata || data->read_size >= data->total_size) { return 0; }
  10642. std::fill_n(ptr, size * nmemb, 'A');
  10643. data->read_size += size * nmemb;
  10644. return size * nmemb;
  10645. };
  10646. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  10647. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  10648. std::vector<char> buffer;
  10649. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  10650. using write_callback_t =
  10651. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  10652. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  10653. void *userdata) -> size_t {
  10654. std::vector<char> *buffer = (std::vector<char> *)userdata;
  10655. buffer->reserve(buffer->size() + size * nmemb + 1);
  10656. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  10657. return size * nmemb;
  10658. };
  10659. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  10660. {
  10661. const auto res = curl_easy_perform(curl.get());
  10662. ASSERT_EQ(res, CURLE_OK);
  10663. }
  10664. {
  10665. auto response_code = long{};
  10666. const auto res =
  10667. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  10668. ASSERT_EQ(res, CURLE_OK);
  10669. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  10670. }
  10671. {
  10672. auto dl = curl_off_t{};
  10673. const auto res =
  10674. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  10675. ASSERT_EQ(res, CURLE_OK);
  10676. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  10677. }
  10678. {
  10679. buffer.push_back('\0');
  10680. ASSERT_STRCASEEQ(buffer.data(), reject);
  10681. }
  10682. }
  10683. }
  10684. #endif
  10685. template <typename S, typename C>
  10686. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  10687. svr.Get("/stream", [&](const Request &, Response &res) {
  10688. auto data = new std::string("01234567890123456789");
  10689. res.set_content_provider(
  10690. data->size(), "text/plain",
  10691. [&, data](size_t offset, size_t length, DataSink &sink) {
  10692. const size_t DATA_CHUNK_SIZE = 4;
  10693. const auto &d = *data;
  10694. std::this_thread::sleep_for(std::chrono::seconds(1));
  10695. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  10696. return true;
  10697. },
  10698. [data](bool success) {
  10699. EXPECT_FALSE(success);
  10700. delete data;
  10701. });
  10702. });
  10703. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  10704. auto i = new size_t(0);
  10705. res.set_content_provider(
  10706. "text/plain",
  10707. [i](size_t, DataSink &sink) {
  10708. if (*i < 5) {
  10709. std::this_thread::sleep_for(std::chrono::seconds(1));
  10710. sink.write("abcd", 4);
  10711. (*i)++;
  10712. } else {
  10713. sink.done();
  10714. }
  10715. return true;
  10716. },
  10717. [i](bool success) {
  10718. EXPECT_FALSE(success);
  10719. delete i;
  10720. });
  10721. });
  10722. svr.Get("/chunked", [&](const Request &, Response &res) {
  10723. auto i = new size_t(0);
  10724. res.set_chunked_content_provider(
  10725. "text/plain",
  10726. [i](size_t, DataSink &sink) {
  10727. if (*i < 5) {
  10728. std::this_thread::sleep_for(std::chrono::seconds(1));
  10729. sink.os << "abcd";
  10730. (*i)++;
  10731. } else {
  10732. sink.done();
  10733. }
  10734. return true;
  10735. },
  10736. [i](bool success) {
  10737. EXPECT_FALSE(success);
  10738. delete i;
  10739. });
  10740. });
  10741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. listen_thread.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.wait_until_ready();
  10748. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  10749. {
  10750. auto start = std::chrono::steady_clock::now();
  10751. auto res = cli.Get("/stream");
  10752. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10753. std::chrono::steady_clock::now() - start)
  10754. .count();
  10755. ASSERT_FALSE(res);
  10756. EXPECT_EQ(Error::Read, res.error());
  10757. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10758. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10759. }
  10760. {
  10761. auto start = std::chrono::steady_clock::now();
  10762. auto res = cli.Get("/stream_without_length");
  10763. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10764. std::chrono::steady_clock::now() - start)
  10765. .count();
  10766. ASSERT_FALSE(res);
  10767. EXPECT_EQ(Error::Read, res.error());
  10768. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10769. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10770. }
  10771. {
  10772. auto start = std::chrono::steady_clock::now();
  10773. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  10774. EXPECT_EQ("abcd", string(data, data_length));
  10775. return true;
  10776. });
  10777. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10778. std::chrono::steady_clock::now() - start)
  10779. .count();
  10780. ASSERT_FALSE(res);
  10781. EXPECT_EQ(Error::Read, res.error());
  10782. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  10783. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  10784. }
  10785. }
  10786. TEST(MaxTimeoutTest, ContentStream) {
  10787. time_t timeout = 2000;
  10788. time_t threshold = 200;
  10789. Server svr;
  10790. Client cli("localhost", PORT);
  10791. max_timeout_test(svr, cli, timeout, threshold);
  10792. }
  10793. #ifdef CPPHTTPLIB_SSL_ENABLED
  10794. TEST(MaxTimeoutTest, ContentStreamSSL) {
  10795. time_t timeout = 2000;
  10796. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  10797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10798. SSLClient cli("localhost", PORT);
  10799. cli.enable_server_certificate_verification(false);
  10800. max_timeout_test(svr, cli, timeout, threshold);
  10801. }
  10802. #endif
  10803. class EventDispatcher {
  10804. public:
  10805. EventDispatcher() {}
  10806. bool wait_event(DataSink *sink) {
  10807. unique_lock<mutex> lk(m_);
  10808. int id = id_;
  10809. // Wait with timeout to prevent hanging if client disconnects
  10810. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  10811. [&] { return cid_ == id; })) {
  10812. return false; // Timeout occurred
  10813. }
  10814. sink->write(message_.data(), message_.size());
  10815. return true;
  10816. }
  10817. void send_event(const string &message) {
  10818. lock_guard<mutex> lk(m_);
  10819. cid_ = id_++;
  10820. message_ = message;
  10821. cv_.notify_all();
  10822. }
  10823. private:
  10824. mutex m_;
  10825. condition_variable cv_;
  10826. atomic_int id_{0};
  10827. atomic_int cid_{-1};
  10828. string message_;
  10829. };
  10830. TEST(ClientInThreadTest, Issue2068) {
  10831. EventDispatcher ed;
  10832. Server svr;
  10833. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  10834. res.set_chunked_content_provider("text/event-stream",
  10835. [&](size_t /*offset*/, DataSink &sink) {
  10836. return ed.wait_event(&sink);
  10837. });
  10838. });
  10839. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10840. svr.wait_until_ready();
  10841. thread event_thread([&] {
  10842. int id = 0;
  10843. while (svr.is_running()) {
  10844. this_thread::sleep_for(chrono::milliseconds(500));
  10845. std::stringstream ss;
  10846. ss << "data: " << id << "\n\n";
  10847. ed.send_event(ss.str());
  10848. id++;
  10849. }
  10850. });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. listen_thread.join();
  10854. event_thread.join();
  10855. ASSERT_FALSE(svr.is_running());
  10856. });
  10857. {
  10858. auto client = detail::make_unique<Client>(HOST, PORT);
  10859. client->set_read_timeout(std::chrono::minutes(10));
  10860. std::atomic<bool> stop{false};
  10861. std::thread t([&] {
  10862. client->Get("/event1",
  10863. [&](const char *, size_t) -> bool { return !stop; });
  10864. });
  10865. std::this_thread::sleep_for(std::chrono::seconds(2));
  10866. stop = true;
  10867. client->stop();
  10868. t.join();
  10869. // Reset client after thread has finished
  10870. client.reset();
  10871. }
  10872. }
  10873. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10874. Server svr;
  10875. svr.Get("/", [](const Request &req, Response &res) {
  10876. EXPECT_EQ(2U, req.trailers.size());
  10877. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10878. // Denied
  10879. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10880. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10881. // Accepted
  10882. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10883. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10884. EXPECT_TRUE(req.has_trailer("X-World"));
  10885. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10886. res.set_content("ok", "text/plain");
  10887. });
  10888. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10889. auto se = detail::scope_exit([&] {
  10890. svr.stop();
  10891. t.join();
  10892. ASSERT_FALSE(svr.is_running());
  10893. });
  10894. svr.wait_until_ready();
  10895. const std::string req = "GET / HTTP/1.1\r\n"
  10896. "Transfer-Encoding: chunked\r\n"
  10897. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10898. "\r\n"
  10899. "0\r\n"
  10900. "Content-Length: 10\r\n"
  10901. "Host: internal.local\r\n"
  10902. "Content-Type: malicious/content\r\n"
  10903. "Cookie: any\r\n"
  10904. "Set-Cookie: any\r\n"
  10905. "X-Forwarded-For: attacker.com\r\n"
  10906. "X-Real-Ip: 1.1.1.1\r\n"
  10907. "X-Hello: hello\r\n"
  10908. "X-World: world\r\n"
  10909. "\r\n";
  10910. std::string res;
  10911. ASSERT_TRUE(send_request(1, req, &res));
  10912. }
  10913. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10914. Server svr;
  10915. std::string observed_remote_addr;
  10916. std::string observed_xff;
  10917. svr.Get("/ip", [&](const Request &req, Response &res) {
  10918. observed_remote_addr = req.remote_addr;
  10919. observed_xff = req.get_header_value("X-Forwarded-For");
  10920. res.set_content("ok", "text/plain");
  10921. });
  10922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli(HOST, PORT);
  10930. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10931. ASSERT_TRUE(res);
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. EXPECT_EQ(observed_xff, "203.0.113.66");
  10934. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10935. observed_remote_addr == "127.0.0.1");
  10936. }
  10937. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10938. Server svr;
  10939. svr.set_trusted_proxies({"203.0.113.66"});
  10940. std::string observed_remote_addr;
  10941. std::string observed_xff;
  10942. svr.Get("/ip", [&](const Request &req, Response &res) {
  10943. observed_remote_addr = req.remote_addr;
  10944. observed_xff = req.get_header_value("X-Forwarded-For");
  10945. res.set_content("ok", "text/plain");
  10946. });
  10947. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10948. auto se = detail::scope_exit([&] {
  10949. svr.stop();
  10950. t.join();
  10951. ASSERT_FALSE(svr.is_running());
  10952. });
  10953. svr.wait_until_ready();
  10954. Client cli(HOST, PORT);
  10955. auto res = cli.Get("/ip");
  10956. ASSERT_TRUE(res);
  10957. EXPECT_EQ(StatusCode::OK_200, res->status);
  10958. EXPECT_EQ(observed_xff, "");
  10959. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10960. observed_remote_addr == "127.0.0.1");
  10961. }
  10962. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10963. Server svr;
  10964. svr.set_trusted_proxies({"203.0.113.66"});
  10965. std::string observed_remote_addr;
  10966. std::string observed_xff;
  10967. svr.Get("/ip", [&](const Request &req, Response &res) {
  10968. observed_remote_addr = req.remote_addr;
  10969. observed_xff = req.get_header_value("X-Forwarded-For");
  10970. res.set_content("ok", "text/plain");
  10971. });
  10972. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10973. auto se = detail::scope_exit([&] {
  10974. svr.stop();
  10975. t.join();
  10976. ASSERT_FALSE(svr.is_running());
  10977. });
  10978. svr.wait_until_ready();
  10979. Client cli(HOST, PORT);
  10980. auto res =
  10981. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10982. ASSERT_TRUE(res);
  10983. EXPECT_EQ(StatusCode::OK_200, res->status);
  10984. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10985. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10986. }
  10987. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10988. Server svr;
  10989. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10990. std::string observed_remote_addr;
  10991. std::string observed_xff;
  10992. svr.Get("/ip", [&](const Request &req, Response &res) {
  10993. observed_remote_addr = req.remote_addr;
  10994. observed_xff = req.get_header_value("X-Forwarded-For");
  10995. res.set_content("ok", "text/plain");
  10996. });
  10997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. t.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. Client cli(HOST, PORT);
  11005. auto res = cli.Get(
  11006. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11007. ASSERT_TRUE(res);
  11008. EXPECT_EQ(StatusCode::OK_200, res->status);
  11009. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11010. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11011. }
  11012. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11013. Server svr;
  11014. svr.set_trusted_proxies({"192.0.2.45"});
  11015. std::string observed_remote_addr;
  11016. std::string observed_xff;
  11017. svr.Get("/ip", [&](const Request &req, Response &res) {
  11018. observed_remote_addr = req.remote_addr;
  11019. observed_xff = req.get_header_value("X-Forwarded-For");
  11020. res.set_content("ok", "text/plain");
  11021. });
  11022. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11023. auto se = detail::scope_exit([&] {
  11024. svr.stop();
  11025. t.join();
  11026. ASSERT_FALSE(svr.is_running());
  11027. });
  11028. svr.wait_until_ready();
  11029. Client cli(HOST, PORT);
  11030. auto res =
  11031. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11032. ASSERT_TRUE(res);
  11033. EXPECT_EQ(StatusCode::OK_200, res->status);
  11034. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11035. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11036. }
  11037. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11038. Server svr;
  11039. svr.set_trusted_proxies({"192.0.2.45"});
  11040. std::string observed_remote_addr;
  11041. std::string observed_xff;
  11042. svr.Get("/ip", [&](const Request &req, Response &res) {
  11043. observed_remote_addr = req.remote_addr;
  11044. observed_xff = req.get_header_value("X-Forwarded-For");
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. Client cli(HOST, PORT);
  11055. auto res = cli.Get(
  11056. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11057. ASSERT_TRUE(res);
  11058. EXPECT_EQ(StatusCode::OK_200, res->status);
  11059. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11060. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11061. }
  11062. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11063. Server svr;
  11064. svr.set_trusted_proxies({"192.0.2.45"});
  11065. std::string observed_remote_addr;
  11066. std::string observed_xff;
  11067. svr.Get("/ip", [&](const Request &req, Response &res) {
  11068. observed_remote_addr = req.remote_addr;
  11069. observed_xff = req.get_header_value("X-Forwarded-For");
  11070. res.set_content("ok", "text/plain");
  11071. });
  11072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11073. auto se = detail::scope_exit([&] {
  11074. svr.stop();
  11075. t.join();
  11076. ASSERT_FALSE(svr.is_running());
  11077. });
  11078. svr.wait_until_ready();
  11079. std::string raw_req =
  11080. "GET /ip HTTP/1.1\r\n"
  11081. "Host: localhost\r\n"
  11082. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11083. "Connection: close\r\n"
  11084. "\r\n";
  11085. std::string out;
  11086. ASSERT_TRUE(send_request(5, raw_req, &out));
  11087. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11088. // Header parser trims surrounding whitespace of the header value
  11089. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11090. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11091. }
  11092. #ifndef _WIN32
  11093. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11094. Server svr;
  11095. svr.Post("/post", [&](const Request &req, Response &res) {
  11096. res.set_content(req.body, "text/plain");
  11097. });
  11098. svr.Put("/put", [&](const Request &req, Response &res) {
  11099. res.set_content(req.body, "text/plain");
  11100. });
  11101. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11102. res.set_content(req.body, "text/plain");
  11103. });
  11104. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11105. res.set_content(req.body, "text/plain");
  11106. });
  11107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. t.join();
  11111. ASSERT_FALSE(svr.is_running());
  11112. });
  11113. svr.wait_until_ready();
  11114. std::string resp;
  11115. // POST without Content-Length
  11116. ASSERT_TRUE(send_request(5,
  11117. "POST /post HTTP/1.1\r\n"
  11118. "Host: localhost\r\n"
  11119. "Connection: close\r\n"
  11120. "\r\n",
  11121. &resp));
  11122. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11123. // PUT without Content-Length
  11124. resp.clear();
  11125. ASSERT_TRUE(send_request(5,
  11126. "PUT /put HTTP/1.1\r\n"
  11127. "Host: localhost\r\n"
  11128. "Connection: close\r\n"
  11129. "\r\n",
  11130. &resp));
  11131. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11132. // PATCH without Content-Length
  11133. resp.clear();
  11134. ASSERT_TRUE(send_request(5,
  11135. "PATCH /patch HTTP/1.1\r\n"
  11136. "Host: localhost\r\n"
  11137. "Connection: close\r\n"
  11138. "\r\n",
  11139. &resp));
  11140. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11141. // DELETE without Content-Length
  11142. resp.clear();
  11143. ASSERT_TRUE(send_request(5,
  11144. "DELETE /delete HTTP/1.1\r\n"
  11145. "Host: localhost\r\n"
  11146. "Connection: close\r\n"
  11147. "\r\n",
  11148. &resp));
  11149. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11150. }
  11151. #endif
  11152. //==============================================================================
  11153. // open_stream() Tests
  11154. //==============================================================================
  11155. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11156. std::string result;
  11157. char buf[8192];
  11158. ssize_t n;
  11159. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11160. result.append(buf, static_cast<size_t>(n));
  11161. }
  11162. return result;
  11163. }
  11164. // Mock stream for unit tests
  11165. class MockStream : public Stream {
  11166. public:
  11167. std::string data;
  11168. size_t pos = 0;
  11169. ssize_t error_after = -1; // -1 = no error
  11170. explicit MockStream(const std::string &d, ssize_t err = -1)
  11171. : data(d), error_after(err) {}
  11172. bool is_readable() const override { return true; }
  11173. bool wait_readable() const override { return true; }
  11174. bool wait_writable() const override { return true; }
  11175. ssize_t read(char *ptr, size_t size) override {
  11176. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11177. if (pos >= data.size()) return 0;
  11178. size_t limit =
  11179. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11180. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11181. std::memcpy(ptr, data.data() + pos, to_read);
  11182. pos += to_read;
  11183. return static_cast<ssize_t>(to_read);
  11184. }
  11185. ssize_t write(const char *, size_t) override { return -1; }
  11186. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11187. ip = "127.0.0.1";
  11188. port = 0;
  11189. }
  11190. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11191. ip = "127.0.0.1";
  11192. port = 0;
  11193. }
  11194. socket_t socket() const override { return INVALID_SOCKET; }
  11195. time_t duration() const override { return 0; }
  11196. };
  11197. TEST(StreamHandleTest, Basic) {
  11198. ClientImpl::StreamHandle handle;
  11199. EXPECT_FALSE(handle.is_valid());
  11200. handle.response = detail::make_unique<Response>();
  11201. handle.error = Error::Connection;
  11202. EXPECT_FALSE(handle.is_valid());
  11203. handle.error = Error::Success;
  11204. EXPECT_TRUE(handle.is_valid());
  11205. }
  11206. TEST(BodyReaderTest, Basic) {
  11207. MockStream stream("Hello, World!");
  11208. detail::BodyReader reader;
  11209. reader.stream = &stream;
  11210. reader.content_length = 13;
  11211. char buf[32];
  11212. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11213. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11214. EXPECT_TRUE(reader.eof);
  11215. }
  11216. TEST(BodyReaderTest, NoStream) {
  11217. detail::BodyReader reader;
  11218. char buf[32];
  11219. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11220. EXPECT_EQ(Error::Connection, reader.last_error);
  11221. }
  11222. TEST(BodyReaderTest, Error) {
  11223. MockStream stream("Hello, World!", 5);
  11224. detail::BodyReader reader;
  11225. reader.stream = &stream;
  11226. reader.content_length = 13;
  11227. char buf[32];
  11228. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11229. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11230. EXPECT_EQ(Error::Read, reader.last_error);
  11231. }
  11232. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11233. // Mock-based StreamHandle tests relying on private internals are removed.
  11234. class OpenStreamTest : public ::testing::Test {
  11235. protected:
  11236. void SetUp() override {
  11237. svr_.Get("/hello", [](const Request &, Response &res) {
  11238. res.set_content("Hello World!", "text/plain");
  11239. });
  11240. svr_.Get("/large", [](const Request &, Response &res) {
  11241. res.set_content(std::string(10000, 'X'), "text/plain");
  11242. });
  11243. svr_.Get("/chunked", [](const Request &, Response &res) {
  11244. res.set_chunked_content_provider("text/plain",
  11245. [](size_t offset, DataSink &sink) {
  11246. if (offset < 15) {
  11247. sink.write("chunk", 5);
  11248. return true;
  11249. }
  11250. sink.done();
  11251. return true;
  11252. });
  11253. });
  11254. svr_.Get("/compressible", [](const Request &, Response &res) {
  11255. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11256. DataSink &sink) {
  11257. if (offset < 100 * 1024) {
  11258. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11259. sink.write(chunk.data(), chunk.size());
  11260. return true;
  11261. }
  11262. sink.done();
  11263. return true;
  11264. });
  11265. });
  11266. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11267. [](const Request & /*req*/, Response &res) {
  11268. auto i = new int(0);
  11269. res.set_header("Trailer", "Content-Length, X-Allowed");
  11270. res.set_chunked_content_provider(
  11271. "text/plain",
  11272. [i](size_t /*offset*/, DataSink &sink) {
  11273. switch (*i) {
  11274. case 0: sink.os << "123"; break;
  11275. case 1: sink.os << "456"; break;
  11276. case 2: sink.os << "789"; break;
  11277. case 3: {
  11278. sink.done_with_trailer(
  11279. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11280. } break;
  11281. }
  11282. (*i)++;
  11283. return true;
  11284. },
  11285. [i](bool success) {
  11286. EXPECT_TRUE(success);
  11287. delete i;
  11288. });
  11289. });
  11290. // Echo headers endpoint for header-related tests
  11291. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11292. std::string body;
  11293. for (const auto &h : req.headers) {
  11294. body.append(h.first);
  11295. body.push_back(':');
  11296. body.append(h.second);
  11297. body.push_back('\n');
  11298. }
  11299. res.set_content(body, "text/plain");
  11300. });
  11301. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11302. std::string body;
  11303. for (const auto &h : req.headers) {
  11304. body.append(h.first);
  11305. body.push_back(':');
  11306. body.append(h.second);
  11307. body.push_back('\n');
  11308. }
  11309. res.set_content(body, "text/plain");
  11310. });
  11311. port_ = svr_.bind_to_any_port("127.0.0.1");
  11312. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11313. svr_.wait_until_ready();
  11314. }
  11315. void TearDown() override {
  11316. svr_.stop();
  11317. if (thread_.joinable()) thread_.join();
  11318. }
  11319. Server svr_;
  11320. std::thread thread_;
  11321. int port_ = 0;
  11322. };
  11323. TEST_F(OpenStreamTest, Basic) {
  11324. Client cli("127.0.0.1", port_);
  11325. auto handle = cli.open_stream("GET", "/hello");
  11326. EXPECT_TRUE(handle.is_valid());
  11327. EXPECT_EQ("Hello World!", read_all(handle));
  11328. }
  11329. TEST_F(OpenStreamTest, SmallBuffer) {
  11330. Client cli("127.0.0.1", port_);
  11331. auto handle = cli.open_stream("GET", "/hello");
  11332. std::string result;
  11333. char buf[4];
  11334. ssize_t n;
  11335. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11336. result.append(buf, static_cast<size_t>(n));
  11337. EXPECT_EQ("Hello World!", result);
  11338. }
  11339. TEST_F(OpenStreamTest, DefaultHeaders) {
  11340. Client cli("127.0.0.1", port_);
  11341. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11342. {
  11343. auto handle = cli.open_stream("GET", "/echo-headers");
  11344. ASSERT_TRUE(handle.is_valid());
  11345. auto body = read_all(handle);
  11346. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11347. std::string::npos);
  11348. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11349. std::string::npos);
  11350. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11351. }
  11352. // open_stream POST with body and no explicit content_type should NOT add
  11353. // text/plain Content-Type (behavior differs from non-streaming path), but
  11354. // should include Content-Length
  11355. {
  11356. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11357. ASSERT_TRUE(handle.is_valid());
  11358. auto body = read_all(handle);
  11359. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11360. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11361. }
  11362. // open_stream POST with explicit Content-Type should preserve it
  11363. {
  11364. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11365. {{"Content-Type", "application/custom"}},
  11366. "{}", "application/custom");
  11367. ASSERT_TRUE(handle.is_valid());
  11368. auto body = read_all(handle);
  11369. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11370. }
  11371. // User-specified User-Agent must not be overwritten for stream API
  11372. {
  11373. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11374. {{"User-Agent", "MyAgent/1.2"}});
  11375. ASSERT_TRUE(handle.is_valid());
  11376. auto body = read_all(handle);
  11377. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11378. }
  11379. }
  11380. TEST_F(OpenStreamTest, Large) {
  11381. Client cli("127.0.0.1", port_);
  11382. auto handle = cli.open_stream("GET", "/large");
  11383. EXPECT_EQ(10000u, read_all(handle).size());
  11384. }
  11385. TEST_F(OpenStreamTest, ConnectionError) {
  11386. Client cli("127.0.0.1", 9999);
  11387. auto handle = cli.open_stream("GET", "/hello");
  11388. EXPECT_FALSE(handle.is_valid());
  11389. }
  11390. TEST_F(OpenStreamTest, Chunked) {
  11391. Client cli("127.0.0.1", port_);
  11392. auto handle = cli.open_stream("GET", "/chunked");
  11393. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11394. "Transfer-Encoding") == "chunked");
  11395. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11396. }
  11397. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11398. Client cli("127.0.0.1", port_);
  11399. auto handle =
  11400. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11401. ASSERT_TRUE(handle.is_valid());
  11402. // Consume body to allow trailers to be received/parsed
  11403. auto body = read_all(handle);
  11404. // Explicitly parse trailers (ensure trailers are available for assertion)
  11405. handle.parse_trailers_if_needed();
  11406. EXPECT_EQ(std::string("123456789"), body);
  11407. // The response should include a Trailer header declaring both names
  11408. ASSERT_TRUE(handle.response);
  11409. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11410. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11411. handle.response->get_header_value("Trailer"));
  11412. // Prohibited trailer must not be present
  11413. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11414. // Allowed trailer should be present
  11415. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11416. EXPECT_EQ(std::string("yes"),
  11417. handle.response->get_trailer_value("X-Allowed"));
  11418. // Verify trailers are NOT present as regular headers
  11419. EXPECT_EQ(std::string(""),
  11420. handle.response->get_header_value("Content-Length"));
  11421. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11422. }
  11423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11424. TEST_F(OpenStreamTest, Gzip) {
  11425. Client cli("127.0.0.1", port_);
  11426. auto handle = cli.open_stream("GET", "/compressible", {},
  11427. {{"Accept-Encoding", "gzip"}});
  11428. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11429. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11430. }
  11431. #endif
  11432. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11433. TEST_F(OpenStreamTest, Brotli) {
  11434. Client cli("127.0.0.1", port_);
  11435. auto handle =
  11436. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11437. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11438. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11439. }
  11440. #endif
  11441. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11442. TEST_F(OpenStreamTest, Zstd) {
  11443. Client cli("127.0.0.1", port_);
  11444. auto handle = cli.open_stream("GET", "/compressible", {},
  11445. {{"Accept-Encoding", "zstd"}});
  11446. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11447. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11448. }
  11449. #endif
  11450. #ifdef CPPHTTPLIB_SSL_ENABLED
  11451. class SSLOpenStreamTest : public ::testing::Test {
  11452. protected:
  11453. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11454. void SetUp() override {
  11455. svr_.Get("/hello", [](const Request &, Response &res) {
  11456. res.set_content("Hello SSL World!", "text/plain");
  11457. });
  11458. svr_.Get("/chunked", [](const Request &, Response &res) {
  11459. res.set_chunked_content_provider("text/plain",
  11460. [](size_t offset, DataSink &sink) {
  11461. if (offset < 15) {
  11462. sink.write("chunk", 5);
  11463. return true;
  11464. }
  11465. sink.done();
  11466. return true;
  11467. });
  11468. });
  11469. svr_.Post("/echo", [](const Request &req, Response &res) {
  11470. res.set_content(req.body, req.get_header_value("Content-Type"));
  11471. });
  11472. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  11473. std::string body = req.body;
  11474. res.set_chunked_content_provider(
  11475. "text/plain", [body](size_t offset, DataSink &sink) {
  11476. if (offset < body.size()) {
  11477. sink.write(body.data() + offset, body.size() - offset);
  11478. }
  11479. sink.done();
  11480. return true;
  11481. });
  11482. });
  11483. port_ = svr_.bind_to_any_port("127.0.0.1");
  11484. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11485. svr_.wait_until_ready();
  11486. }
  11487. void TearDown() override {
  11488. svr_.stop();
  11489. if (thread_.joinable()) thread_.join();
  11490. }
  11491. SSLServer svr_;
  11492. std::thread thread_;
  11493. int port_ = 0;
  11494. };
  11495. TEST_F(SSLOpenStreamTest, Basic) {
  11496. SSLClient cli("127.0.0.1", port_);
  11497. cli.enable_server_certificate_verification(false);
  11498. auto handle = cli.open_stream("GET", "/hello");
  11499. ASSERT_TRUE(handle.is_valid());
  11500. EXPECT_EQ("Hello SSL World!", read_all(handle));
  11501. }
  11502. TEST_F(SSLOpenStreamTest, Chunked) {
  11503. SSLClient cli("127.0.0.1", port_);
  11504. cli.enable_server_certificate_verification(false);
  11505. auto handle = cli.open_stream("GET", "/chunked");
  11506. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11507. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11508. "Transfer-Encoding") == "chunked");
  11509. auto body = read_all(handle);
  11510. EXPECT_EQ("chunkchunkchunk", body);
  11511. }
  11512. TEST_F(SSLOpenStreamTest, Post) {
  11513. SSLClient cli("127.0.0.1", port_);
  11514. cli.enable_server_certificate_verification(false);
  11515. auto handle =
  11516. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  11517. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  11518. EXPECT_EQ(200, handle.response->status);
  11519. auto body = read_all(handle);
  11520. EXPECT_EQ("Hello SSL POST", body);
  11521. }
  11522. TEST_F(SSLOpenStreamTest, PostChunked) {
  11523. SSLClient cli("127.0.0.1", port_);
  11524. cli.enable_server_certificate_verification(false);
  11525. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  11526. "Chunked SSL Data", "text/plain");
  11527. ASSERT_TRUE(handle.is_valid());
  11528. EXPECT_EQ(200, handle.response->status);
  11529. auto body = read_all(handle);
  11530. EXPECT_EQ("Chunked SSL Data", body);
  11531. }
  11532. #endif // CPPHTTPLIB_SSL_ENABLED
  11533. //==============================================================================
  11534. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  11535. // results for various scenarios.
  11536. //==============================================================================
  11537. TEST(ParityTest, GetVsOpenStream) {
  11538. Server svr;
  11539. const std::string path = "/parity";
  11540. const std::string content = "Parity test content: hello world";
  11541. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11542. res.set_content(content, "text/plain");
  11543. });
  11544. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11545. auto se = detail::scope_exit([&] {
  11546. svr.stop();
  11547. t.join();
  11548. ASSERT_FALSE(svr.is_running());
  11549. });
  11550. svr.wait_until_ready();
  11551. Client cli(HOST, PORT);
  11552. // Non-stream path
  11553. auto r1 = cli.Get(path);
  11554. ASSERT_TRUE(r1);
  11555. EXPECT_EQ(StatusCode::OK_200, r1->status);
  11556. // Stream path
  11557. auto h = cli.open_stream("GET", path);
  11558. ASSERT_TRUE(h.is_valid());
  11559. EXPECT_EQ(r1->body, read_all(h));
  11560. }
  11561. // Helper to compress data with provided compressor type T
  11562. template <typename Compressor>
  11563. static std::string compress_payload_for_parity(const std::string &in) {
  11564. std::string out;
  11565. Compressor compressor;
  11566. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  11567. [&](const char *data, size_t n) {
  11568. out.append(data, n);
  11569. return true;
  11570. });
  11571. EXPECT_TRUE(ok);
  11572. return out;
  11573. }
  11574. // Helper function for compression parity tests
  11575. template <typename Compressor>
  11576. static void test_compression_parity(const std::string &original,
  11577. const std::string &path,
  11578. const std::string &encoding) {
  11579. const std::string compressed =
  11580. compress_payload_for_parity<Compressor>(original);
  11581. Server svr;
  11582. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  11583. res.set_content(compressed, "application/octet-stream");
  11584. res.set_header("Content-Encoding", encoding);
  11585. });
  11586. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  11587. auto se = detail::scope_exit([&] {
  11588. svr.stop();
  11589. t.join();
  11590. ASSERT_FALSE(svr.is_running());
  11591. });
  11592. svr.wait_until_ready();
  11593. Client cli(HOST, PORT);
  11594. // Non-streaming
  11595. {
  11596. auto res = cli.Get(path);
  11597. ASSERT_TRUE(res);
  11598. EXPECT_EQ(StatusCode::OK_200, res->status);
  11599. EXPECT_EQ(original, res->body);
  11600. }
  11601. // Streaming
  11602. {
  11603. auto h = cli.open_stream("GET", path);
  11604. ASSERT_TRUE(h.is_valid());
  11605. EXPECT_EQ(original, read_all(h));
  11606. }
  11607. }
  11608. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11609. TEST(ParityTest, Gzip) {
  11610. test_compression_parity<detail::gzip_compressor>(
  11611. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  11612. }
  11613. #endif
  11614. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11615. TEST(ParityTest, Brotli) {
  11616. test_compression_parity<detail::brotli_compressor>(
  11617. "Hello, brotli parity test payload", "/parity-br", "br");
  11618. }
  11619. #endif
  11620. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11621. TEST(ParityTest, Zstd) {
  11622. test_compression_parity<detail::zstd_compressor>(
  11623. "Zstandard parity test payload", "/parity-zstd", "zstd");
  11624. }
  11625. #endif
  11626. //==============================================================================
  11627. // New Stream API Tests
  11628. //==============================================================================
  11629. inline std::string read_body(httplib::stream::Result &result) {
  11630. std::string body;
  11631. while (result.next()) {
  11632. body.append(result.data(), result.size());
  11633. }
  11634. return body;
  11635. }
  11636. TEST(ClientConnectionTest, Basic) {
  11637. httplib::ClientConnection conn;
  11638. EXPECT_FALSE(conn.is_open());
  11639. conn.sock = 1;
  11640. EXPECT_TRUE(conn.is_open());
  11641. httplib::ClientConnection conn2(std::move(conn));
  11642. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  11643. conn2.sock = INVALID_SOCKET;
  11644. }
  11645. // Unified test server for all stream::* tests
  11646. class StreamApiTest : public ::testing::Test {
  11647. protected:
  11648. void SetUp() override {
  11649. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11650. res.set_content("Hello World!", "text/plain");
  11651. });
  11652. svr_.Get("/echo-params",
  11653. [](const httplib::Request &req, httplib::Response &res) {
  11654. std::string r;
  11655. for (const auto &p : req.params) {
  11656. if (!r.empty()) r += "&";
  11657. r += p.first + "=" + p.second;
  11658. }
  11659. res.set_content(r, "text/plain");
  11660. });
  11661. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11662. res.set_content(req.body, req.get_header_value("Content-Type"));
  11663. });
  11664. svr_.Post("/echo-headers",
  11665. [](const httplib::Request &req, httplib::Response &res) {
  11666. std::string r;
  11667. for (const auto &h : req.headers)
  11668. r += h.first + ": " + h.second + "\n";
  11669. res.set_content(r, "text/plain");
  11670. });
  11671. svr_.Post("/echo-params",
  11672. [](const httplib::Request &req, httplib::Response &res) {
  11673. std::string r = "params:";
  11674. for (const auto &p : req.params)
  11675. r += p.first + "=" + p.second + ";";
  11676. res.set_content(r + " body:" + req.body, "text/plain");
  11677. });
  11678. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  11679. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  11680. });
  11681. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11682. res.set_content("PUT:" + req.body, "text/plain");
  11683. });
  11684. svr_.Patch("/echo",
  11685. [](const httplib::Request &req, httplib::Response &res) {
  11686. res.set_content("PATCH:" + req.body, "text/plain");
  11687. });
  11688. svr_.Delete(
  11689. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  11690. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  11691. "text/plain");
  11692. });
  11693. svr_.Get("/head-test",
  11694. [](const httplib::Request &, httplib::Response &res) {
  11695. res.set_content("body for HEAD", "text/plain");
  11696. });
  11697. svr_.Options("/options",
  11698. [](const httplib::Request &, httplib::Response &res) {
  11699. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  11700. });
  11701. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  11702. svr_.wait_until_ready();
  11703. }
  11704. void TearDown() override {
  11705. svr_.stop();
  11706. if (thread_.joinable()) thread_.join();
  11707. }
  11708. httplib::Server svr_;
  11709. std::thread thread_;
  11710. };
  11711. // stream::Get tests
  11712. TEST_F(StreamApiTest, GetBasic) {
  11713. httplib::Client cli(HOST, PORT);
  11714. auto result = httplib::stream::Get(cli, "/hello");
  11715. ASSERT_TRUE(result.is_valid());
  11716. EXPECT_EQ(200, result.status());
  11717. EXPECT_EQ("Hello World!", read_body(result));
  11718. }
  11719. TEST_F(StreamApiTest, GetWithParams) {
  11720. httplib::Client cli(HOST, PORT);
  11721. httplib::Params params{{"foo", "bar"}};
  11722. auto result = httplib::stream::Get(cli, "/echo-params", params);
  11723. ASSERT_TRUE(result.is_valid());
  11724. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  11725. }
  11726. TEST_F(StreamApiTest, GetConnectionError) {
  11727. httplib::Client cli(HOST, 9999);
  11728. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  11729. }
  11730. TEST_F(StreamApiTest, Get404) {
  11731. httplib::Client cli(HOST, PORT);
  11732. auto result = httplib::stream::Get(cli, "/nonexistent");
  11733. EXPECT_TRUE(result.is_valid());
  11734. EXPECT_EQ(404, result.status());
  11735. }
  11736. // stream::Post tests
  11737. TEST_F(StreamApiTest, PostBasic) {
  11738. httplib::Client cli(HOST, PORT);
  11739. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  11740. "application/json");
  11741. ASSERT_TRUE(result.is_valid());
  11742. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  11743. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  11744. }
  11745. TEST_F(StreamApiTest, PostWithHeaders) {
  11746. httplib::Client cli(HOST, PORT);
  11747. httplib::Headers headers{{"X-Custom", "value"}};
  11748. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  11749. "text/plain");
  11750. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  11751. }
  11752. TEST_F(StreamApiTest, PostWithParams) {
  11753. httplib::Client cli(HOST, PORT);
  11754. httplib::Params params{{"k", "v"}};
  11755. auto result =
  11756. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  11757. auto body = read_body(result);
  11758. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  11759. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  11760. }
  11761. TEST_F(StreamApiTest, PostLarge) {
  11762. httplib::Client cli(HOST, PORT);
  11763. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  11764. size_t total = 0;
  11765. while (result.next()) {
  11766. total += result.size();
  11767. }
  11768. EXPECT_EQ(100u * 1024u, total);
  11769. }
  11770. // stream::Put/Patch tests
  11771. TEST_F(StreamApiTest, PutAndPatch) {
  11772. httplib::Client cli(HOST, PORT);
  11773. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  11774. EXPECT_EQ("PUT:test", read_body(put));
  11775. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  11776. EXPECT_EQ("PATCH:test", read_body(patch));
  11777. }
  11778. // stream::Delete tests
  11779. TEST_F(StreamApiTest, Delete) {
  11780. httplib::Client cli(HOST, PORT);
  11781. auto del1 = httplib::stream::Delete(cli, "/resource");
  11782. EXPECT_EQ("Deleted", read_body(del1));
  11783. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  11784. EXPECT_EQ("Deleted:data", read_body(del2));
  11785. }
  11786. // stream::Head/Options tests
  11787. TEST_F(StreamApiTest, HeadAndOptions) {
  11788. httplib::Client cli(HOST, PORT);
  11789. auto head = httplib::stream::Head(cli, "/head-test");
  11790. EXPECT_TRUE(head.is_valid());
  11791. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  11792. auto opts = httplib::stream::Options(cli, "/options");
  11793. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  11794. }
  11795. // SSL stream::* tests
  11796. #ifdef CPPHTTPLIB_SSL_ENABLED
  11797. class SSLStreamApiTest : public ::testing::Test {
  11798. protected:
  11799. void SetUp() override {
  11800. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  11801. res.set_content("Hello SSL!", "text/plain");
  11802. });
  11803. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  11804. res.set_content(req.body, "text/plain");
  11805. });
  11806. port_ = svr_.bind_to_any_port("127.0.0.1");
  11807. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11808. svr_.wait_until_ready();
  11809. }
  11810. void TearDown() override {
  11811. svr_.stop();
  11812. if (thread_.joinable()) thread_.join();
  11813. }
  11814. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  11815. std::thread thread_;
  11816. int port_ = 0;
  11817. };
  11818. TEST_F(SSLStreamApiTest, GetAndPost) {
  11819. httplib::SSLClient cli("127.0.0.1", port_);
  11820. cli.enable_server_certificate_verification(false);
  11821. auto get = httplib::stream::Get(cli, "/hello");
  11822. EXPECT_EQ("Hello SSL!", read_body(get));
  11823. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  11824. EXPECT_EQ("test", read_body(post));
  11825. }
  11826. #endif
  11827. // Tests for Error::Timeout and Error::ConnectionClosed error types
  11828. // These errors are set in SocketStream/SSLSocketStream and propagated through
  11829. // BodyReader
  11830. TEST(ErrorHandlingTest, StreamReadTimeout) {
  11831. // Test that read timeout during streaming is detected
  11832. // Use a large content-length response where server delays mid-stream
  11833. Server svr;
  11834. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11835. // Send a large response with delay in the middle
  11836. res.set_content_provider(
  11837. 1000, // content_length
  11838. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  11839. if (offset < 100) {
  11840. // Send first 100 bytes immediately
  11841. std::string data(100, 'A');
  11842. sink.write(data.c_str(), data.size());
  11843. return true;
  11844. }
  11845. // Then delay longer than client timeout
  11846. std::this_thread::sleep_for(std::chrono::seconds(3));
  11847. std::string data(900, 'B');
  11848. sink.write(data.c_str(), data.size());
  11849. return true;
  11850. });
  11851. });
  11852. auto port = 8091;
  11853. std::thread t([&]() { svr.listen("localhost", port); });
  11854. svr.wait_until_ready();
  11855. Client cli("localhost", port);
  11856. cli.set_read_timeout(1, 0); // 1 second timeout
  11857. auto handle = cli.open_stream("GET", "/slow-stream");
  11858. ASSERT_TRUE(handle.is_valid());
  11859. char buf[256];
  11860. ssize_t total = 0;
  11861. ssize_t n;
  11862. bool got_error = false;
  11863. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11864. total += n;
  11865. }
  11866. if (n < 0) {
  11867. got_error = true;
  11868. // Should be timeout or read error
  11869. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11870. handle.get_read_error() == Error::Read)
  11871. << "Actual error: " << to_string(handle.get_read_error());
  11872. }
  11873. // Either we got an error, or we got less data than expected
  11874. EXPECT_TRUE(got_error || total < 1000)
  11875. << "Expected timeout but got all " << total << " bytes";
  11876. svr.stop();
  11877. t.join();
  11878. }
  11879. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11880. // Test connection closed detection via BodyReader
  11881. Server svr;
  11882. std::atomic<bool> close_now{false};
  11883. svr.Get("/will-close", [&](const Request &, Response &res) {
  11884. res.set_content_provider(
  11885. 10000, // Large content_length that we won't fully send
  11886. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11887. if (offset < 100) {
  11888. std::string data(100, 'X');
  11889. sink.write(data.c_str(), data.size());
  11890. return true;
  11891. }
  11892. // Wait for signal then abort
  11893. while (!close_now) {
  11894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11895. }
  11896. return false; // Abort - server will close connection
  11897. });
  11898. });
  11899. auto port = 8092;
  11900. std::thread t([&]() { svr.listen("localhost", port); });
  11901. svr.wait_until_ready();
  11902. Client cli("localhost", port);
  11903. auto handle = cli.open_stream("GET", "/will-close");
  11904. ASSERT_TRUE(handle.is_valid());
  11905. char buf[256];
  11906. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11907. EXPECT_GT(n, 0) << "First read should succeed";
  11908. // Signal server to close
  11909. close_now = true;
  11910. // Keep reading until error or EOF
  11911. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11912. // Keep reading
  11913. }
  11914. // Should get an error since content_length wasn't satisfied
  11915. if (n < 0) {
  11916. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11917. handle.get_read_error() == Error::Read)
  11918. << "Actual error: " << to_string(handle.get_read_error());
  11919. }
  11920. svr.stop();
  11921. t.join();
  11922. }
  11923. #ifdef CPPHTTPLIB_SSL_ENABLED
  11924. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11925. // Test that read timeout during SSL streaming is detected
  11926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11927. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11928. res.set_content_provider(
  11929. 1000, "text/plain",
  11930. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11931. if (offset < 100) {
  11932. std::string data(100, 'A');
  11933. sink.write(data.c_str(), data.size());
  11934. return true;
  11935. }
  11936. std::this_thread::sleep_for(std::chrono::seconds(3));
  11937. std::string data(900, 'B');
  11938. sink.write(data.c_str(), data.size());
  11939. return true;
  11940. });
  11941. });
  11942. auto port = 8093;
  11943. std::thread t([&]() { svr.listen("localhost", port); });
  11944. svr.wait_until_ready();
  11945. SSLClient cli("localhost", port);
  11946. cli.enable_server_certificate_verification(false);
  11947. cli.set_read_timeout(1, 0); // 1 second timeout
  11948. auto handle = cli.open_stream("GET", "/slow-stream");
  11949. ASSERT_TRUE(handle.is_valid());
  11950. char buf[256];
  11951. ssize_t total = 0;
  11952. ssize_t n;
  11953. bool got_error = false;
  11954. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11955. total += n;
  11956. }
  11957. if (n < 0) {
  11958. got_error = true;
  11959. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11960. handle.get_read_error() == Error::Read)
  11961. << "Actual error: " << to_string(handle.get_read_error());
  11962. }
  11963. EXPECT_TRUE(got_error || total < 1000)
  11964. << "Expected timeout but got all " << total << " bytes";
  11965. svr.stop();
  11966. t.join();
  11967. }
  11968. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11969. // Test SSL connection closed detection
  11970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11971. std::atomic<bool> close_now{false};
  11972. svr.Get("/will-close", [&](const Request &, Response &res) {
  11973. res.set_content_provider(
  11974. 10000, "text/plain",
  11975. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11976. if (offset < 100) {
  11977. std::string data(100, 'X');
  11978. sink.write(data.c_str(), data.size());
  11979. return true;
  11980. }
  11981. while (!close_now) {
  11982. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11983. }
  11984. return false;
  11985. });
  11986. });
  11987. auto port = 8094;
  11988. std::thread t([&]() { svr.listen("localhost", port); });
  11989. svr.wait_until_ready();
  11990. SSLClient cli("localhost", port);
  11991. cli.enable_server_certificate_verification(false);
  11992. auto handle = cli.open_stream("GET", "/will-close");
  11993. ASSERT_TRUE(handle.is_valid());
  11994. char buf[256];
  11995. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11996. EXPECT_GT(n, 0);
  11997. // Signal server to close
  11998. close_now = true;
  11999. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12000. // Keep reading
  12001. }
  12002. if (n < 0) {
  12003. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12004. handle.get_read_error() == Error::Read)
  12005. << "Actual error: " << to_string(handle.get_read_error());
  12006. }
  12007. svr.stop();
  12008. t.join();
  12009. }
  12010. #endif
  12011. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12012. using namespace httplib;
  12013. // Create a test file
  12014. const char *fname = "etag_testfile.txt";
  12015. const char *content = "etag-content";
  12016. {
  12017. std::ofstream ofs(fname);
  12018. ofs << content;
  12019. ASSERT_TRUE(ofs.good());
  12020. }
  12021. Server svr;
  12022. svr.set_mount_point("/static", ".");
  12023. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12024. svr.wait_until_ready();
  12025. Client cli(HOST, PORT);
  12026. // First request: should get 200 with ETag header
  12027. auto res1 = cli.Get("/static/etag_testfile.txt");
  12028. ASSERT_TRUE(res1);
  12029. ASSERT_EQ(200, res1->status);
  12030. ASSERT_TRUE(res1->has_header("ETag"));
  12031. std::string etag = res1->get_header_value("ETag");
  12032. EXPECT_FALSE(etag.empty());
  12033. // Verify ETag format: W/"hex-hex"
  12034. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12035. EXPECT_EQ('W', etag[0]);
  12036. EXPECT_EQ('/', etag[1]);
  12037. EXPECT_EQ('"', etag[2]);
  12038. EXPECT_EQ('"', etag.back());
  12039. // Exact match: expect 304 Not Modified
  12040. Headers h2 = {{"If-None-Match", etag}};
  12041. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12042. ASSERT_TRUE(res2);
  12043. EXPECT_EQ(304, res2->status);
  12044. // Wildcard match: expect 304 Not Modified
  12045. Headers h3 = {{"If-None-Match", "*"}};
  12046. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12047. ASSERT_TRUE(res3);
  12048. EXPECT_EQ(304, res3->status);
  12049. // Non-matching ETag: expect 200
  12050. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12051. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12052. ASSERT_TRUE(res4);
  12053. EXPECT_EQ(200, res4->status);
  12054. // Multiple ETags with one matching: expect 304
  12055. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12056. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12057. ASSERT_TRUE(res5);
  12058. EXPECT_EQ(304, res5->status);
  12059. svr.stop();
  12060. t.join();
  12061. std::remove(fname);
  12062. }
  12063. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12064. using namespace httplib;
  12065. Server svr;
  12066. svr.set_mount_point("/static", ".");
  12067. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12068. svr.wait_until_ready();
  12069. Client cli(HOST, PORT);
  12070. // Send If-None-Match: * to a non-existent file
  12071. Headers h = {{"If-None-Match", "*"}};
  12072. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12073. ASSERT_TRUE(res);
  12074. EXPECT_EQ(404, res->status);
  12075. svr.stop();
  12076. t.join();
  12077. }
  12078. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12079. using namespace httplib;
  12080. // Create a test file
  12081. const char *fname = "etag_boundary_testfile.txt";
  12082. const char *content = "boundary-test";
  12083. {
  12084. std::ofstream ofs(fname);
  12085. ofs << content;
  12086. ASSERT_TRUE(ofs.good());
  12087. }
  12088. Server svr;
  12089. svr.set_mount_point("/static", ".");
  12090. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12091. svr.wait_until_ready();
  12092. Client cli(HOST, PORT);
  12093. // Get the actual ETag
  12094. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12095. ASSERT_TRUE(res1);
  12096. ASSERT_EQ(200, res1->status);
  12097. ASSERT_TRUE(res1->has_header("ETag"));
  12098. std::string etag = res1->get_header_value("ETag");
  12099. // Test 1: Very long ETag value (longer than actual ETag)
  12100. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12101. Headers h1 = {{"If-None-Match", "W/"
  12102. "\"very-long-etag-value-that-is-much-longer-"
  12103. "than-the-actual-etag-value\""}};
  12104. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12105. ASSERT_TRUE(res2);
  12106. EXPECT_EQ(200, res2->status); // Should not match
  12107. // Test 2: Long string followed by wildcard
  12108. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12109. // string)
  12110. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12111. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12112. ASSERT_TRUE(res3);
  12113. EXPECT_EQ(304, res3->status); // Should match on "*"
  12114. // Test 3: Wildcard followed by long string
  12115. // Should match on "*" immediately and return 304
  12116. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12117. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12118. ASSERT_TRUE(res4);
  12119. EXPECT_EQ(304, res4->status); // Should match on "*"
  12120. // Test 4: Multiple long non-matching values
  12121. // Should NOT match and return 200 (test that all comparisons are safe)
  12122. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12123. "W/\"second-long-non-matching-value\", "
  12124. "W/\"third-long-non-matching-value\""}};
  12125. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12126. ASSERT_TRUE(res5);
  12127. EXPECT_EQ(200, res5->status); // Should not match
  12128. // Test 5: Single character that is not "*" (edge case)
  12129. Headers h5 = {{"If-None-Match", "X"}};
  12130. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12131. ASSERT_TRUE(res6);
  12132. EXPECT_EQ(200, res6->status); // Should not match
  12133. svr.stop();
  12134. t.join();
  12135. std::remove(fname);
  12136. }
  12137. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12138. using namespace httplib;
  12139. // Create a test file
  12140. const char *fname = "ims_testfile.txt";
  12141. const char *content = "if-modified-since-test";
  12142. {
  12143. std::ofstream ofs(fname);
  12144. ofs << content;
  12145. ASSERT_TRUE(ofs.good());
  12146. }
  12147. Server svr;
  12148. svr.set_mount_point("/static", ".");
  12149. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12150. svr.wait_until_ready();
  12151. Client cli(HOST, PORT);
  12152. // First request: should get 200 with Last-Modified header
  12153. auto res1 = cli.Get("/static/ims_testfile.txt");
  12154. ASSERT_TRUE(res1);
  12155. ASSERT_EQ(200, res1->status);
  12156. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12157. std::string last_modified = res1->get_header_value("Last-Modified");
  12158. EXPECT_FALSE(last_modified.empty());
  12159. // If-Modified-Since with same time: expect 304
  12160. Headers h2 = {{"If-Modified-Since", last_modified}};
  12161. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12162. ASSERT_TRUE(res2);
  12163. EXPECT_EQ(304, res2->status);
  12164. // If-Modified-Since with future time: expect 304
  12165. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12166. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12167. ASSERT_TRUE(res3);
  12168. EXPECT_EQ(304, res3->status);
  12169. // If-Modified-Since with past time: expect 200
  12170. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12171. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12172. ASSERT_TRUE(res4);
  12173. EXPECT_EQ(200, res4->status);
  12174. // If-None-Match takes precedence over If-Modified-Since
  12175. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12176. ASSERT_TRUE(res1->has_header("ETag"));
  12177. std::string etag = res1->get_header_value("ETag");
  12178. Headers h5 = {{"If-None-Match", etag},
  12179. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12180. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12181. ASSERT_TRUE(res5);
  12182. EXPECT_EQ(304, res5->status);
  12183. svr.stop();
  12184. t.join();
  12185. std::remove(fname);
  12186. }
  12187. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12188. using namespace httplib;
  12189. Server svr;
  12190. // Endpoint that returns compressible content
  12191. svr.Get("/compressible", [](const Request &, Response &res) {
  12192. // Return a large enough body to trigger compression
  12193. std::string body(1000, 'a');
  12194. res.set_content(body, "text/plain");
  12195. });
  12196. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12197. svr.wait_until_ready();
  12198. Client cli(HOST, PORT);
  12199. // Request with gzip support: should get Vary header when compressed
  12200. cli.set_compress(true);
  12201. auto res1 = cli.Get("/compressible");
  12202. ASSERT_TRUE(res1);
  12203. EXPECT_EQ(200, res1->status);
  12204. // If Content-Encoding is set, Vary should also be set
  12205. if (res1->has_header("Content-Encoding")) {
  12206. EXPECT_TRUE(res1->has_header("Vary"));
  12207. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12208. }
  12209. // Request without Accept-Encoding header: should not have compression
  12210. Headers h_no_compress;
  12211. auto res2 = cli.Get("/compressible", h_no_compress);
  12212. ASSERT_TRUE(res2);
  12213. EXPECT_EQ(200, res2->status);
  12214. // Verify Vary header is present when compression is applied
  12215. // (the exact behavior depends on server configuration)
  12216. svr.stop();
  12217. t.join();
  12218. }
  12219. TEST(ETagTest, IfRangeWithETag) {
  12220. using namespace httplib;
  12221. // Create a test file with known content
  12222. const char *fname = "if_range_testfile.txt";
  12223. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12224. {
  12225. std::ofstream ofs(fname);
  12226. ofs << content;
  12227. ASSERT_TRUE(ofs.good());
  12228. }
  12229. Server svr;
  12230. svr.set_mount_point("/static", ".");
  12231. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12232. svr.wait_until_ready();
  12233. Client cli(HOST, PORT);
  12234. // First request: get ETag
  12235. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12236. ASSERT_TRUE(res1);
  12237. ASSERT_EQ(200, res1->status);
  12238. ASSERT_TRUE(res1->has_header("ETag"));
  12239. std::string etag = res1->get_header_value("ETag");
  12240. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12241. // Since our server generates weak ETags (W/"..."), If-Range with our
  12242. // ETag should NOT result in partial content - it should return full content.
  12243. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12244. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12245. ASSERT_TRUE(res2);
  12246. // Weak ETag in If-Range -> full content (200), not partial (206)
  12247. EXPECT_EQ(200, res2->status);
  12248. EXPECT_EQ(content, res2->body);
  12249. EXPECT_FALSE(res2->has_header("Content-Range"));
  12250. // Range request with non-matching If-Range (ETag): should get 200 (full
  12251. // content)
  12252. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12253. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12254. ASSERT_TRUE(res3);
  12255. EXPECT_EQ(200, res3->status);
  12256. EXPECT_EQ(content, res3->body);
  12257. EXPECT_FALSE(res3->has_header("Content-Range"));
  12258. // Range request with strong ETag (hypothetical - our server doesn't generate
  12259. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12260. // should return full content)
  12261. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12262. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12263. ASSERT_TRUE(res4);
  12264. EXPECT_EQ(200, res4->status);
  12265. EXPECT_EQ(content, res4->body);
  12266. EXPECT_FALSE(res4->has_header("Content-Range"));
  12267. svr.stop();
  12268. t.join();
  12269. std::remove(fname);
  12270. }
  12271. TEST(ETagTest, IfRangeWithDate) {
  12272. using namespace httplib;
  12273. // Create a test file
  12274. const char *fname = "if_range_date_testfile.txt";
  12275. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12276. {
  12277. std::ofstream ofs(fname);
  12278. ofs << content;
  12279. ASSERT_TRUE(ofs.good());
  12280. }
  12281. Server svr;
  12282. svr.set_mount_point("/static", ".");
  12283. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, PORT);
  12286. // First request: get Last-Modified
  12287. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12288. ASSERT_TRUE(res1);
  12289. ASSERT_EQ(200, res1->status);
  12290. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12291. std::string last_modified = res1->get_header_value("Last-Modified");
  12292. // Range request with matching If-Range (date): should get 206
  12293. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12294. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12295. ASSERT_TRUE(res2);
  12296. EXPECT_EQ(206, res2->status);
  12297. EXPECT_EQ("FGHIJ", res2->body);
  12298. // Range request with old If-Range date: should get 200 (full content)
  12299. Headers h3 = {{"Range", "bytes=5-9"},
  12300. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12301. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12302. ASSERT_TRUE(res3);
  12303. EXPECT_EQ(200, res3->status);
  12304. EXPECT_EQ(content, res3->body);
  12305. // Range request with future If-Range date: should get 206
  12306. Headers h4 = {{"Range", "bytes=0-4"},
  12307. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12308. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12309. ASSERT_TRUE(res4);
  12310. EXPECT_EQ(206, res4->status);
  12311. EXPECT_EQ("ABCDE", res4->body);
  12312. svr.stop();
  12313. t.join();
  12314. std::remove(fname);
  12315. }
  12316. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12317. using namespace httplib;
  12318. const char *fname = "etag_malformed.txt";
  12319. const char *content = "malformed-etag";
  12320. {
  12321. std::ofstream ofs(fname);
  12322. ofs << content;
  12323. ASSERT_TRUE(ofs.good());
  12324. }
  12325. Server svr;
  12326. svr.set_mount_point("/static", ".");
  12327. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12328. svr.wait_until_ready();
  12329. Client cli(HOST, PORT);
  12330. // baseline: should get 200 and an ETag
  12331. auto res1 = cli.Get("/static/etag_malformed.txt");
  12332. ASSERT_TRUE(res1);
  12333. ASSERT_EQ(200, res1->status);
  12334. ASSERT_TRUE(res1->has_header("ETag"));
  12335. // Malformed ETag value (missing quotes) should be treated as non-matching
  12336. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12337. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12338. ASSERT_TRUE(res_bad);
  12339. EXPECT_EQ(200, res_bad->status);
  12340. // Whitespace-only header value should be considered invalid / non-matching
  12341. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12342. "Host: localhost\r\n"
  12343. "If-None-Match: \r\n"
  12344. "Connection: close\r\n"
  12345. "\r\n";
  12346. std::string out;
  12347. ASSERT_TRUE(send_request(5, raw_req, &out));
  12348. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12349. svr.stop();
  12350. t.join();
  12351. std::remove(fname);
  12352. }
  12353. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12354. using namespace httplib;
  12355. const char *fname = "ims_invalid_format.txt";
  12356. const char *content = "ims-bad-format";
  12357. {
  12358. std::ofstream ofs(fname);
  12359. ofs << content;
  12360. ASSERT_TRUE(ofs.good());
  12361. }
  12362. Server svr;
  12363. svr.set_mount_point("/static", ".");
  12364. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12365. svr.wait_until_ready();
  12366. Client cli(HOST, PORT);
  12367. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12368. ASSERT_TRUE(res1);
  12369. ASSERT_EQ(200, res1->status);
  12370. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12371. // If-Modified-Since with invalid format should not result in 304
  12372. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12373. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12374. ASSERT_TRUE(res_bad);
  12375. EXPECT_EQ(200, res_bad->status);
  12376. // If-Range with invalid date format should be treated as mismatch -> full
  12377. // content (200)
  12378. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12379. {"If-Range", "invalid-date"}};
  12380. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12381. ASSERT_TRUE(res_ifrange);
  12382. EXPECT_EQ(200, res_ifrange->status);
  12383. svr.stop();
  12384. t.join();
  12385. std::remove(fname);
  12386. }
  12387. TEST(ETagTest, IfRangeWithMalformedETag) {
  12388. using namespace httplib;
  12389. const char *fname = "ifrange_malformed.txt";
  12390. const std::string content = "0123456789";
  12391. {
  12392. std::ofstream ofs(fname);
  12393. ofs << content;
  12394. ASSERT_TRUE(ofs.good());
  12395. }
  12396. Server svr;
  12397. svr.set_mount_point("/static", ".");
  12398. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12399. svr.wait_until_ready();
  12400. Client cli(HOST, PORT);
  12401. // First request: get ETag
  12402. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12403. ASSERT_TRUE(res1);
  12404. ASSERT_EQ(200, res1->status);
  12405. ASSERT_TRUE(res1->has_header("ETag"));
  12406. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12407. // full content (200)
  12408. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12409. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12410. ASSERT_TRUE(res2);
  12411. EXPECT_EQ(200, res2->status);
  12412. EXPECT_EQ(content, res2->body);
  12413. svr.stop();
  12414. t.join();
  12415. std::remove(fname);
  12416. }
  12417. TEST(ETagTest, ExtremeLargeDateValues) {
  12418. using namespace httplib;
  12419. const char *fname = "ims_extreme_date.txt";
  12420. const char *content = "ims-extreme-date";
  12421. {
  12422. std::ofstream ofs(fname);
  12423. ofs << content;
  12424. ASSERT_TRUE(ofs.good());
  12425. }
  12426. Server svr;
  12427. svr.set_mount_point("/static", ".");
  12428. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12429. svr.wait_until_ready();
  12430. Client cli(HOST, PORT);
  12431. auto res1 = cli.Get(std::string("/static/") + fname);
  12432. ASSERT_TRUE(res1);
  12433. ASSERT_EQ(200, res1->status);
  12434. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12435. // Extremely large year that may overflow date parsing routines.
  12436. Headers h_large_date = {
  12437. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12438. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12439. ASSERT_TRUE(res_bad);
  12440. // Expect server to treat this as invalid/mismatch and return full content
  12441. EXPECT_EQ(200, res_bad->status);
  12442. // If-Range with extremely large date should be treated as mismatch -> full
  12443. // content (200)
  12444. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12445. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12446. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12447. ASSERT_TRUE(res_ifrange);
  12448. EXPECT_EQ(200, res_ifrange->status);
  12449. svr.stop();
  12450. t.join();
  12451. std::remove(fname);
  12452. }
  12453. TEST(ETagTest, NegativeFileModificationTime) {
  12454. using namespace httplib;
  12455. const char *fname = "ims_negative_mtime.txt";
  12456. const std::string content = "negative-mtime";
  12457. {
  12458. std::ofstream ofs(fname);
  12459. ofs << content;
  12460. ASSERT_TRUE(ofs.good());
  12461. }
  12462. // Try to set file mtime to a negative value. This may fail on some
  12463. // platforms/filesystems; if it fails, the test will still verify server
  12464. // behaves safely by performing a regular conditional request.
  12465. #if defined(__APPLE__) || defined(__linux__)
  12466. bool set_negative = false;
  12467. do {
  12468. struct timeval times[2];
  12469. // access time: now
  12470. times[0].tv_sec = time(nullptr);
  12471. times[0].tv_usec = 0;
  12472. // modification time: negative (e.g., -1)
  12473. times[1].tv_sec = -1;
  12474. times[1].tv_usec = 0;
  12475. if (utimes(fname, times) == 0) { set_negative = true; }
  12476. } while (0);
  12477. #else
  12478. bool set_negative = false;
  12479. #endif
  12480. Server svr;
  12481. svr.set_mount_point("/static", ".");
  12482. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12483. svr.wait_until_ready();
  12484. Client cli(HOST, PORT);
  12485. auto res1 = cli.Get(std::string("/static/") + fname);
  12486. ASSERT_TRUE(res1);
  12487. ASSERT_EQ(200, res1->status);
  12488. bool has_last_modified = res1->has_header("Last-Modified");
  12489. std::string last_modified;
  12490. if (has_last_modified) {
  12491. last_modified = res1->get_header_value("Last-Modified");
  12492. }
  12493. if (set_negative) {
  12494. // If we successfully set a negative mtime, ensure server returns a
  12495. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  12496. // with an old date and ensure server handles it without crash.
  12497. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  12498. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  12499. ASSERT_TRUE(res2);
  12500. // Behavior may vary; at minimum ensure server responds (200 or 304).
  12501. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  12502. } else {
  12503. // Could not set negative mtime on this platform; fall back to verifying
  12504. // that normal invalid/malformed dates are treated safely (non-304).
  12505. Headers h_bad_date = {
  12506. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12507. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  12508. ASSERT_TRUE(res_bad);
  12509. EXPECT_EQ(200, res_bad->status);
  12510. }
  12511. svr.stop();
  12512. t.join();
  12513. std::remove(fname);
  12514. }
  12515. //==============================================================================
  12516. // SSE Parsing Tests
  12517. //==============================================================================
  12518. class SSEParsingTest : public ::testing::Test {
  12519. protected:
  12520. // Test helper that mimics SSE parsing behavior
  12521. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  12522. int &retry_ms) {
  12523. // Blank line signals end of event
  12524. if (line.empty() || line == "\r") { return true; }
  12525. // Lines starting with ':' are comments (ignored)
  12526. if (!line.empty() && line[0] == ':') { return false; }
  12527. // Find the colon separator
  12528. auto colon_pos = line.find(':');
  12529. if (colon_pos == std::string::npos) {
  12530. // Line with no colon is treated as field name with empty value
  12531. return false;
  12532. }
  12533. std::string field = line.substr(0, colon_pos);
  12534. std::string value;
  12535. // Value starts after colon, skip optional single space
  12536. if (colon_pos + 1 < line.size()) {
  12537. size_t value_start = colon_pos + 1;
  12538. if (line[value_start] == ' ') { value_start++; }
  12539. value = line.substr(value_start);
  12540. // Remove trailing \r if present
  12541. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  12542. }
  12543. // Handle known fields
  12544. if (field == "event") {
  12545. msg.event = value;
  12546. } else if (field == "data") {
  12547. // Multiple data lines are concatenated with newlines
  12548. if (!msg.data.empty()) { msg.data += "\n"; }
  12549. msg.data += value;
  12550. } else if (field == "id") {
  12551. // Empty id is valid (clears the last event ID)
  12552. msg.id = value;
  12553. } else if (field == "retry") {
  12554. // Parse retry interval in milliseconds
  12555. {
  12556. int v = 0;
  12557. auto res =
  12558. detail::from_chars(value.data(), value.data() + value.size(), v);
  12559. if (res.ec == std::errc{}) { retry_ms = v; }
  12560. }
  12561. }
  12562. // Unknown fields are ignored per SSE spec
  12563. return false;
  12564. }
  12565. };
  12566. // Test: Single-line data
  12567. TEST_F(SSEParsingTest, SingleLineData) {
  12568. sse::SSEMessage msg;
  12569. int retry_ms = 3000;
  12570. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  12571. EXPECT_EQ(msg.data, "hello");
  12572. EXPECT_EQ(msg.event, "message");
  12573. // Blank line ends event
  12574. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12575. }
  12576. // Test: Multi-line data
  12577. TEST_F(SSEParsingTest, MultiLineData) {
  12578. sse::SSEMessage msg;
  12579. int retry_ms = 3000;
  12580. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  12581. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  12582. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  12583. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  12584. }
  12585. // Test: Custom event types
  12586. TEST_F(SSEParsingTest, CustomEventType) {
  12587. sse::SSEMessage msg;
  12588. int retry_ms = 3000;
  12589. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  12590. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  12591. EXPECT_EQ(msg.event, "update");
  12592. EXPECT_EQ(msg.data, "payload");
  12593. }
  12594. // Test: Event ID handling
  12595. TEST_F(SSEParsingTest, EventIdHandling) {
  12596. sse::SSEMessage msg;
  12597. int retry_ms = 3000;
  12598. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  12599. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  12600. EXPECT_EQ(msg.id, "12345");
  12601. }
  12602. // Test: Empty event ID (clears last event ID)
  12603. TEST_F(SSEParsingTest, EmptyEventId) {
  12604. sse::SSEMessage msg;
  12605. msg.id = "previous";
  12606. int retry_ms = 3000;
  12607. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  12608. EXPECT_EQ(msg.id, "");
  12609. }
  12610. // Test: Retry field parsing
  12611. TEST_F(SSEParsingTest, RetryFieldParsing) {
  12612. sse::SSEMessage msg;
  12613. int retry_ms = 3000;
  12614. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  12615. EXPECT_EQ(retry_ms, 5000);
  12616. }
  12617. // Test: Invalid retry value
  12618. TEST_F(SSEParsingTest, InvalidRetryValue) {
  12619. sse::SSEMessage msg;
  12620. int retry_ms = 3000;
  12621. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  12622. EXPECT_EQ(retry_ms, 3000); // Unchanged
  12623. }
  12624. // Test: Comments (lines starting with :)
  12625. TEST_F(SSEParsingTest, CommentsIgnored) {
  12626. sse::SSEMessage msg;
  12627. int retry_ms = 3000;
  12628. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  12629. EXPECT_EQ(msg.data, "");
  12630. EXPECT_EQ(msg.event, "message");
  12631. }
  12632. // Test: Colon in value
  12633. TEST_F(SSEParsingTest, ColonInValue) {
  12634. sse::SSEMessage msg;
  12635. int retry_ms = 3000;
  12636. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  12637. EXPECT_EQ(msg.data, "hello:world:test");
  12638. }
  12639. // Test: Line with no colon (field name only)
  12640. TEST_F(SSEParsingTest, FieldNameOnly) {
  12641. sse::SSEMessage msg;
  12642. int retry_ms = 3000;
  12643. // According to SSE spec, this is treated as field name with empty value
  12644. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  12645. // Since we don't recognize "data" without colon, data should be empty
  12646. EXPECT_EQ(msg.data, "");
  12647. }
  12648. // Test: Trailing \r handling
  12649. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  12650. sse::SSEMessage msg;
  12651. int retry_ms = 3000;
  12652. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  12653. EXPECT_EQ(msg.data, "hello");
  12654. }
  12655. // Test: Unknown fields ignored
  12656. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  12657. sse::SSEMessage msg;
  12658. int retry_ms = 3000;
  12659. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  12660. EXPECT_EQ(msg.data, "");
  12661. EXPECT_EQ(msg.event, "message");
  12662. }
  12663. // Test: Space after colon is optional
  12664. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  12665. sse::SSEMessage msg1, msg2;
  12666. int retry_ms = 3000;
  12667. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  12668. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  12669. EXPECT_EQ(msg1.data, "hello");
  12670. EXPECT_EQ(msg2.data, "hello");
  12671. }
  12672. // Test: SSEMessage clear
  12673. TEST_F(SSEParsingTest, MessageClear) {
  12674. sse::SSEMessage msg;
  12675. msg.event = "custom";
  12676. msg.data = "some data";
  12677. msg.id = "123";
  12678. msg.clear();
  12679. EXPECT_EQ(msg.event, "message");
  12680. EXPECT_EQ(msg.data, "");
  12681. EXPECT_EQ(msg.id, "");
  12682. }
  12683. // Test: Complete event parsing
  12684. TEST_F(SSEParsingTest, CompleteEventParsing) {
  12685. sse::SSEMessage msg;
  12686. int retry_ms = 3000;
  12687. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  12688. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  12689. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  12690. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  12691. // Blank line ends event
  12692. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  12693. EXPECT_EQ(msg.event, "notification");
  12694. EXPECT_EQ(msg.id, "evt-42");
  12695. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  12696. EXPECT_EQ(retry_ms, 1000);
  12697. }
  12698. //==============================================================================
  12699. // Integration Tests with Server
  12700. //==============================================================================
  12701. class SSEIntegrationTest : public ::testing::Test {
  12702. protected:
  12703. void SetUp() override {
  12704. stop_server_.store(false);
  12705. events_.clear();
  12706. server_ = httplib::detail::make_unique<Server>();
  12707. setup_server();
  12708. start_server();
  12709. }
  12710. void TearDown() override {
  12711. stop_server_.store(true);
  12712. event_cv_.notify_all();
  12713. server_->stop();
  12714. if (server_thread_.joinable()) { server_thread_.join(); }
  12715. }
  12716. void setup_server() {
  12717. // Simple SSE endpoint
  12718. server_->Get("/events", [this](const Request &req, Response &res) {
  12719. auto last_id = req.get_header_value("Last-Event-ID");
  12720. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  12721. res.set_chunked_content_provider(
  12722. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  12723. std::unique_lock<std::mutex> lock(event_mutex_);
  12724. if (event_cv_.wait_for(
  12725. lock, std::chrono::milliseconds(200), [this] {
  12726. return !events_.empty() || stop_server_.load();
  12727. })) {
  12728. if (stop_server_.load()) { return false; }
  12729. if (!events_.empty()) {
  12730. std::string event = events_.front();
  12731. events_.erase(events_.begin());
  12732. sink.write(event.data(), event.size());
  12733. return true;
  12734. }
  12735. }
  12736. return !stop_server_.load();
  12737. });
  12738. });
  12739. // Endpoint that returns error
  12740. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  12741. res.status = 500;
  12742. res.set_content("Internal Server Error", "text/plain");
  12743. });
  12744. // Endpoint for custom event types
  12745. server_->Get("/custom-events", [](const Request &, Response &res) {
  12746. res.set_chunked_content_provider(
  12747. "text/event-stream", [](size_t offset, DataSink &sink) {
  12748. if (offset == 0) {
  12749. std::string event = "event: update\ndata: updated\n\n"
  12750. "event: delete\ndata: deleted\n\n";
  12751. sink.write(event.data(), event.size());
  12752. }
  12753. return false; // End stream after sending
  12754. });
  12755. });
  12756. }
  12757. void start_server() {
  12758. port_ = server_->bind_to_any_port(HOST);
  12759. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  12760. // Wait for server to start
  12761. while (!server_->is_running()) {
  12762. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12763. }
  12764. }
  12765. int get_port() const { return port_; }
  12766. void send_event(const std::string &event) {
  12767. std::lock_guard<std::mutex> lock(event_mutex_);
  12768. events_.push_back(event);
  12769. event_cv_.notify_all();
  12770. }
  12771. std::unique_ptr<Server> server_;
  12772. std::thread server_thread_;
  12773. std::mutex event_mutex_;
  12774. std::condition_variable event_cv_;
  12775. std::vector<std::string> events_;
  12776. std::atomic<bool> stop_server_{false};
  12777. std::string last_received_event_id_;
  12778. int port_ = 0;
  12779. };
  12780. // Test: Successful connection and on_open callback
  12781. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  12782. // Add a simple endpoint that sends one event and closes
  12783. server_->Get("/simple-event", [](const Request &, Response &res) {
  12784. res.set_chunked_content_provider(
  12785. "text/event-stream", [](size_t offset, DataSink &sink) {
  12786. if (offset == 0) {
  12787. std::string event = "data: hello\n\n";
  12788. sink.write(event.data(), event.size());
  12789. }
  12790. return false; // Close stream after sending
  12791. });
  12792. });
  12793. Client client("localhost", get_port());
  12794. sse::SSEClient sse(client, "/simple-event");
  12795. std::atomic<bool> open_called{false};
  12796. std::atomic<bool> message_received{false};
  12797. sse.on_open([&open_called]() { open_called.store(true); });
  12798. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  12799. if (msg.data == "hello") { message_received.store(true); }
  12800. });
  12801. sse.set_reconnect_interval(100);
  12802. sse.set_max_reconnect_attempts(1);
  12803. // Start async
  12804. sse.start_async();
  12805. // Wait for message to be processed
  12806. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12807. sse.stop();
  12808. EXPECT_TRUE(open_called.load());
  12809. EXPECT_TRUE(message_received.load());
  12810. }
  12811. // Test: on_message callback
  12812. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  12813. // Endpoint that sends multiple events then closes
  12814. server_->Get("/multi-event", [](const Request &, Response &res) {
  12815. res.set_chunked_content_provider(
  12816. "text/event-stream", [](size_t offset, DataSink &sink) {
  12817. if (offset == 0) {
  12818. std::string events = "data: message1\n\ndata: message2\n\n";
  12819. sink.write(events.data(), events.size());
  12820. }
  12821. return false;
  12822. });
  12823. });
  12824. Client client("localhost", get_port());
  12825. sse::SSEClient sse(client, "/multi-event");
  12826. std::vector<std::string> received_messages;
  12827. std::mutex messages_mutex;
  12828. sse.on_message([&](const sse::SSEMessage &msg) {
  12829. std::lock_guard<std::mutex> lock(messages_mutex);
  12830. received_messages.push_back(msg.data);
  12831. });
  12832. sse.set_reconnect_interval(100);
  12833. sse.set_max_reconnect_attempts(1);
  12834. sse.start_async();
  12835. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12836. sse.stop();
  12837. std::lock_guard<std::mutex> lock(messages_mutex);
  12838. EXPECT_GE(received_messages.size(), 2u);
  12839. if (received_messages.size() >= 2) {
  12840. EXPECT_EQ(received_messages[0], "message1");
  12841. EXPECT_EQ(received_messages[1], "message2");
  12842. }
  12843. }
  12844. // Test: on_event for specific types
  12845. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  12846. Client client("localhost", get_port());
  12847. sse::SSEClient sse(client, "/custom-events");
  12848. std::atomic<bool> update_received{false};
  12849. std::atomic<bool> delete_received{false};
  12850. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  12851. if (msg.data == "updated") { update_received.store(true); }
  12852. });
  12853. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  12854. if (msg.data == "deleted") { delete_received.store(true); }
  12855. });
  12856. sse.set_max_reconnect_attempts(1);
  12857. sse.start_async();
  12858. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  12859. sse.stop();
  12860. EXPECT_TRUE(update_received.load());
  12861. EXPECT_TRUE(delete_received.load());
  12862. }
  12863. // Test: on_error callback on connection failure
  12864. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  12865. // Connect to a non-existent port
  12866. Client client("localhost", 59999);
  12867. sse::SSEClient sse(client, "/events");
  12868. std::atomic<bool> error_called{false};
  12869. Error received_error = Error::Success;
  12870. sse.on_error([&](Error err) {
  12871. error_called.store(true);
  12872. received_error = err;
  12873. });
  12874. sse.set_reconnect_interval(50);
  12875. sse.set_max_reconnect_attempts(1);
  12876. sse.start_async();
  12877. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12878. sse.stop();
  12879. EXPECT_TRUE(error_called.load());
  12880. EXPECT_NE(received_error, Error::Success);
  12881. }
  12882. // Test: Last-Event-ID header sent on reconnect
  12883. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  12884. // Endpoint that sends event with ID
  12885. server_->Get("/event-with-id", [](const Request &, Response &res) {
  12886. res.set_chunked_content_provider(
  12887. "text/event-stream", [](size_t offset, DataSink &sink) {
  12888. if (offset == 0) {
  12889. std::string event = "id: evt-123\ndata: test\n\n";
  12890. sink.write(event.data(), event.size());
  12891. }
  12892. return false;
  12893. });
  12894. });
  12895. Client client("localhost", get_port());
  12896. sse::SSEClient sse(client, "/event-with-id");
  12897. std::atomic<bool> id_received{false};
  12898. sse.on_message([&](const sse::SSEMessage &msg) {
  12899. if (!msg.id.empty()) { id_received.store(true); }
  12900. });
  12901. sse.set_reconnect_interval(100);
  12902. sse.set_max_reconnect_attempts(1);
  12903. sse.start_async();
  12904. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12905. sse.stop();
  12906. EXPECT_TRUE(id_received.load());
  12907. EXPECT_EQ(sse.last_event_id(), "evt-123");
  12908. }
  12909. // Test: Manual stop
  12910. TEST_F(SSEIntegrationTest, ManualStop) {
  12911. // Endpoint that sends one event and stays open briefly
  12912. std::atomic<bool> handler_running{true};
  12913. server_->Get("/stay-open", [&handler_running](const Request &,
  12914. Response &res) {
  12915. res.set_chunked_content_provider(
  12916. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12917. if (offset == 0) {
  12918. std::string event = "data: connected\n\n";
  12919. sink.write(event.data(), event.size());
  12920. }
  12921. // Keep connection open while handler_running is true
  12922. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12923. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12924. }
  12925. return false;
  12926. });
  12927. });
  12928. Client client("localhost", get_port());
  12929. sse::SSEClient sse(client, "/stay-open");
  12930. std::atomic<bool> connected{false};
  12931. sse.on_open([&connected]() { connected.store(true); });
  12932. sse.set_reconnect_interval(100);
  12933. sse.set_max_reconnect_attempts(1);
  12934. sse.start_async();
  12935. // Wait for connection to establish
  12936. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12937. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12938. }
  12939. EXPECT_TRUE(connected.load());
  12940. EXPECT_TRUE(sse.is_connected());
  12941. // Signal handler to stop
  12942. handler_running.store(false);
  12943. // Stop SSE client
  12944. sse.stop();
  12945. EXPECT_FALSE(sse.is_connected());
  12946. }
  12947. // Test: SSEClient with custom headers
  12948. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12949. // Setup a server endpoint that checks for custom header
  12950. std::atomic<bool> header_received{false};
  12951. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12952. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12953. header_received.store(true);
  12954. }
  12955. res.set_chunked_content_provider("text/event-stream",
  12956. [](size_t, DataSink &) { return false; });
  12957. });
  12958. Client client("localhost", get_port());
  12959. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12960. sse::SSEClient sse(client, "/header-check", headers);
  12961. sse.set_max_reconnect_attempts(1);
  12962. sse.start_async();
  12963. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12964. sse.stop();
  12965. EXPECT_TRUE(header_received.load());
  12966. }
  12967. // Test: Reconnect interval configuration
  12968. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12969. Client client("localhost", get_port());
  12970. sse::SSEClient sse(client, "/events");
  12971. auto &result = sse.set_reconnect_interval(500);
  12972. // Builder pattern should return reference to self
  12973. EXPECT_EQ(&result, &sse);
  12974. }
  12975. // Test: Max reconnect attempts
  12976. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12977. // Connect to non-existent port to force reconnects
  12978. Client client("localhost", 59998);
  12979. sse::SSEClient sse(client, "/events");
  12980. std::atomic<int> error_count{0};
  12981. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12982. sse.set_reconnect_interval(50);
  12983. sse.set_max_reconnect_attempts(2);
  12984. auto start = std::chrono::steady_clock::now();
  12985. sse.start(); // Blocking call
  12986. auto end = std::chrono::steady_clock::now();
  12987. // Should have stopped after 2 failed attempts
  12988. EXPECT_GE(error_count.load(), 2);
  12989. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12990. auto duration =
  12991. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12992. #ifdef _WIN32
  12993. // Windows is much slower for socket connection failures
  12994. EXPECT_LT(duration.count(), 7000);
  12995. #else
  12996. EXPECT_LT(duration.count(), 1000);
  12997. #endif
  12998. }
  12999. // Test: Multi-line data in integration
  13000. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13001. // Endpoint with multi-line data
  13002. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13003. res.set_chunked_content_provider(
  13004. "text/event-stream", [](size_t offset, DataSink &sink) {
  13005. if (offset == 0) {
  13006. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13007. sink.write(event.data(), event.size());
  13008. }
  13009. return false;
  13010. });
  13011. });
  13012. Client client("localhost", get_port());
  13013. sse::SSEClient sse(client, "/multiline-data");
  13014. std::string received_data;
  13015. std::mutex data_mutex;
  13016. sse.on_message([&](const sse::SSEMessage &msg) {
  13017. std::lock_guard<std::mutex> lock(data_mutex);
  13018. received_data = msg.data;
  13019. });
  13020. sse.set_reconnect_interval(100);
  13021. sse.set_max_reconnect_attempts(1);
  13022. sse.start_async();
  13023. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13024. sse.stop();
  13025. std::lock_guard<std::mutex> lock(data_mutex);
  13026. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13027. }
  13028. // Test: Auto-reconnect after server disconnection
  13029. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13030. std::atomic<int> connection_count{0};
  13031. std::atomic<int> message_count{0};
  13032. // Endpoint that sends one event and closes, forcing reconnect
  13033. server_->Get("/reconnect-test",
  13034. [&connection_count](const Request &, Response &res) {
  13035. connection_count.fetch_add(1);
  13036. res.set_chunked_content_provider(
  13037. "text/event-stream", [](size_t offset, DataSink &sink) {
  13038. if (offset == 0) {
  13039. std::string event = "data: hello\n\n";
  13040. sink.write(event.data(), event.size());
  13041. }
  13042. return false; // Close connection after sending
  13043. });
  13044. });
  13045. Client client("localhost", get_port());
  13046. sse::SSEClient sse(client, "/reconnect-test");
  13047. sse.on_message([&message_count](const sse::SSEMessage &) {
  13048. message_count.fetch_add(1);
  13049. });
  13050. sse.set_reconnect_interval(100);
  13051. sse.set_max_reconnect_attempts(3);
  13052. sse.start_async();
  13053. // Wait long enough for multiple reconnects
  13054. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13055. sse.stop();
  13056. // Should have connected multiple times (initial + reconnects)
  13057. EXPECT_GE(connection_count.load(), 2);
  13058. // Should have received messages from multiple connections
  13059. EXPECT_GE(message_count.load(), 2);
  13060. }
  13061. // Test: Last-Event-ID sent on reconnect
  13062. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13063. std::atomic<int> connection_count{0};
  13064. std::vector<std::string> received_last_event_ids;
  13065. std::mutex id_mutex;
  13066. // Endpoint that checks Last-Event-ID header and sends event with ID
  13067. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13068. int conn = connection_count.fetch_add(1);
  13069. // Capture the Last-Event-ID header from each connection
  13070. {
  13071. std::lock_guard<std::mutex> lock(id_mutex);
  13072. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13073. }
  13074. res.set_chunked_content_provider(
  13075. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13076. if (offset == 0) {
  13077. std::string event =
  13078. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13079. sink.write(event.data(), event.size());
  13080. }
  13081. return false;
  13082. });
  13083. });
  13084. Client client("localhost", get_port());
  13085. sse::SSEClient sse(client, "/reconnect-with-id");
  13086. sse.set_reconnect_interval(100);
  13087. sse.set_max_reconnect_attempts(3);
  13088. sse.start_async();
  13089. // Wait for at least 2 connections
  13090. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13091. sse.stop();
  13092. // Verify behavior
  13093. std::lock_guard<std::mutex> lock(id_mutex);
  13094. EXPECT_GE(received_last_event_ids.size(), 2u);
  13095. // First connection should have no Last-Event-ID
  13096. if (!received_last_event_ids.empty()) {
  13097. EXPECT_EQ(received_last_event_ids[0], "");
  13098. }
  13099. // Second connection should have Last-Event-ID from first connection
  13100. if (received_last_event_ids.size() >= 2) {
  13101. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13102. }
  13103. }
  13104. TEST(Issue2318Test, EmptyHostString) {
  13105. {
  13106. httplib::Client cli_empty("", PORT);
  13107. auto res = cli_empty.Get("/");
  13108. ASSERT_FALSE(res);
  13109. EXPECT_EQ(httplib::Error::Connection, res.error());
  13110. }
  13111. {
  13112. httplib::Client cli(" ", PORT);
  13113. auto res = cli.Get("/");
  13114. ASSERT_FALSE(res);
  13115. EXPECT_EQ(httplib::Error::Connection, res.error());
  13116. }
  13117. }
  13118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13119. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13120. Server svr;
  13121. // Set a small payload limit (1KB)
  13122. svr.set_payload_max_length(1024);
  13123. svr.Post("/test", [&](const Request &req, Response &res) {
  13124. res.set_content("Body size: " + std::to_string(req.body.size()),
  13125. "text/plain");
  13126. });
  13127. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13128. auto se = detail::scope_exit([&] {
  13129. svr.stop();
  13130. listen_thread.join();
  13131. });
  13132. svr.wait_until_ready();
  13133. // Create data that compresses well but exceeds limit when decompressed
  13134. // 8KB of repeated null bytes compresses to a very small size
  13135. std::string original_data(8 * 1024, '\0');
  13136. // Compress the data using gzip
  13137. std::string compressed_data;
  13138. detail::gzip_compressor compressor;
  13139. compressor.compress(original_data.data(), original_data.size(), true,
  13140. [&](const char *data, size_t size) {
  13141. compressed_data.append(data, size);
  13142. return true;
  13143. });
  13144. // Verify compression worked (compressed should be much smaller)
  13145. ASSERT_LT(compressed_data.size(), original_data.size());
  13146. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13147. // Send compressed data with Content-Encoding: gzip
  13148. Client cli(HOST, PORT);
  13149. Headers headers = {{"Content-Encoding", "gzip"}};
  13150. auto res =
  13151. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13152. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13153. ASSERT_TRUE(res);
  13154. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13155. }
  13156. #endif
  13157. // ============================================================================
  13158. // OpenSSL-Specific Tests
  13159. // ============================================================================
  13160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13161. X509 *readCertificate(const std::string &strFileName) {
  13162. std::ifstream inStream(strFileName);
  13163. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13164. std::istreambuf_iterator<char>());
  13165. if (strCertPEM.empty()) return (nullptr);
  13166. BIO *pbCert = BIO_new(BIO_s_mem());
  13167. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13168. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13169. BIO_free(pbCert);
  13170. return (pCert);
  13171. }
  13172. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13173. std::ifstream inStream(strFileName);
  13174. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13175. std::istreambuf_iterator<char>());
  13176. if (strPrivateKeyPEM.empty()) return (nullptr);
  13177. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13178. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13179. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13180. BIO_free(pbPrivKey);
  13181. return (pPrivateKey);
  13182. }
  13183. TEST(BindServerTest, UpdateCerts) {
  13184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13185. int port = svr.bind_to_any_port("0.0.0.0");
  13186. ASSERT_TRUE(svr.is_valid());
  13187. ASSERT_TRUE(port > 0);
  13188. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13189. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13190. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(cert != nullptr);
  13192. ASSERT_TRUE(ca_cert != nullptr);
  13193. ASSERT_TRUE(key != nullptr);
  13194. X509_STORE *cert_store = X509_STORE_new();
  13195. X509_STORE_add_cert(cert_store, ca_cert);
  13196. // svr.update_certs(cert, key, cert_store); // deprecated
  13197. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13198. CLIENT_CA_CERT_FILE);
  13199. ASSERT_TRUE(svr.is_valid());
  13200. svr.stop();
  13201. X509_STORE_free(cert_store);
  13202. X509_free(cert);
  13203. X509_free(ca_cert);
  13204. EVP_PKEY_free(key);
  13205. }
  13206. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13207. // client CA list correctly for TLS handshake
  13208. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13209. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13210. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13211. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13212. ASSERT_TRUE(cert != nullptr);
  13213. ASSERT_TRUE(ca_cert != nullptr);
  13214. ASSERT_TRUE(key != nullptr);
  13215. X509_STORE *cert_store = X509_STORE_new();
  13216. X509_STORE_add_cert(cert_store, ca_cert);
  13217. // Use X509-based constructor (deprecated but should still work correctly)
  13218. #pragma GCC diagnostic push
  13219. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13220. SSLServer svr(cert, key, cert_store);
  13221. #pragma GCC diagnostic pop
  13222. ASSERT_TRUE(svr.is_valid());
  13223. // Verify that client CA list is set in SSL_CTX
  13224. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13225. ASSERT_TRUE(ssl_ctx != nullptr);
  13226. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13227. ASSERT_TRUE(ca_list != nullptr);
  13228. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13229. X509_free(cert);
  13230. X509_free(ca_cert);
  13231. EVP_PKEY_free(key);
  13232. }
  13233. // Test that update_certs() updates client CA list correctly
  13234. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13235. // Start with file-based constructor
  13236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13237. ASSERT_TRUE(svr.is_valid());
  13238. // Initially no client CA list should be set
  13239. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13240. ASSERT_TRUE(ssl_ctx != nullptr);
  13241. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13242. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13243. EXPECT_EQ(0, count_before);
  13244. // Now update with client CA (PEM string)
  13245. std::string cert_pem, key_pem, ca_pem;
  13246. read_file(SERVER_CERT_FILE, cert_pem);
  13247. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13248. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13249. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13250. ASSERT_TRUE(svr.is_valid());
  13251. // Now client CA list should be set
  13252. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13253. ASSERT_TRUE(ca_list_after != nullptr);
  13254. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13255. }
  13256. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13257. // Test that the file-path SSLServer constructor properly sets the client CA
  13258. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13260. ASSERT_TRUE(svr.is_valid());
  13261. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13262. ASSERT_TRUE(ssl_ctx != nullptr);
  13263. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13264. ASSERT_TRUE(ca_list != nullptr);
  13265. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13266. }
  13267. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  13268. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  13269. // prepare large data
  13270. std::random_device seed_gen;
  13271. std::mt19937 random(seed_gen());
  13272. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  13273. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  13274. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  13275. // server
  13276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. ASSERT_TRUE(svr.is_valid());
  13278. svr.Post("/binary", [&](const Request &req, Response &res) {
  13279. EXPECT_EQ(large_size_byte, req.body.size());
  13280. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  13281. res.set_content(req.body, "application/octet-stream");
  13282. });
  13283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13284. auto se = detail::scope_exit([&] {
  13285. svr.stop();
  13286. listen_thread.join();
  13287. ASSERT_FALSE(svr.is_running());
  13288. });
  13289. svr.wait_until_ready();
  13290. // client POST
  13291. SSLClient cli("localhost", PORT);
  13292. cli.enable_server_certificate_verification(false);
  13293. cli.set_read_timeout(std::chrono::seconds(100));
  13294. cli.set_write_timeout(std::chrono::seconds(100));
  13295. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  13296. large_size_byte, "application/octet-stream");
  13297. // compare
  13298. EXPECT_EQ(StatusCode::OK_200, res->status);
  13299. EXPECT_EQ(large_size_byte, res->body.size());
  13300. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  13301. }
  13302. #endif
  13303. // ============================================================================
  13304. // MbedTLS-Specific Tests
  13305. // ============================================================================
  13306. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13307. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13308. using namespace httplib::tls;
  13309. // Track if callback was invoked
  13310. bool callback_invoked = false;
  13311. // The callback receives void* ctx which is actually MbedTlsContext*
  13312. // We can access the mbedtls_ssl_config via the context
  13313. auto setup_callback = [&callback_invoked](void *ctx) {
  13314. callback_invoked = true;
  13315. // Cast to MbedTlsContext* to access the ssl config
  13316. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13317. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13318. // Use static variables to hold certificate data (simplified for test)
  13319. static mbedtls_x509_crt own_cert;
  13320. static mbedtls_pk_context own_key;
  13321. static mbedtls_x509_crt ca_chain;
  13322. static bool initialized = false;
  13323. if (!initialized) {
  13324. mbedtls_x509_crt_init(&own_cert);
  13325. mbedtls_pk_init(&own_key);
  13326. mbedtls_x509_crt_init(&ca_chain);
  13327. // Load server certificate
  13328. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13329. return false;
  13330. }
  13331. // Load server private key
  13332. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13333. #if MBEDTLS_VERSION_MAJOR >= 3
  13334. ,
  13335. mbedtls_ctr_drbg_random, nullptr
  13336. #endif
  13337. ) != 0) {
  13338. return false;
  13339. }
  13340. // Load CA chain for client verification
  13341. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13342. return false;
  13343. }
  13344. initialized = true;
  13345. }
  13346. // Configure the SSL config
  13347. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13348. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13349. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13350. // Set minimum TLS version using mbedTLS native API
  13351. #if MBEDTLS_VERSION_MAJOR >= 3
  13352. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13353. #else
  13354. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13355. MBEDTLS_SSL_MINOR_VERSION_3);
  13356. #endif
  13357. return true;
  13358. };
  13359. SSLServer svr(setup_callback);
  13360. ASSERT_TRUE(svr.is_valid());
  13361. ASSERT_TRUE(callback_invoked);
  13362. svr.Get("/test", [&](const Request &req, Response &res) {
  13363. res.set_content("test", "text/plain");
  13364. auto cert = req.peer_cert();
  13365. ASSERT_TRUE(static_cast<bool>(cert));
  13366. auto common_name = cert.subject_cn();
  13367. EXPECT_EQ("Common Name", common_name);
  13368. });
  13369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13370. auto se = detail::scope_exit([&] {
  13371. svr.stop();
  13372. t.join();
  13373. ASSERT_FALSE(svr.is_running());
  13374. });
  13375. svr.wait_until_ready();
  13376. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13377. cli.enable_server_certificate_verification(false);
  13378. cli.set_connection_timeout(30);
  13379. auto res = cli.Get("/test");
  13380. ASSERT_TRUE(res);
  13381. ASSERT_EQ(StatusCode::OK_200, res->status);
  13382. }
  13383. #endif
  13384. // WebSocket Tests
  13385. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13386. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13387. // defining the meaning of these bits has been negotiated.
  13388. auto make_frame = [](uint8_t first_byte) {
  13389. std::string frame;
  13390. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13391. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13392. frame += "Hello";
  13393. return frame;
  13394. };
  13395. // RSV1 set (0x40)
  13396. {
  13397. detail::BufferStream strm;
  13398. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13399. ws::Opcode opcode;
  13400. std::string payload;
  13401. bool fin;
  13402. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13403. false, 1024));
  13404. }
  13405. // RSV2 set (0x20)
  13406. {
  13407. detail::BufferStream strm;
  13408. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13409. ws::Opcode opcode;
  13410. std::string payload;
  13411. bool fin;
  13412. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13413. false, 1024));
  13414. }
  13415. // RSV3 set (0x10)
  13416. {
  13417. detail::BufferStream strm;
  13418. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13419. ws::Opcode opcode;
  13420. std::string payload;
  13421. bool fin;
  13422. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13423. false, 1024));
  13424. }
  13425. // No RSV bits set - should succeed
  13426. {
  13427. detail::BufferStream strm;
  13428. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13429. ws::Opcode opcode;
  13430. std::string payload;
  13431. bool fin;
  13432. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13433. false, 1024));
  13434. EXPECT_EQ(ws::Opcode::Text, opcode);
  13435. EXPECT_EQ("Hello", payload);
  13436. EXPECT_TRUE(fin);
  13437. }
  13438. }
  13439. TEST(WebSocketTest, ControlFrameValidation) {
  13440. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  13441. // payload length <= 125.
  13442. // Ping with FIN=0 - must be rejected
  13443. {
  13444. detail::BufferStream strm;
  13445. std::string frame;
  13446. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  13447. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13448. strm.write(frame.data(), frame.size());
  13449. ws::Opcode opcode;
  13450. std::string payload;
  13451. bool fin;
  13452. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13453. false, 1024));
  13454. }
  13455. // Close with FIN=0 - must be rejected
  13456. {
  13457. detail::BufferStream strm;
  13458. std::string frame;
  13459. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  13460. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  13461. strm.write(frame.data(), frame.size());
  13462. ws::Opcode opcode;
  13463. std::string payload;
  13464. bool fin;
  13465. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13466. false, 1024));
  13467. }
  13468. // Ping with payload_len=126 (extended length) - must be rejected
  13469. {
  13470. detail::BufferStream strm;
  13471. std::string frame;
  13472. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13473. frame += static_cast<char>(126); // payload_len=126 (>125)
  13474. frame += static_cast<char>(0x00); // extended length high byte
  13475. frame += static_cast<char>(126); // extended length low byte
  13476. frame += std::string(126, 'x');
  13477. strm.write(frame.data(), frame.size());
  13478. ws::Opcode opcode;
  13479. std::string payload;
  13480. bool fin;
  13481. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13482. false, 1024));
  13483. }
  13484. // Ping with FIN=1 and payload_len=125 - should succeed
  13485. {
  13486. detail::BufferStream strm;
  13487. std::string frame;
  13488. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  13489. frame += static_cast<char>(125); // payload_len=125
  13490. frame += std::string(125, 'x');
  13491. strm.write(frame.data(), frame.size());
  13492. ws::Opcode opcode;
  13493. std::string payload;
  13494. bool fin;
  13495. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13496. false, 1024));
  13497. EXPECT_EQ(ws::Opcode::Ping, opcode);
  13498. EXPECT_EQ(125u, payload.size());
  13499. EXPECT_TRUE(fin);
  13500. }
  13501. }
  13502. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  13503. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  13504. // length MUST be 0.
  13505. // MSB set - must be rejected
  13506. {
  13507. detail::BufferStream strm;
  13508. std::string frame;
  13509. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13510. frame += static_cast<char>(127); // 64-bit extended length
  13511. frame += static_cast<char>(0x80); // MSB set (invalid)
  13512. frame += std::string(7, '\0'); // remaining 7 bytes of length
  13513. strm.write(frame.data(), frame.size());
  13514. ws::Opcode opcode;
  13515. std::string payload;
  13516. bool fin;
  13517. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13518. false, 1024));
  13519. }
  13520. // MSB clear - should pass length parsing (will be rejected by max_len,
  13521. // but that's a different check; use a small length to verify)
  13522. {
  13523. detail::BufferStream strm;
  13524. std::string frame;
  13525. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  13526. frame += static_cast<char>(127); // 64-bit extended length
  13527. frame += std::string(7, '\0'); // high bytes = 0
  13528. frame += static_cast<char>(0x03); // length = 3
  13529. frame += "abc";
  13530. strm.write(frame.data(), frame.size());
  13531. ws::Opcode opcode;
  13532. std::string payload;
  13533. bool fin;
  13534. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13535. false, 1024));
  13536. EXPECT_EQ(ws::Opcode::Text, opcode);
  13537. EXPECT_EQ("abc", payload);
  13538. }
  13539. }
  13540. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  13541. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  13542. // Valid UTF-8
  13543. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  13544. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  13545. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  13546. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  13547. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  13548. // Invalid UTF-8
  13549. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  13550. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  13551. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  13552. EXPECT_FALSE(
  13553. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  13554. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  13555. }
  13556. TEST(WebSocketTest, ConnectAndDisconnect) {
  13557. Server svr;
  13558. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13559. std::string msg;
  13560. while (ws.read(msg)) {}
  13561. });
  13562. auto port = svr.bind_to_any_port(HOST);
  13563. std::thread t([&]() { svr.listen_after_bind(); });
  13564. svr.wait_until_ready();
  13565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  13566. ASSERT_TRUE(client.connect());
  13567. EXPECT_TRUE(client.is_open());
  13568. client.close();
  13569. EXPECT_FALSE(client.is_open());
  13570. svr.stop();
  13571. t.join();
  13572. }
  13573. TEST(WebSocketTest, ValidURL) {
  13574. ws::WebSocketClient ws1("ws://localhost:8080/path");
  13575. EXPECT_TRUE(ws1.is_valid());
  13576. ws::WebSocketClient ws2("ws://example.com/path");
  13577. EXPECT_TRUE(ws2.is_valid());
  13578. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  13579. EXPECT_TRUE(ws3.is_valid());
  13580. #ifdef CPPHTTPLIB_SSL_ENABLED
  13581. ws::WebSocketClient wss1("wss://example.com/path");
  13582. EXPECT_TRUE(wss1.is_valid());
  13583. ws::WebSocketClient wss2("wss://example.com:443/path");
  13584. EXPECT_TRUE(wss2.is_valid());
  13585. #endif
  13586. }
  13587. TEST(WebSocketTest, InvalidURL) {
  13588. // No scheme
  13589. ws::WebSocketClient ws1("localhost:8080/path");
  13590. EXPECT_FALSE(ws1.is_valid());
  13591. // No path
  13592. ws::WebSocketClient ws2("ws://localhost:8080");
  13593. EXPECT_FALSE(ws2.is_valid());
  13594. // Empty string
  13595. ws::WebSocketClient ws3("");
  13596. EXPECT_FALSE(ws3.is_valid());
  13597. // Missing host
  13598. ws::WebSocketClient ws4("ws://:8080/path");
  13599. EXPECT_FALSE(ws4.is_valid());
  13600. }
  13601. TEST(WebSocketTest, UnsupportedScheme) {
  13602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  13603. ws::WebSocketClient ws1("http://localhost:8080/path");
  13604. EXPECT_FALSE(ws1.is_valid());
  13605. ws::WebSocketClient ws2("https://localhost:8080/path");
  13606. EXPECT_FALSE(ws2.is_valid());
  13607. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  13608. EXPECT_FALSE(ws3.is_valid());
  13609. #else
  13610. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  13611. std::invalid_argument);
  13612. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  13613. std::invalid_argument);
  13614. #endif
  13615. }
  13616. TEST(WebSocketTest, ConnectWhenInvalid) {
  13617. ws::WebSocketClient ws("not a valid url");
  13618. EXPECT_FALSE(ws.is_valid());
  13619. EXPECT_FALSE(ws.connect());
  13620. }
  13621. TEST(WebSocketTest, DefaultPort) {
  13622. ws::WebSocketClient ws1("ws://example.com/path");
  13623. EXPECT_TRUE(ws1.is_valid());
  13624. // ws:// defaults to port 80 (verified by successful parse)
  13625. #ifdef CPPHTTPLIB_SSL_ENABLED
  13626. ws::WebSocketClient ws2("wss://example.com/path");
  13627. EXPECT_TRUE(ws2.is_valid());
  13628. // wss:// defaults to port 443 (verified by successful parse)
  13629. #endif
  13630. }
  13631. TEST(WebSocketTest, IPv6LiteralAddress) {
  13632. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  13633. EXPECT_TRUE(ws1.is_valid());
  13634. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  13635. EXPECT_TRUE(ws2.is_valid());
  13636. }
  13637. TEST(WebSocketTest, ComplexPath) {
  13638. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  13639. EXPECT_TRUE(ws1.is_valid());
  13640. ws::WebSocketClient ws2("ws://localhost:8080/");
  13641. EXPECT_TRUE(ws2.is_valid());
  13642. }
  13643. class WebSocketIntegrationTest : public ::testing::Test {
  13644. protected:
  13645. void SetUp() override {
  13646. server_ = httplib::detail::make_unique<Server>();
  13647. setup_server();
  13648. start_server();
  13649. }
  13650. void TearDown() override {
  13651. server_->stop();
  13652. if (server_thread_.joinable()) { server_thread_.join(); }
  13653. }
  13654. void setup_server() {
  13655. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13656. std::string msg;
  13657. ws::ReadResult ret;
  13658. while ((ret = ws.read(msg))) {
  13659. if (ret == ws::Binary) {
  13660. ws.send(msg.data(), msg.size());
  13661. } else {
  13662. ws.send(msg);
  13663. }
  13664. }
  13665. });
  13666. server_->WebSocket("/ws-echo-string",
  13667. [](const Request &, ws::WebSocket &ws) {
  13668. std::string msg;
  13669. while (ws.read(msg)) {
  13670. ws.send("echo: " + msg);
  13671. }
  13672. });
  13673. server_->WebSocket(
  13674. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  13675. // Echo back request metadata
  13676. ws.send("path:" + req.path);
  13677. ws.send("header:" + req.get_header_value("X-Test-Header"));
  13678. std::string msg;
  13679. while (ws.read(msg)) {}
  13680. });
  13681. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  13682. std::string msg;
  13683. ws.read(msg); // wait for a message
  13684. ws.close();
  13685. });
  13686. server_->WebSocket("/ws-close-status",
  13687. [](const Request &, ws::WebSocket &ws) {
  13688. std::string msg;
  13689. ws.read(msg); // wait for a message
  13690. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  13691. });
  13692. server_->WebSocket(
  13693. "/ws-subprotocol",
  13694. [](const Request &, ws::WebSocket &ws) {
  13695. std::string msg;
  13696. while (ws.read(msg)) {
  13697. ws.send(msg);
  13698. }
  13699. },
  13700. [](const std::vector<std::string> &protocols) -> std::string {
  13701. for (const auto &p : protocols) {
  13702. if (p == "graphql-ws") { return p; }
  13703. }
  13704. return "";
  13705. });
  13706. }
  13707. void start_server() {
  13708. port_ = server_->bind_to_any_port(HOST);
  13709. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13710. server_->wait_until_ready();
  13711. }
  13712. std::unique_ptr<Server> server_;
  13713. std::thread server_thread_;
  13714. int port_ = 0;
  13715. };
  13716. TEST_F(WebSocketIntegrationTest, TextEcho) {
  13717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13718. "/ws-echo");
  13719. ASSERT_TRUE(client.connect());
  13720. ASSERT_TRUE(client.is_open());
  13721. ASSERT_TRUE(client.send("Hello WebSocket"));
  13722. std::string msg;
  13723. EXPECT_EQ(ws::Text, client.read(msg));
  13724. EXPECT_EQ("Hello WebSocket", msg);
  13725. client.close();
  13726. }
  13727. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  13728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13729. "/ws-echo");
  13730. ASSERT_TRUE(client.connect());
  13731. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  13732. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  13733. std::string msg;
  13734. EXPECT_EQ(ws::Binary, client.read(msg));
  13735. EXPECT_EQ(binary_data, msg);
  13736. client.close();
  13737. }
  13738. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  13739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13740. "/ws-echo");
  13741. ASSERT_TRUE(client.connect());
  13742. for (int i = 0; i < 10; i++) {
  13743. auto text = "message " + std::to_string(i);
  13744. ASSERT_TRUE(client.send(text));
  13745. std::string msg;
  13746. ASSERT_TRUE(client.read(msg));
  13747. EXPECT_EQ(text, msg);
  13748. }
  13749. client.close();
  13750. }
  13751. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  13752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13753. "/ws-close");
  13754. ASSERT_TRUE(client.connect());
  13755. // Send a message to trigger the server to close
  13756. ASSERT_TRUE(client.send("trigger close"));
  13757. // The server will close, so read should return false
  13758. std::string msg;
  13759. EXPECT_FALSE(client.read(msg));
  13760. EXPECT_FALSE(client.is_open());
  13761. }
  13762. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  13763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13764. "/ws-echo");
  13765. ASSERT_TRUE(client.connect());
  13766. // 128KB message
  13767. std::string large_data(128 * 1024, 'X');
  13768. ASSERT_TRUE(client.send(large_data));
  13769. std::string msg;
  13770. ASSERT_TRUE(client.read(msg));
  13771. EXPECT_EQ(large_data, msg);
  13772. client.close();
  13773. }
  13774. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  13775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13776. "/ws-echo");
  13777. ASSERT_TRUE(client.connect());
  13778. const int num_threads = 4;
  13779. std::vector<std::thread> threads;
  13780. std::atomic<int> send_count{0};
  13781. for (int t = 0; t < num_threads; t++) {
  13782. threads.emplace_back([&client, &send_count, t]() {
  13783. for (int i = 0; i < 5; i++) {
  13784. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  13785. if (client.send(text)) { send_count++; }
  13786. }
  13787. });
  13788. }
  13789. for (auto &th : threads) {
  13790. th.join();
  13791. }
  13792. int received = 0;
  13793. std::string msg;
  13794. while (received < send_count.load()) {
  13795. if (!client.read(msg)) { break; }
  13796. received++;
  13797. }
  13798. EXPECT_EQ(send_count.load(), received);
  13799. client.close();
  13800. }
  13801. TEST_F(WebSocketIntegrationTest, ReadString) {
  13802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13803. "/ws-echo-string");
  13804. ASSERT_TRUE(client.connect());
  13805. ASSERT_TRUE(client.send("hello"));
  13806. std::string msg;
  13807. ASSERT_TRUE(client.read(msg));
  13808. EXPECT_EQ("echo: hello", msg);
  13809. ASSERT_TRUE(client.send("world"));
  13810. ASSERT_TRUE(client.read(msg));
  13811. EXPECT_EQ("echo: world", msg);
  13812. client.close();
  13813. }
  13814. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  13815. Headers headers = {{"X-Test-Header", "test-value"}};
  13816. ws::WebSocketClient client(
  13817. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  13818. ASSERT_TRUE(client.connect());
  13819. std::string msg;
  13820. ASSERT_TRUE(client.read(msg));
  13821. EXPECT_EQ("path:/ws-request-info", msg);
  13822. ASSERT_TRUE(client.read(msg));
  13823. EXPECT_EQ("header:test-value", msg);
  13824. client.close();
  13825. }
  13826. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  13827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13828. "/ws-echo");
  13829. client.set_read_timeout(1, 0); // 1 second
  13830. ASSERT_TRUE(client.connect());
  13831. // Don't send anything — server echo handler waits for a message,
  13832. // so read() should time out and return false.
  13833. std::string msg;
  13834. EXPECT_FALSE(client.read(msg));
  13835. }
  13836. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  13837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13838. "/ws-echo");
  13839. client.set_read_timeout(5, 0);
  13840. ASSERT_TRUE(client.connect());
  13841. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13842. // The server should reject it and close the connection.
  13843. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  13844. client.send(oversized);
  13845. // The server's read() should have failed due to payload limit,
  13846. // so our read() should return false (connection closed).
  13847. std::string msg;
  13848. EXPECT_FALSE(client.read(msg));
  13849. }
  13850. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  13851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13852. "/ws-echo");
  13853. client.set_read_timeout(10, 0);
  13854. ASSERT_TRUE(client.connect());
  13855. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  13856. // This should succeed.
  13857. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  13858. ASSERT_TRUE(client.send(at_limit));
  13859. std::string msg;
  13860. ASSERT_TRUE(client.read(msg));
  13861. EXPECT_EQ(at_limit.size(), msg.size());
  13862. client.close();
  13863. }
  13864. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  13865. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13866. "/nonexistent");
  13867. EXPECT_FALSE(client.connect());
  13868. EXPECT_FALSE(client.is_open());
  13869. }
  13870. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  13871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13872. "/ws-echo");
  13873. ASSERT_TRUE(client.connect());
  13874. ASSERT_TRUE(client.send(""));
  13875. std::string msg;
  13876. EXPECT_EQ(ws::Text, client.read(msg));
  13877. EXPECT_EQ("", msg);
  13878. client.close();
  13879. }
  13880. TEST_F(WebSocketIntegrationTest, Reconnect) {
  13881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13882. "/ws-echo");
  13883. // First connection
  13884. ASSERT_TRUE(client.connect());
  13885. ASSERT_TRUE(client.send("first"));
  13886. std::string msg;
  13887. ASSERT_TRUE(client.read(msg));
  13888. EXPECT_EQ("first", msg);
  13889. client.close();
  13890. EXPECT_FALSE(client.is_open());
  13891. // Reconnect using the same client object
  13892. ASSERT_TRUE(client.connect());
  13893. ASSERT_TRUE(client.is_open());
  13894. ASSERT_TRUE(client.send("second"));
  13895. ASSERT_TRUE(client.read(msg));
  13896. EXPECT_EQ("second", msg);
  13897. client.close();
  13898. }
  13899. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  13900. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13901. "/ws-close-status");
  13902. ASSERT_TRUE(client.connect());
  13903. // Trigger the server to close with GoingAway status
  13904. ASSERT_TRUE(client.send("trigger"));
  13905. // read() should return false after receiving the close frame
  13906. std::string msg;
  13907. EXPECT_FALSE(client.read(msg));
  13908. EXPECT_FALSE(client.is_open());
  13909. }
  13910. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  13911. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13912. "/ws-echo");
  13913. ASSERT_TRUE(client.connect());
  13914. client.close(ws::CloseStatus::GoingAway, "client leaving");
  13915. EXPECT_FALSE(client.is_open());
  13916. }
  13917. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  13918. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  13919. ws::WebSocketClient client(
  13920. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13921. ASSERT_TRUE(client.connect());
  13922. // Server should have selected graphql-ws
  13923. EXPECT_EQ("graphql-ws", client.subprotocol());
  13924. client.close();
  13925. }
  13926. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  13927. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  13928. ws::WebSocketClient client(
  13929. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  13930. ASSERT_TRUE(client.connect());
  13931. // Server should not have selected any subprotocol
  13932. EXPECT_TRUE(client.subprotocol().empty());
  13933. client.close();
  13934. }
  13935. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  13936. // Connect without requesting any subprotocol
  13937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  13938. "/ws-subprotocol");
  13939. ASSERT_TRUE(client.connect());
  13940. EXPECT_TRUE(client.subprotocol().empty());
  13941. client.close();
  13942. }
  13943. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  13944. Server svr;
  13945. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  13946. if (!req.has_header("Authorization")) {
  13947. res.status = StatusCode::Unauthorized_401;
  13948. res.set_content("Unauthorized", "text/plain");
  13949. return Server::HandlerResponse::Handled;
  13950. }
  13951. return Server::HandlerResponse::Unhandled;
  13952. });
  13953. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  13954. std::string msg;
  13955. while (ws.read(msg)) {
  13956. ws.send(msg);
  13957. }
  13958. });
  13959. auto port = svr.bind_to_any_port("localhost");
  13960. std::thread t([&]() { svr.listen_after_bind(); });
  13961. svr.wait_until_ready();
  13962. // Without Authorization header - should be rejected before upgrade
  13963. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  13964. EXPECT_FALSE(client1.connect());
  13965. // With Authorization header - should succeed
  13966. Headers headers = {{"Authorization", "Bearer token123"}};
  13967. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  13968. headers);
  13969. ASSERT_TRUE(client2.connect());
  13970. ASSERT_TRUE(client2.send("hello"));
  13971. std::string msg;
  13972. ASSERT_TRUE(client2.read(msg));
  13973. EXPECT_EQ("hello", msg);
  13974. client2.close();
  13975. svr.stop();
  13976. t.join();
  13977. }
  13978. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13979. class WebSocketSSLIntegrationTest : public ::testing::Test {
  13980. protected:
  13981. void SetUp() override {
  13982. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  13983. SERVER_PRIVATE_KEY_FILE);
  13984. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  13985. std::string msg;
  13986. ws::ReadResult ret;
  13987. while ((ret = ws.read(msg))) {
  13988. if (ret == ws::Binary) {
  13989. ws.send(msg.data(), msg.size());
  13990. } else {
  13991. ws.send(msg);
  13992. }
  13993. }
  13994. });
  13995. port_ = server_->bind_to_any_port(HOST);
  13996. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13997. server_->wait_until_ready();
  13998. }
  13999. void TearDown() override {
  14000. server_->stop();
  14001. if (server_thread_.joinable()) { server_thread_.join(); }
  14002. }
  14003. std::unique_ptr<SSLServer> server_;
  14004. std::thread server_thread_;
  14005. int port_ = 0;
  14006. };
  14007. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14008. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14009. "/ws-echo");
  14010. client.enable_server_certificate_verification(false);
  14011. ASSERT_TRUE(client.connect());
  14012. ASSERT_TRUE(client.is_open());
  14013. ASSERT_TRUE(client.send("Hello WSS"));
  14014. std::string msg;
  14015. EXPECT_EQ(ws::Text, client.read(msg));
  14016. EXPECT_EQ("Hello WSS", msg);
  14017. client.close();
  14018. }
  14019. #endif